Merge branch '79-students-tags-generation' into 'dev'

Resolve "Генерация периодических задач по тегам"

Closes #79

See merge request romanov73/ng-tracker!80
This commit is contained in:
Anton Romanov 2019-05-16 03:30:46 +00:00
commit 19a6b45cf9
15 changed files with 434 additions and 3 deletions

View File

@ -54,4 +54,10 @@ public class DateUtils {
cal.add(Calendar.DAY_OF_MONTH, count);
return cal.getTime();
}
public static Date addYears(Date date, int count) {
Calendar cal = getCalendar(date);
cal.add(Calendar.YEAR, count);
return cal.getTime();
}
}

View File

@ -64,6 +64,7 @@ public class GrantNotificationService {
Map<String, Object> variables = ImmutableMap.of("grant", grant, "oldLeader", oldLeader);
sendForAllAuthors(variables, grant, TEMPLATE_LEADER_CHANGED, String.format(TITLE_LEADER_CHANGED, grant.getTitle()));
}
private void sendForAllAuthors(Map<String, Object> variables, Grant grant, String template, String title) {
Set<User> allAuthors = grant.getAuthors();
allAuthors.forEach(author -> mailService.sendEmailFromTemplate(variables, author, template, title));

View File

@ -0,0 +1,49 @@
package ru.ulstu.students.model;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
@Entity
@Table(name = "scheduler")
public class Scheduler extends BaseEntity {
@OneToOne(optional = false)
@JoinColumn(name = "task_id")
private Task task;
@Temporal(value = TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
public Scheduler() {
}
public Scheduler(Task task, Date date) {
this.task = task;
this.date = date;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}

View File

@ -0,0 +1,11 @@
package ru.ulstu.students.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.students.model.Scheduler;
import ru.ulstu.students.model.Task;
public interface SchedulerRepository extends JpaRepository<Scheduler, Integer> {
Scheduler findOneByTask(Task task);
}

View File

@ -6,6 +6,7 @@ import org.springframework.data.repository.query.Param;
import ru.ulstu.students.model.Task;
import ru.ulstu.tags.model.Tag;
import java.util.Date;
import java.util.List;
public interface TaskRepository extends JpaRepository<Task, Integer> {
@ -15,4 +16,12 @@ public interface TaskRepository extends JpaRepository<Task, Integer> {
@Query("SELECT t FROM Task t WHERE (t.status = :status OR :status IS NULL) AND (:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY create_date ASC")
List<Task> filterOld(@Param("status") Task.TaskStatus status, @Param("tag") Tag tag);
@Query("SELECT t FROM Task t WHERE(:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY create_date DESC")
List<Task> findByTag(@Param("tag") Tag tag);
@Query("SELECT t FROM Task t WHERE (t.createDate >= :date) ORDER BY create_date DESC")
List<Task> findAllYear(@Param("date") Date date);
}

View File

@ -0,0 +1,116 @@
package ru.ulstu.students.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.students.model.Scheduler;
import ru.ulstu.students.model.Task;
import ru.ulstu.students.repository.SchedulerRepository;
import ru.ulstu.tags.model.Tag;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class SchedulerService {
private final TaskService taskService;
private final SchedulerRepository schedulerRepository;
public SchedulerService(TaskService taskService, SchedulerRepository schedulerRepository) {
this.taskService = taskService;
this.schedulerRepository = schedulerRepository;
}
private void save(Tag tag) {
List<Task> taskList = taskService.findTasksByTag(tag);
create(taskList.get(0));
}
@Transactional
private Scheduler create(Task task) {
Scheduler scheduler = new Scheduler(task, task.getDeadlines().get(task.getDeadlines().size() - 1).getDate());
return schedulerRepository.save(scheduler);
}
@Transactional
private void delete(Integer schedulerId) {
if (schedulerRepository.exists(schedulerId)) {
schedulerRepository.delete(schedulerId);
}
}
public void checkPlanToday() {
List<Scheduler> schedulerList = schedulerRepository.findAll();
if (!schedulerList.isEmpty()) {
doTodayPlanIfNeed(schedulerList);
schedulerList = schedulerRepository.findAll();
}
checkNewPlan(schedulerList);
}
private void checkNewPlan(List<Scheduler> schedulerList) {
Set<Tag> tags = taskService.checkRepeatingTags(true);
Set<Tag> newTags = null;
if (!schedulerList.isEmpty()) {
newTags = checkNewTags(tags, schedulerList);
} else {
if (!tags.isEmpty()) {
newTags = tags;
}
}
if (newTags != null) {
newTags.forEach(tag -> {
if (!hasNewTag(tag, schedulerList)) {
save(tag);
Task task = taskService.findTasksByTag(tag).get(0);
schedulerList.add(new Scheduler(task, task.getDeadlines().get(task.getDeadlines().size() - 1).getDate()));
}
});
}
}
private boolean hasNewTag(Tag tag, List<Scheduler> schedulerList) {
return schedulerList
.stream()
.anyMatch(scheduler -> scheduler.getTask().getTags().contains(tag));
}
private Set<Tag> checkNewTags(Set<Tag> tags, List<Scheduler> schedulerList) {
Set<Tag> newTags = tags
.stream()
.filter(tag -> schedulerList
.stream()
.anyMatch(scheduler ->
!scheduler.getTask().getTags().contains(tag)))
.collect(Collectors.toSet());
if (!newTags.isEmpty()) {
return newTags;
}
return null;
}
private void doTodayPlanIfNeed(List<Scheduler> schedulerList) {
List<Scheduler> plan = schedulerList
.stream()
.filter(scheduler -> scheduler.getDate().before(new Date()))
.collect(Collectors.toList());
doToday(plan);
}
private void doToday(List<Scheduler> plan) {
plan.forEach(scheduler -> {
taskService.createPeriodTask(scheduler);
delete(scheduler.getId());
});
}
}

View File

@ -0,0 +1,32 @@
package ru.ulstu.students.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class TaskGenerationService {
private final Logger log = LoggerFactory.getLogger(TaskGenerationService.class);
private final TaskService taskService;
private final SchedulerService schedulerService;
public TaskGenerationService(TaskService taskService, SchedulerService schedulerService) {
this.taskService = taskService;
this.schedulerService = schedulerService;
}
@Scheduled(cron = "0 0 0 * * ?", zone = "Europe/Samara")
public void generateTasks() {
log.debug("SchedulerService.checkPlanToday started");
schedulerService.checkPlanToday();
log.debug("SchedulerService.checkPlanToday finished");
log.debug("TaskService.generateYearTasks started");
taskService.generateYearTasks();
log.debug("TaskService.generateYearTasks finished");
}
}

View File

@ -4,19 +4,29 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.students.model.Scheduler;
import ru.ulstu.students.model.Task;
import ru.ulstu.students.model.TaskDto;
import ru.ulstu.students.model.TaskFilterDto;
import ru.ulstu.students.repository.SchedulerRepository;
import ru.ulstu.students.repository.TaskRepository;
import ru.ulstu.tags.model.Tag;
import ru.ulstu.tags.service.TagService;
import ru.ulstu.timeline.service.EventService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import static org.springframework.util.ObjectUtils.isEmpty;
import static ru.ulstu.core.util.StreamApiUtils.convert;
@ -28,16 +38,19 @@ public class TaskService {
private final static int MAX_DISPLAY_SIZE = 40;
private final TaskRepository taskRepository;
private final SchedulerRepository schedulerRepository;
private final DeadlineService deadlineService;
private final TagService tagService;
private final EventService eventService;
public TaskService(TaskRepository taskRepository,
DeadlineService deadlineService, TagService tagService, EventService eventService) {
DeadlineService deadlineService, TagService tagService, SchedulerRepository schedulerRepository, EventService eventService) {
this.taskRepository = taskRepository;
this.deadlineService = deadlineService;
this.tagService = tagService;
this.eventService = eventService;
this.schedulerRepository = schedulerRepository;
}
public List<Task> findAll() {
@ -97,6 +110,11 @@ public class TaskService {
@Transactional
public void delete(Integer taskId) throws IOException {
if (taskRepository.exists(taskId)) {
Task scheduleTask = taskRepository.findOne(taskId);
Scheduler sch = schedulerRepository.findOneByTask(scheduleTask);
if (sch != null) {
schedulerRepository.delete(sch.getId());
}
taskRepository.delete(taskId);
}
@ -110,6 +128,110 @@ public class TaskService {
}
}
public 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) {
Task newTask = new Task();
copyMainPart(newTask, task);
Calendar cal1 = DateUtils.getCalendar(newTask.getCreateDate());
Calendar cal2 = DateUtils.getCalendar(task.getCreateDate());
Integer interval = cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR);
newTask.setDeadlines(newDatesDeadlines(task.getDeadlines(), interval));
return newTask;
}
private List<Deadline> newDatesDeadlines(List<Deadline> deadlines, Integer interval) {
return deadlines
.stream()
.map(deadline -> {
Deadline newDeadline = new Deadline();
Date newDate = DateUtils.addDays(deadline.getDate(), interval);
newDeadline.setDescription(deadline.getDescription());
newDeadline.setDate(newDate);
return deadlineService.create(newDeadline);
}).collect(Collectors.toList());
}
public Task copyTaskWithNewYear(Task task) {
Task newTask = new Task();
copyMainPart(newTask, task);
newTask.setDeadlines(newYearDeadlines(task.getDeadlines()));
return newTask;
}
private List<Deadline> newYearDeadlines(List<Deadline> deadlines) {
return deadlines
.stream()
.map(deadline -> {
Deadline newDeadline = new Deadline();
newDeadline.setDescription(deadline.getDescription());
newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1));
return deadlineService.create(newDeadline);
}).collect(Collectors.toList());
}
private boolean equalsDate(Task task) {
Calendar taskDate = DateUtils.getCalendar(task.getCreateDate());
Calendar nowDate = DateUtils.getCalendar(new Date());
return (taskDate.get(Calendar.DAY_OF_MONTH) == nowDate.get(Calendar.DAY_OF_MONTH) &&
taskDate.get(Calendar.MONTH) + 1 == nowDate.get(Calendar.MONTH) + 1 &&
taskDate.get(Calendar.YEAR) + 1 == nowDate.get(Calendar.YEAR));
}
@Transactional
public void generateYearTasks() {
Set<Tag> tags = checkRepeatingTags(false);
List<Task> tasks = new ArrayList<>();
tags.forEach(tag -> {
Task singleTask = findTasksByTag(tag).get(0);
if (equalsDate(singleTask)) {
if (!tasks.contains(singleTask)) {
tasks.add(singleTask);
}
}
});
if (tasks != null) {
tasks.forEach(task -> {
Task newTask = copyTaskWithNewYear(task);
taskRepository.save(newTask);
});
}
}
@Transactional
public Set<Tag> checkRepeatingTags(Boolean createPeriodTask) { //param: false = year task; true = period task
Map<Tag, Long> tagsCount = new TreeMap<>();
List<Tag> tags = tagService.getTags();
List<Task> tasks = taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)));
tags.forEach(tag ->
tagsCount.put(tag, tasks
.stream()
.filter(task -> task.getTags().contains(tag))
.count()));
if (!createPeriodTask) {
return tagsCount
.entrySet()
.stream()
.filter(tagLongEntry -> tagLongEntry.getValue() == 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
.keySet();
} else {
return tagsCount
.entrySet()
.stream()
.filter(tagLongEntry -> tagLongEntry.getValue() >= 2)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
.keySet();
}
}
public List<Task.TaskStatus> getTaskStatuses() {
return Arrays.asList(Task.TaskStatus.values());
}
@ -118,4 +240,13 @@ public class TaskService {
return tagService.getTags();
}
public List<Task> findTasksByTag(Tag tag) {
return taskRepository.findByTag(tag);
}
@Transactional
public void createPeriodTask(Scheduler scheduler) {
Task newTask = copyTaskWithNewDates(scheduler.getTask());
taskRepository.save(newTask);
}
}

View File

@ -9,6 +9,7 @@ import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "tag")
@ -41,4 +42,21 @@ public class Tag extends BaseEntity {
public void setTagName(String tagName) {
this.tagName = tagName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tag tag = (Tag) o;
return tagName.equals(tag.tagName);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), tagName);
}
}

View File

@ -2,6 +2,7 @@
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="tanya" id="20190505_000000-1">
<addColumn tableName="event">
<column name="grant_id" type="integer"/>

View File

@ -0,0 +1,25 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="nastya" id="20190505_000001-1">
<createTable tableName="scheduler">
<column name="id" type="integer">
<constraints nullable="false"/>
</column>
<column name="task_id" type="integer">
<constraints nullable="false"/>
</column>
<column name="date" type="timestamp">
<constraints nullable="false"/>
</column>
<column name="version" type="integer"/>
</createTable>
<addPrimaryKey columnNames="id" constraintName="pk_scheduler" tableName="scheduler"/>
<addForeignKeyConstraint baseTableName="scheduler" baseColumnNames="task_id"
constraintName="fk_scheduler_task_id" referencedTableName="task"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -38,6 +38,7 @@
<include file="db/changelog-20190428_000000-schema.xml"/>
<include file="db/changelog-20190430_000000-schema.xml"/>
<include file="db/changelog-20190505_000000-schema.xml"/>
<include file="db/changelog-20190505_000001-schema.xml"/>
<include file="db/changelog-20190507_000000-schema.xml"/>
<include file="db/changelog-20190507_000001-schema.xml"/>
<include file="db/changelog-20190511_000000-schema.xml"/>

View File

@ -38,6 +38,29 @@
width: auto;
max-width: inherit;
}
.tag-info{
font-size: 10px;
color: white;
padding: 5px 15px;
background-color: black;
display: none;
margin-left: 5px;
border-radius: 5px;
opacity: 0.8;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.fa-question-circle{
font-size: 15px;
color: #212529;
cursor:pointer;
}
.fa-question-circle:hover .tag-info{
display:inline-block;
}
.task-row{

View File

@ -19,8 +19,16 @@ $(document).ready(function () {
$("#input-tag").keyup(function (event) {
if(event.keyCode == 13 || event.keyCode == 188) {
if(event.keyCode == 13) {
var tagNumber = $("#tags .tag").length;
if(tagNumber > 0) {
tagNumber = $("#tags .tag").last()
.children('input')
.attr("name")
.split(']')[0]
.split('[')[1];
tagNumber++;
}
var tagName = $.trim($(this).val());
var addTag = true;
// проверка, добавлен ли этот тег

View File

@ -52,7 +52,7 @@
</div>
<div class="form-group">
<label for="tags">Теги:</label>
<label for="tags">Теги: <i class="fa fa-question-circle"><span class="tag-info">Для ввода тега наберите слово (или словосочетание) и нажмите Enter </span></i></label>
<div class="tags-container" id="tags">
<div class="tag" th:each="tag, rowStat : *{tags}">
<input type="hidden" th:field="*{tags[__${rowStat.index}__].id}"/>