diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000..c19504c --- /dev/null +++ b/.jshintrc @@ -0,0 +1,165 @@ +{ + // JSHint Default Configuration File (as on JSHint website) + // See http://jshint.com/docs/ for more details + + "maxerr": 50, + // {int} Maximum error before stopping + + // Enforcing + "bitwise": true, + // true: Prohibit bitwise operators (&, |, ^, etc.) + "camelcase": false, + // true: Identifiers must be in camelCase + "curly": true, + // true: Require {} for every new block or scope + "eqeqeq": true, + // true: Require triple equals (===) for comparison + "forin": true, + // true: Require filtering for..in loops with obj.hasOwnProperty() + "freeze": true, + // true: prohibits overwriting prototypes of native objects such as Array, Date etc. + "immed": false, + // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` + "latedef": false, + // true: Require variables/functions to be defined before being used + "newcap": false, + // true: Require capitalization of all constructor functions e.g. `new F()` + "noarg": true, + // true: Prohibit use of `arguments.caller` and `arguments.callee` + "noempty": true, + // true: Prohibit use of empty blocks + "nonbsp": true, + // true: Prohibit "non-breaking whitespace" characters. + "nonew": false, + // true: Prohibit use of constructors for side-effects (without assignment) + "plusplus": false, + // true: Prohibit use of `++` and `--` + "quotmark": false, + // Quotation mark consistency: + // false : do nothing (default) + // true : ensure whatever is used is consistent + // "single" : require single quotes + // "double" : require double quotes + "undef": true, + // true: Require all non-global variables to be declared (prevents global leaks) + "unused": true, + // Unused variables: + // true : all variables, last function parameter + // "vars" : all variables only + // "strict" : all variables, all function parameters + "strict": false, + // true: Requires all functions run in ES5 Strict Mode + "maxparams": false, + // {int} Max number of formal params allowed per function + "maxdepth": false, + // {int} Max depth of nested blocks (within functions) + "maxstatements": false, + // {int} Max number statements per function + "maxcomplexity": false, + // {int} Max cyclomatic complexity per function + "maxlen": false, + // {int} Max number of characters per line + "varstmt": false, + // true: Disallow any var statements. Only `let` and `const` are allowed. + + // Relaxing + "asi": false, + // true: Tolerate Automatic Semicolon Insertion (no semicolons) + "boss": false, + // true: Tolerate assignments where comparisons would be expected + "debug": false, + // true: Allow debugger statements e.g. browser breakpoints. + "eqnull": true, + // true: Tolerate use of `== null` + "esversion": 5, + // {int} Specify the ECMAScript version to which the code must adhere. + "moz": false, + // true: Allow Mozilla specific syntax (extends and overrides esnext features) + // (ex: `for each`, multiple try/catch, function expression…) + "evil": false, + // true: Tolerate use of `eval` and `new Function()` + "expr": false, + // true: Tolerate `ExpressionStatement` as Programs + "funcscope": false, + // true: Tolerate defining variables inside control statements + "globalstrict": false, + // true: Allow global "use strict" (also enables 'strict') + "iterator": false, + // true: Tolerate using the `__iterator__` property + "lastsemic": false, + // true: Tolerate omitting a semicolon for the last statement of a 1-line block + "laxbreak": false, + // true: Tolerate possibly unsafe line breakings + "laxcomma": false, + // true: Tolerate comma-first style coding + "loopfunc": false, + // true: Tolerate functions being defined in loops + "multistr": false, + // true: Tolerate multi-line strings + "noyield": false, + // true: Tolerate generator functions with no yield statement in them. + "notypeof": false, + // true: Tolerate invalid typeof operator values + "proto": false, + // true: Tolerate using the `__proto__` property + "scripturl": false, + // true: Tolerate script-targeted URLs + "shadow": false, + // true: Allows re-define variables later in code e.g. `var x=1; x=2;` + "sub": false, + // true: Tolerate using `[]` notation when it can still be expressed in dot notation + "supernew": false, + // true: Tolerate `new function () { ... };` and `new Object;` + "validthis": false, + // true: Tolerate using this in a non-constructor function + + // Environments + "browser": true, + // Web Browser (window, document, etc) + "browserify": false, + // Browserify (node.js code in the browser) + "couch": false, + // CouchDB + "devel": true, + // Development/debugging (alert, confirm, etc) + "dojo": false, + // Dojo Toolkit + "jasmine": false, + // Jasmine + "jquery": true, + // jQuery + "mocha": false, + // Mocha + "mootools": false, + // MooTools + "node": false, + // Node.js + "nonstandard": false, + // Widely adopted globals (escape, unescape, etc) + "phantom": false, + // PhantomJS + "prototypejs": false, + // Prototype and Scriptaculous + "qunit": false, + // QUnit + "rhino": false, + // Rhino + "shelljs": false, + // ShellJS + "typed": false, + // Globals for typed array constructions + "worker": false, + // Web Workers + "wsh": false, + // Windows Scripting Host + "yui": false, + // Yahoo User Interface + + // Custom Globals + "globals": { + "spc": false, + "spsn": false, + "spconf": false + } + // additional predefined global variables +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 4fb0185..232cd74 100644 --- a/build.gradle +++ b/build.gradle @@ -117,11 +117,16 @@ dependencies { compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7' - compile group: 'org.webjars', name: 'bootstrap', version: '4.1.0' - compile group: 'org.webjars', name: 'bootstrap-select', version: '1.13.3' - compile group: 'org.webjars', name: 'jquery', version: '3.3.1-1' - compile group: 'org.webjars.npm', name: 'jquery.easing', version: '1.4.1' compile group: 'org.webjars', name: 'font-awesome', version: '4.7.0' + compile group: 'org.webjars', name: 'bootstrap', version: '4.1.3' + compile group: 'org.webjars.npm', name: 'vue', version: '2.6.9' + compile group: 'org.webjars.npm', name: 'vuex', version: '3.1.0' + compile group: 'org.webjars.npm', name: 'vue-router', version: '3.0.2' + compile group: 'org.webjars.npm', name: 'vue-multiselect', version: '2.0.2' + compile group: 'org.webjars.npm', name: 'vue-moment', version: '4.0.0' + compile group: 'org.webjars.npm', name: 'http-vue-loader', version: '1.3.5' + compile group: 'org.webjars.npm', name: 'axios', version: '0.18.0' + compile group: 'org.webjars.npm', name: 'vee-validate', version: '2.1.7' compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.0' compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0' diff --git a/deploy/run_psql.sh b/deploy/run_psql.sh new file mode 100644 index 0000000..5532e93 --- /dev/null +++ b/deploy/run_psql.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# to run this execute +# export PSQL_HOME_DIR=/home/user/pgsql-10.5.1; bash ./deploy/run_psql.sh +PSQL_DATA_DIR=./ng-tracker +PSQL_USER_NAME=postgres +PSQL_DB_NAME=ng-tracker +if [ ! -d "$PSQL_HOME_DIR" ]; then + echo "Directory $PSQL_HOME_DIR is not exists" + exit 0 +fi +cd "$PSQL_HOME_DIR" +if [ ! -d "$PSQL_DATA_DIR" ]; then + ./bin/initdb "$PSQL_DATA_DIR" + ./bin/pg_ctl -D "$PSQL_DATA_DIR" start + ./bin/createuser -s "$PSQL_USER_NAME" + ./bin/createdb -O "$PSQL_USER_NAME" "$PSQL_DB_NAME" +else + PSQL_STATUS=$(./bin/pg_ctl -D "$PSQL_DATA_DIR" status | wc -l) + if [ $PSQL_STATUS -eq 1 ]; then + ./bin/pg_ctl -D "$PSQL_DATA_DIR" start + else + ./bin/pg_ctl -D "$PSQL_DATA_DIR" stop + fi +fi diff --git a/src/main/java/ru/ulstu/activity/api/ActivityController.java b/src/main/java/ru/ulstu/activity/api/ActivityController.java new file mode 100644 index 0000000..0fd5d1e --- /dev/null +++ b/src/main/java/ru/ulstu/activity/api/ActivityController.java @@ -0,0 +1,31 @@ +package ru.ulstu.activity.api; + +import ru.ulstu.activity.api.model.ActivityDashboardDto; +import ru.ulstu.activity.api.model.ActivityDto; +import ru.ulstu.activity.api.model.ActivityListDto; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.core.model.response.Response; + +/** + * Базовый API для контролеров активностей + * + * @param + * @param + * @param + */ +public interface ActivityController { + + Response> getList(int offset, int count); + + Response> getDashboard(int offset, int count); + + Response get(Integer entityId); + + Response create(ENTITYDTO entity); + + Response update(ENTITYDTO entity); + + Response delete(Integer entityId); + + void ping(int entityId); +} diff --git a/src/main/java/ru/ulstu/activity/api/ActivityRepository.java b/src/main/java/ru/ulstu/activity/api/ActivityRepository.java new file mode 100644 index 0000000..e2feaf8 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/api/ActivityRepository.java @@ -0,0 +1,23 @@ +package ru.ulstu.activity.api; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.query.Param; + +import java.util.Optional; + +public interface ActivityRepository { + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); + + T save(T t); + + T getById(Integer id); + + Page findAll(Pageable pageable); + + void deleteById(Integer id); + + Optional findById(Integer id); + + void detach(T t); +} diff --git a/src/main/java/ru/ulstu/activity/api/model/ActivityDashboardDto.java b/src/main/java/ru/ulstu/activity/api/model/ActivityDashboardDto.java new file mode 100644 index 0000000..0f6446d --- /dev/null +++ b/src/main/java/ru/ulstu/activity/api/model/ActivityDashboardDto.java @@ -0,0 +1,19 @@ +package ru.ulstu.activity.api.model; + +public abstract class ActivityDashboardDto { + private final Integer id; + private final String title; + + protected ActivityDashboardDto(Integer id, String title) { + this.id = id; + this.title = title; + } + + public Integer getId() { + return id; + } + + public String getTitle() { + return title; + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/activity/api/model/ActivityDto.java b/src/main/java/ru/ulstu/activity/api/model/ActivityDto.java new file mode 100644 index 0000000..8f88493 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/api/model/ActivityDto.java @@ -0,0 +1,13 @@ +package ru.ulstu.activity.api.model; + +public abstract class ActivityDto { + private final Integer id; + + public ActivityDto(Integer id) { + this.id = id; + } + + public Integer getId() { + return id; + } +} diff --git a/src/main/java/ru/ulstu/activity/api/model/ActivityListDto.java b/src/main/java/ru/ulstu/activity/api/model/ActivityListDto.java new file mode 100644 index 0000000..52237eb --- /dev/null +++ b/src/main/java/ru/ulstu/activity/api/model/ActivityListDto.java @@ -0,0 +1,19 @@ +package ru.ulstu.activity.api.model; + +public abstract class ActivityListDto { + private final Integer id; + private final String title; + + protected ActivityListDto(Integer id, String title) { + this.id = id; + this.title = title; + } + + public Integer getId() { + return id; + } + + public String getTitle() { + return title; + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java b/src/main/java/ru/ulstu/activity/boundary/timetable/TimetableService.java similarity index 92% rename from src/main/java/ru/ulstu/utils/timetable/TimetableService.java rename to src/main/java/ru/ulstu/activity/boundary/timetable/TimetableService.java index b2a7874..56b82d2 100644 --- a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java +++ b/src/main/java/ru/ulstu/activity/boundary/timetable/TimetableService.java @@ -1,12 +1,12 @@ -package ru.ulstu.utils.timetable; +package ru.ulstu.activity.boundary.timetable; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import ru.ulstu.activity.boundary.timetable.errors.TimetableClientException; +import ru.ulstu.activity.boundary.timetable.model.Lesson; +import ru.ulstu.activity.boundary.timetable.model.TimetableResponse; import ru.ulstu.core.util.DateUtils; -import ru.ulstu.utils.timetable.errors.TimetableClientException; -import ru.ulstu.utils.timetable.model.Lesson; -import ru.ulstu.utils.timetable.model.TimetableResponse; import java.text.ParseException; import java.text.SimpleDateFormat; diff --git a/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java b/src/main/java/ru/ulstu/activity/boundary/timetable/errors/TimetableClientException.java similarity index 74% rename from src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java rename to src/main/java/ru/ulstu/activity/boundary/timetable/errors/TimetableClientException.java index 4723bda..bb0aaf5 100644 --- a/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java +++ b/src/main/java/ru/ulstu/activity/boundary/timetable/errors/TimetableClientException.java @@ -1,4 +1,4 @@ -package ru.ulstu.utils.timetable.errors; +package ru.ulstu.activity.boundary.timetable.errors; public class TimetableClientException extends RuntimeException { public TimetableClientException(String message) { diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Day.java b/src/main/java/ru/ulstu/activity/boundary/timetable/model/Day.java similarity index 89% rename from src/main/java/ru/ulstu/utils/timetable/model/Day.java rename to src/main/java/ru/ulstu/activity/boundary/timetable/model/Day.java index 211165d..4448a8c 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/Day.java +++ b/src/main/java/ru/ulstu/activity/boundary/timetable/model/Day.java @@ -1,4 +1,4 @@ -package ru.ulstu.utils.timetable.model; +package ru.ulstu.activity.boundary.timetable.model; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java b/src/main/java/ru/ulstu/activity/boundary/timetable/model/Lesson.java similarity index 88% rename from src/main/java/ru/ulstu/utils/timetable/model/Lesson.java rename to src/main/java/ru/ulstu/activity/boundary/timetable/model/Lesson.java index 9c855bd..0df534b 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java +++ b/src/main/java/ru/ulstu/activity/boundary/timetable/model/Lesson.java @@ -1,4 +1,4 @@ -package ru.ulstu.utils.timetable.model; +package ru.ulstu.activity.boundary.timetable.model; public class Lesson { private String group; diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Response.java b/src/main/java/ru/ulstu/activity/boundary/timetable/model/Response.java similarity index 84% rename from src/main/java/ru/ulstu/utils/timetable/model/Response.java rename to src/main/java/ru/ulstu/activity/boundary/timetable/model/Response.java index dfd3a84..0089433 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/Response.java +++ b/src/main/java/ru/ulstu/activity/boundary/timetable/model/Response.java @@ -1,4 +1,4 @@ -package ru.ulstu.utils.timetable.model; +package ru.ulstu.activity.boundary.timetable.model; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java b/src/main/java/ru/ulstu/activity/boundary/timetable/model/TimetableResponse.java similarity index 88% rename from src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java rename to src/main/java/ru/ulstu/activity/boundary/timetable/model/TimetableResponse.java index 118c979..06fbed6 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java +++ b/src/main/java/ru/ulstu/activity/boundary/timetable/model/TimetableResponse.java @@ -1,4 +1,4 @@ -package ru.ulstu.utils.timetable.model; +package ru.ulstu.activity.boundary.timetable.model; public class TimetableResponse { private Response response; diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Week.java b/src/main/java/ru/ulstu/activity/boundary/timetable/model/Week.java similarity index 85% rename from src/main/java/ru/ulstu/utils/timetable/model/Week.java rename to src/main/java/ru/ulstu/activity/boundary/timetable/model/Week.java index 8ea76ea..242d783 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/Week.java +++ b/src/main/java/ru/ulstu/activity/boundary/timetable/model/Week.java @@ -1,4 +1,4 @@ -package ru.ulstu.utils.timetable.model; +package ru.ulstu.activity.boundary.timetable.model; import java.io.Serializable; import java.util.ArrayList; diff --git a/src/main/java/ru/ulstu/activity/common/model/AbstractActivity.java b/src/main/java/ru/ulstu/activity/common/model/AbstractActivity.java new file mode 100644 index 0000000..8796bb0 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/common/model/AbstractActivity.java @@ -0,0 +1,24 @@ +package ru.ulstu.activity.common.model; + +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.user.model.User; + +import java.util.List; +import java.util.Set; + +public abstract class AbstractActivity extends BaseEntity { + private String title; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public abstract Set getActivityMembers(); + + public abstract List getEvents(); +} diff --git a/src/main/java/ru/ulstu/core/model/EventSource.java b/src/main/java/ru/ulstu/activity/common/model/EventSource.java similarity index 58% rename from src/main/java/ru/ulstu/core/model/EventSource.java rename to src/main/java/ru/ulstu/activity/common/model/EventSource.java index 32ffcf2..3c1efe0 100644 --- a/src/main/java/ru/ulstu/core/model/EventSource.java +++ b/src/main/java/ru/ulstu/activity/common/model/EventSource.java @@ -1,7 +1,7 @@ -package ru.ulstu.core.model; +package ru.ulstu.activity.common.model; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.timeline.model.Event; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.timeline.model.Event; import ru.ulstu.user.model.User; import java.util.List; @@ -14,4 +14,6 @@ public interface EventSource { List getRecipients(); void addObjectToEvent(Event event); + + String getSuffix(); } diff --git a/src/main/java/ru/ulstu/activity/common/model/ScienceGroupMemberDto.java b/src/main/java/ru/ulstu/activity/common/model/ScienceGroupMemberDto.java new file mode 100644 index 0000000..694b837 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/common/model/ScienceGroupMemberDto.java @@ -0,0 +1,77 @@ +package ru.ulstu.activity.common.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import ru.ulstu.activity.conference.model.ConferenceUser; +import ru.ulstu.user.model.User; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +public class ScienceGroupMemberDto { + + private Integer id; + + @NotBlank + @Size(min = 2, max = 50) + private String firstName; + + @NotBlank + @Size(min = 2, max = 50) + private String lastName; + + @JsonCreator + public ScienceGroupMemberDto(@JsonProperty("id") Integer id, + @JsonProperty("firstName") String firstName, + @JsonProperty("lastName") String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public ScienceGroupMemberDto(User user) { + this.id = user.getId(); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + } + + public ScienceGroupMemberDto(ConferenceUser conferenceUser) { + User user = conferenceUser.getUser(); + this.id = user.getId(); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Override + public String toString() { + return "ScienceGroupMember{" + + "id=" + id + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + '}'; + } +} diff --git a/src/main/java/ru/ulstu/activity/common/service/ActivityNotificationService.java b/src/main/java/ru/ulstu/activity/common/service/ActivityNotificationService.java new file mode 100644 index 0000000..7827b84 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/common/service/ActivityNotificationService.java @@ -0,0 +1,25 @@ +package ru.ulstu.activity.common.service; + +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.MailService; + +import java.util.Map; + +public abstract class ActivityNotificationService { + private final MailService mailService; + + protected ActivityNotificationService(MailService mailService) { + this.mailService = mailService; + } + + public abstract void sendCreateNotification(T entity); + + protected void sendForAuthor(Map variables, User author, String template, String title) { + mailService.sendEmailFromTemplate(variables, author, template, title); + } + + protected void sendForAllAuthors(Map variables, T entity, String template, String title) { + entity.getActivityMembers().forEach(author -> sendForAuthor(variables, author, template, title)); + } +} diff --git a/src/main/java/ru/ulstu/activity/common/service/ActivityService.java b/src/main/java/ru/ulstu/activity/common/service/ActivityService.java new file mode 100644 index 0000000..1f817b8 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/common/service/ActivityService.java @@ -0,0 +1,129 @@ +package ru.ulstu.activity.common.service; + +import org.springframework.data.domain.Page; +import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.activity.api.ActivityRepository; +import ru.ulstu.activity.api.model.ActivityDto; +import ru.ulstu.activity.api.model.ActivityListDto; +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.common.model.EventSource; +import ru.ulstu.activity.ping.service.PingService; +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.activity.timeline.service.EventService; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.response.PageableItems; + +import javax.persistence.EntityNotFoundException; +import java.io.IOException; +import java.util.List; + +import static ru.ulstu.core.util.StreamApiUtils.convertPageable; + +public abstract class ActivityService { + + protected final ActivityRepository activityRepository; + protected final ActivityNotificationService activityNotificationService; + protected final PingService pingService; + protected final EventService eventService; + + protected ActivityService(ActivityRepository activityRepository, + ActivityNotificationService activityNotificationService, + PingService pingService, + EventService eventService) { + this.activityRepository = activityRepository; + this.activityNotificationService = activityNotificationService; + this.pingService = pingService; + this.eventService = eventService; + } + + @Transactional + public D create(D entityDto) { + T newEntity; + try { + newEntity = copyFromDto(getNewActivity(), entityDto); + } catch (IOException e) { + throw new RuntimeException(e); + } + return getNewActivityDto(create(newEntity)); + } + + @Transactional + public T update(T oldEntity, T entity) { + entity.getEvents().clear(); + eventService.deleteAll(getEvents(entity)); + eventService.createFromObject((EventSource) entity); + doActionsOnDiffObjects(oldEntity, entity); + return activityRepository.save(entity); + } + + protected abstract void doActionsOnDiffObjects(T oldEntity, T entity); + + protected abstract List getEvents(T entity); + + @Transactional + public D update(D entityDto) { + T oldEntity = activityRepository.getById(entityDto.getId()); + //to init lazy collection + oldEntity.getActivityMembers().size(); + activityRepository.detach(oldEntity); + T newEntity; + try { + newEntity = copyFromDto(activityRepository.getById(entityDto.getId()), entityDto); + } catch (IOException e) { + throw new RuntimeException(e); + } + return getNewActivityDto(update(oldEntity, newEntity)); + } + + @Transactional + public T create(T entity) { + eventService.createFromObject((EventSource) entity); + T newEntity = activityRepository.save(entity); + activityNotificationService.sendCreateNotification(newEntity); + return newEntity; + } + + public boolean delete(Integer id) { + activityRepository.deleteById(id); + return true; + } + + public D findDtoById(Integer id) { + return getNewActivityDto(findById(id)); + } + + public T findById(Integer id) { + return activityRepository.findById(id) + .orElseThrow(() -> new EntityNotFoundException("Entity with id=" + id + " not found")); + } + + public PageableItems findAll(int offset, int count) { + final Page page = activityRepository.findAll(new OffsetablePageRequest(offset, count)); + return new PageableItems<>(page.getTotalElements(), page.getContent()); + } + + public PageableItems findAllDto(int offset, int count) { + return convertPageable(findAll(offset, count), entity -> getActivityListDto(entity)); + } + + public abstract PageableItems findAllActiveDto(int offset, int count); + + public abstract PageableItems findAllActive(int offset, int count); + + protected abstract T copyFromDto(T t, D d) throws IOException; + + protected abstract L getActivityListDto(T entity); + + protected abstract T getNewActivity(); + + protected abstract D getNewActivityDto(T entity); + + protected boolean checkUniqueName(String title, Integer id) { + return title.equals(activityRepository.findByNameAndNotId(title, id)); + } + + @Transactional + public void ping(int entityId) { + pingService.addPing(findById(entityId)); + } +} diff --git a/src/main/java/ru/ulstu/strategy/api/EntityCreateStrategy.java b/src/main/java/ru/ulstu/activity/common/strategy/api/EntityCreateStrategy.java similarity index 67% rename from src/main/java/ru/ulstu/strategy/api/EntityCreateStrategy.java rename to src/main/java/ru/ulstu/activity/common/strategy/api/EntityCreateStrategy.java index bf857a0..86bcdb1 100644 --- a/src/main/java/ru/ulstu/strategy/api/EntityCreateStrategy.java +++ b/src/main/java/ru/ulstu/activity/common/strategy/api/EntityCreateStrategy.java @@ -1,21 +1,21 @@ -package ru.ulstu.strategy.api; +package ru.ulstu.activity.common.strategy.api; -import ru.ulstu.core.model.UserActivity; +import ru.ulstu.activity.common.model.AbstractActivity; import ru.ulstu.user.model.User; import java.util.List; import java.util.stream.Collectors; -public abstract class EntityCreateStrategy { +public abstract class EntityCreateStrategy { protected abstract List getActiveEntities(); protected abstract void createEntity(User user); - private void createDefaultEntityIfNeed(List allUsers, List entities) { + private void createDefaultEntityIfNeed(List allUsers, List entities) { allUsers.forEach(user -> { if (entities .stream() - .filter(entity -> entity.getActivityUsers().contains(user)) + .filter(entity -> entity.getActivityMembers().contains(user)) .collect(Collectors.toSet()).isEmpty()) { createEntity(user); } diff --git a/src/main/java/ru/ulstu/strategy/api/StrategyEntityCreateExecutor.java b/src/main/java/ru/ulstu/activity/common/strategy/api/StrategyEntityCreateExecutor.java similarity index 94% rename from src/main/java/ru/ulstu/strategy/api/StrategyEntityCreateExecutor.java rename to src/main/java/ru/ulstu/activity/common/strategy/api/StrategyEntityCreateExecutor.java index c3d4d95..0ca34d5 100644 --- a/src/main/java/ru/ulstu/strategy/api/StrategyEntityCreateExecutor.java +++ b/src/main/java/ru/ulstu/activity/common/strategy/api/StrategyEntityCreateExecutor.java @@ -1,4 +1,4 @@ -package ru.ulstu.strategy.api; +package ru.ulstu.activity.common.strategy.api; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; diff --git a/src/main/java/ru/ulstu/activity/conference/controller/ConferenceController.java b/src/main/java/ru/ulstu/activity/conference/controller/ConferenceController.java new file mode 100644 index 0000000..63af6c6 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/conference/controller/ConferenceController.java @@ -0,0 +1,70 @@ +package ru.ulstu.activity.conference.controller; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import ru.ulstu.activity.api.ActivityController; +import ru.ulstu.activity.conference.model.ConferenceDashboardDto; +import ru.ulstu.activity.conference.model.ConferenceDto; +import ru.ulstu.activity.conference.model.ConferenceListDto; +import ru.ulstu.activity.conference.service.ConferenceService; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.core.model.response.Response; + +import javax.validation.Valid; + +public class ConferenceController implements ActivityController { + + private final ConferenceService conferenceService; + + public ConferenceController(ConferenceService conferenceService) { + this.conferenceService = conferenceService; + } + + @Override + @GetMapping("list") + public Response> getList(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "0") int count) { + return new Response<>(conferenceService.findAllDto(offset, count)); + } + + @Override + @GetMapping("dashboard") + public Response> getDashboard(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "0") int count) { + return new Response<>(conferenceService.findAllActiveDto(offset, count)); + } + + @Override + @GetMapping("{conference-id}") + public Response get(@PathVariable("conference-id") Integer entityId) { + return new Response<>(conferenceService.findConferenceById(entityId)); + } + + @Override + @PostMapping + public Response create(@RequestBody @Valid ConferenceDto entity) { + return new Response<>(conferenceService.create(entity)); + } + + @Override + @PutMapping + public Response update(@RequestBody @Valid ConferenceDto entity) { + return new Response<>(conferenceService.update(entity)); + } + + @Override + @DeleteMapping("{conference-id}") + public Response delete(@PathVariable("conference-id") Integer entityId) { + return new Response<>(conferenceService.delete(entityId)); + } + + @PostMapping("ping/{conference-id}") + public void ping(@PathVariable("conference-id") int conferenceId) { + conferenceService.ping(conferenceId); + } +} diff --git a/src/main/java/ru/ulstu/conference/model/Conference.java b/src/main/java/ru/ulstu/activity/conference/model/Conference.java similarity index 84% rename from src/main/java/ru/ulstu/conference/model/Conference.java rename to src/main/java/ru/ulstu/activity/conference/model/Conference.java index d11901f..8a34f4e 100644 --- a/src/main/java/ru/ulstu/conference/model/Conference.java +++ b/src/main/java/ru/ulstu/activity/conference/model/Conference.java @@ -1,14 +1,13 @@ -package ru.ulstu.conference.model; +package ru.ulstu.activity.conference.model; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.springframework.format.annotation.DateTimeFormat; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.EventSource; -import ru.ulstu.core.model.UserActivity; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.timeline.model.Event; +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.common.model.EventSource; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.activity.timeline.model.Event; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; @@ -26,6 +25,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotBlank; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; @@ -36,7 +36,7 @@ import java.util.stream.Collectors; @Entity @Table(name = "conference") @DiscriminatorValue("CONFERENCE") -public class Conference extends BaseEntity implements UserActivity, EventSource { +public class Conference extends AbstractActivity implements EventSource { @NotBlank private String title; @@ -79,6 +79,10 @@ public class Conference extends BaseEntity implements UserActivity, EventSource return title; } + public void setTitle(String title) { + this.title = title; + } + @Override public List getRecipients() { List list = new ArrayList<>(); @@ -88,12 +92,13 @@ public class Conference extends BaseEntity implements UserActivity, EventSource } @Override - public void addObjectToEvent(Event event) { - event.setConference(this); + public String getSuffix() { + return "конференции"; } - public void setTitle(String title) { - this.title = title; + @Override + public void addObjectToEvent(Event event) { + event.setConference(this); } public String getDescription() { @@ -170,7 +175,12 @@ public class Conference extends BaseEntity implements UserActivity, EventSource } @Override - public Set getActivityUsers() { - return getUsers().stream().map(ConferenceUser::getUser).collect(Collectors.toSet()); + public Set getActivityMembers() { + return users.stream().map(conferenceUser -> conferenceUser.getUser()).collect(Collectors.toSet()); + } + + @Override + public List getEvents() { + return Collections.emptyList(); } } diff --git a/src/main/java/ru/ulstu/activity/conference/model/ConferenceDashboardDto.java b/src/main/java/ru/ulstu/activity/conference/model/ConferenceDashboardDto.java new file mode 100644 index 0000000..3cdae05 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/conference/model/ConferenceDashboardDto.java @@ -0,0 +1,21 @@ +package ru.ulstu.activity.conference.model; + +import ru.ulstu.activity.api.model.ActivityDashboardDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; + +import java.util.Set; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class ConferenceDashboardDto extends ActivityDashboardDto { + private final Set members; + + public ConferenceDashboardDto(Conference conference) { + super(conference.getId(), conference.getTitle()); + this.members = convert(conference.getActivityMembers(), ScienceGroupMemberDto::new); + } + + public Set getAuthors() { + return members; + } +} diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java b/src/main/java/ru/ulstu/activity/conference/model/ConferenceDto.java similarity index 56% rename from src/main/java/ru/ulstu/conference/model/ConferenceDto.java rename to src/main/java/ru/ulstu/activity/conference/model/ConferenceDto.java index 7246854..b6b33ea 100644 --- a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java +++ b/src/main/java/ru/ulstu/activity/conference/model/ConferenceDto.java @@ -1,12 +1,12 @@ -package ru.ulstu.conference.model; +package ru.ulstu.activity.conference.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.format.annotation.DateTimeFormat; +import ru.ulstu.activity.api.model.ActivityDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; +import ru.ulstu.activity.deadline.model.DeadlineDto; import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.name.NameContainer; -import ru.ulstu.paper.model.Paper; import javax.persistence.Temporal; import javax.persistence.TemporalType; @@ -15,11 +15,10 @@ import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.Objects; import static ru.ulstu.core.util.StreamApiUtils.convert; -public class ConferenceDto extends NameContainer { +public class ConferenceDto extends ActivityDto { private final static String BEGIN_DATE = "Начало: "; private final static String END_DATE = "Конец: "; @@ -39,18 +38,12 @@ public class ConferenceDto extends NameContainer { @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "yyyy-MM-dd") private Date endDate = new Date(); - private List deadlines = new ArrayList<>(); - private List removedDeadlineIds = new ArrayList<>(); - private List userIds = new ArrayList<>(); + private List deadlines = new ArrayList<>(); + private List userIds = new ArrayList<>(); private List paperIds = new ArrayList<>(); - private List papers = new ArrayList<>(); - private List notSelectedPapers = new ArrayList<>(); private List users = new ArrayList<>(); private boolean disabledTakePart = false; - public ConferenceDto() { - } - @JsonCreator public ConferenceDto(@JsonProperty("id") Integer id, @JsonProperty("title") String title, @@ -59,15 +52,11 @@ public class ConferenceDto extends NameContainer { @JsonProperty("ping") Integer ping, @JsonProperty("beginDate") Date beginDate, @JsonProperty("endDate") Date endDate, - @JsonProperty("deadlines") List deadlines, - @JsonProperty("userIds") List userIds, + @JsonProperty("deadlines") List deadlines, + @JsonProperty("userIds") List userIds, @JsonProperty("paperIds") List paperIds, - @JsonProperty("users") List users, - @JsonProperty("papers") List papers, - @JsonProperty("notSelectedPapers") List notSelectedPapers, - @JsonProperty("notSelectedPapers") Boolean disabledTakePart) { - this.id = id; - this.title = title; + @JsonProperty("users") List users) { + super(id); this.description = description; this.url = url; this.ping = ping; @@ -77,24 +66,25 @@ public class ConferenceDto extends NameContainer { this.userIds = userIds; this.paperIds = paperIds; this.users = users; - this.papers = papers; - this.notSelectedPapers = notSelectedPapers; - this.disabledTakePart = disabledTakePart; + this.title = title; } public ConferenceDto(Conference conference) { - this.id = conference.getId(); + super(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(), BaseEntity::getId); + this.deadlines = convert(conference.getDeadlines(), DeadlineDto::new); + this.userIds = convert(conference.getUsers(), ScienceGroupMemberDto::new); this.paperIds = convert(conference.getPapers(), BaseEntity::getId); this.users = conference.getUsers(); - this.papers = conference.getPapers(); + } + + public ConferenceDto() { + super(null); } public Integer getId() { @@ -153,19 +143,19 @@ public class ConferenceDto extends NameContainer { this.endDate = endDate; } - public List getDeadlines() { + public List getDeadlines() { return deadlines; } - public void setDeadlines(List deadlines) { + public void setDeadlines(List deadlines) { this.deadlines = deadlines; } - public List getUserIds() { + public List getUserIds() { return userIds; } - public void setUserIds(List userIds) { + public void setUserIds(List userIds) { this.userIds = userIds; } @@ -177,14 +167,6 @@ public class ConferenceDto extends NameContainer { this.paperIds = paperIds; } - public List getPapers() { - return papers; - } - - public void setPapers(List papers) { - this.papers = papers; - } - public List getUsers() { return users; } @@ -200,54 +182,4 @@ public class ConferenceDto extends NameContainer { public void setDisabledTakePart(boolean disabledTakePart) { this.disabledTakePart = disabledTakePart; } - - public List getRemovedDeadlineIds() { - return removedDeadlineIds; - } - - public void setRemovedDeadlineIds(List removedDeadlineIds) { - this.removedDeadlineIds = removedDeadlineIds; - } - - public List getNotSelectedPapers() { - return notSelectedPapers; - } - - public void setNotSelectedPapers(List notSelectedPapers) { - this.notSelectedPapers = notSelectedPapers; - } - - public String getDatesString() { - return BEGIN_DATE + beginDate.toString().split(" ")[0] + " " + END_DATE + endDate.toString().split(" ")[0]; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ConferenceDto that = (ConferenceDto) o; - return ping == that.ping && - disabledTakePart == that.disabledTakePart && - Objects.equals(id, that.id) && - Objects.equals(title, that.title) && - Objects.equals(description, that.description) && - Objects.equals(url, that.url) && - Objects.equals(deadlines, that.deadlines) && - Objects.equals(removedDeadlineIds, that.removedDeadlineIds) && - Objects.equals(userIds, that.userIds) && - Objects.equals(paperIds, that.paperIds) && - Objects.equals(papers, that.papers) && - Objects.equals(notSelectedPapers, that.notSelectedPapers) && - Objects.equals(users, that.users); - } - - @Override - public int hashCode() { - return Objects.hash(id, title, description, url, ping, beginDate, endDate, deadlines, removedDeadlineIds, - userIds, paperIds, papers, notSelectedPapers, users, disabledTakePart); - } } diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java b/src/main/java/ru/ulstu/activity/conference/model/ConferenceFilterDto.java similarity index 95% rename from src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java rename to src/main/java/ru/ulstu/activity/conference/model/ConferenceFilterDto.java index 0649901..c1b07b5 100644 --- a/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java +++ b/src/main/java/ru/ulstu/activity/conference/model/ConferenceFilterDto.java @@ -1,4 +1,4 @@ -package ru.ulstu.conference.model; +package ru.ulstu.activity.conference.model; import java.util.List; diff --git a/src/main/java/ru/ulstu/activity/conference/model/ConferenceListDto.java b/src/main/java/ru/ulstu/activity/conference/model/ConferenceListDto.java new file mode 100644 index 0000000..d1a6f0a --- /dev/null +++ b/src/main/java/ru/ulstu/activity/conference/model/ConferenceListDto.java @@ -0,0 +1,21 @@ +package ru.ulstu.activity.conference.model; + +import ru.ulstu.activity.api.model.ActivityListDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; + +import java.util.Set; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class ConferenceListDto extends ActivityListDto { + private final Set members; + + public ConferenceListDto(Conference conference) { + super(conference.getId(), conference.getTitle()); + this.members = convert(conference.getActivityMembers(), ScienceGroupMemberDto::new); + } + + public Set getAuthors() { + return members; + } +} diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceUser.java b/src/main/java/ru/ulstu/activity/conference/model/ConferenceUser.java similarity index 98% rename from src/main/java/ru/ulstu/conference/model/ConferenceUser.java rename to src/main/java/ru/ulstu/activity/conference/model/ConferenceUser.java index f00b9fa..057ff9e 100644 --- a/src/main/java/ru/ulstu/conference/model/ConferenceUser.java +++ b/src/main/java/ru/ulstu/activity/conference/model/ConferenceUser.java @@ -1,4 +1,4 @@ -package ru.ulstu.conference.model; +package ru.ulstu.activity.conference.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/ru/ulstu/conference/repository/ConferenceUserRepository.java b/src/main/java/ru/ulstu/activity/conference/repository/ConferenceUserRepository.java similarity index 59% rename from src/main/java/ru/ulstu/conference/repository/ConferenceUserRepository.java rename to src/main/java/ru/ulstu/activity/conference/repository/ConferenceUserRepository.java index 5e654d5..252f52c 100644 --- a/src/main/java/ru/ulstu/conference/repository/ConferenceUserRepository.java +++ b/src/main/java/ru/ulstu/activity/conference/repository/ConferenceUserRepository.java @@ -1,7 +1,7 @@ -package ru.ulstu.conference.repository; +package ru.ulstu.activity.conference.repository; import org.springframework.data.jpa.repository.JpaRepository; -import ru.ulstu.conference.model.ConferenceUser; +import ru.ulstu.activity.conference.model.ConferenceUser; public interface ConferenceUserRepository extends JpaRepository { } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java b/src/main/java/ru/ulstu/activity/conference/service/ConferenceNotificationService.java similarity index 94% rename from src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java rename to src/main/java/ru/ulstu/activity/conference/service/ConferenceNotificationService.java index 961d369..c76fb3a 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java +++ b/src/main/java/ru/ulstu/activity/conference/service/ConferenceNotificationService.java @@ -1,10 +1,11 @@ -package ru.ulstu.conference.service; +package ru.ulstu.activity.conference.service; import com.google.common.collect.ImmutableMap; import org.springframework.stereotype.Service; -import ru.ulstu.conference.model.Conference; +import ru.ulstu.activity.common.service.ActivityNotificationService; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.ping.service.PingService; import ru.ulstu.core.util.DateUtils; -import ru.ulstu.ping.service.PingService; import ru.ulstu.user.service.MailService; import ru.ulstu.user.service.UserService; @@ -14,7 +15,7 @@ import java.util.List; import java.util.Map; @Service -public class ConferenceNotificationService { +public class ConferenceNotificationService extends ActivityNotificationService { private final static int YESTERDAY = -1; private final static int DAYS_TO_DEADLINE_NOTIFICATION = 7; @@ -37,6 +38,7 @@ public class ConferenceNotificationService { public ConferenceNotificationService(MailService mailService, UserService userService, PingService pingService) { + super(mailService); this.mailService = mailService; this.userService = userService; this.pingService = pingService; diff --git a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java b/src/main/java/ru/ulstu/activity/conference/service/ConferenceRepository.java similarity index 77% rename from src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java rename to src/main/java/ru/ulstu/activity/conference/service/ConferenceRepository.java index 8f9e05f..0ca32f7 100644 --- a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java +++ b/src/main/java/ru/ulstu/activity/conference/service/ConferenceRepository.java @@ -1,23 +1,25 @@ -package ru.ulstu.conference.repository; +package ru.ulstu.activity.conference.service; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.name.BaseRepository; +import ru.ulstu.activity.api.ActivityRepository; +import ru.ulstu.activity.conference.model.Conference; import ru.ulstu.user.model.User; import java.util.Date; import java.util.List; -public interface ConferenceRepository extends JpaRepository, BaseRepository { +interface ConferenceRepository extends JpaRepository, ActivityRepository { @Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " + "AND (YEAR(c.beginDate) = :year OR :year IS NULL) ORDER BY begin_date DESC") List findByUserAndYear(@Param("user") User user, @Param("year") Integer year); @Query("SELECT c FROM Conference c WHERE c.beginDate > :date") - List findAllActive(@Param("date") Date date); + Page findAllActive(Pageable pageable, @Param("date") Date date); @Query("SELECT case when count(c) > 0 then true else false end FROM Conference c JOIN c.papers p WHERE p.id = :paperId") boolean isPaperAttached(@Param("paperId") Integer paperId); diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceScheduler.java b/src/main/java/ru/ulstu/activity/conference/service/ConferenceScheduler.java similarity index 83% rename from src/main/java/ru/ulstu/conference/service/ConferenceScheduler.java rename to src/main/java/ru/ulstu/activity/conference/service/ConferenceScheduler.java index 6f8fe90..2d8df65 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceScheduler.java +++ b/src/main/java/ru/ulstu/activity/conference/service/ConferenceScheduler.java @@ -1,10 +1,12 @@ -package ru.ulstu.conference.service; +package ru.ulstu.activity.conference.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.util.stream.Collectors; + @Service public class ConferenceScheduler { private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; @@ -24,14 +26,16 @@ public class ConferenceScheduler { @Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara") public void checkDeadlineBeforeWeek() { log.debug("ConferenceScheduler.checkDeadlineBeforeWeek started"); - conferenceNotificationService.sendDeadlineNotifications(conferenceService.findAll()); + conferenceNotificationService.sendDeadlineNotifications(conferenceService.findAll(0, 100) + .getItems().stream().collect(Collectors.toList())); log.debug("ConferenceScheduler.checkDeadlineBeforeWeek finished"); } @Scheduled(cron = "0 0 8 * * *", zone = "Europe/Samara") public void checkNewPing() { log.debug("ConferenceScheduler.checkPing started"); - conferenceNotificationService.sendPingNotifications(conferenceService.findAll()); + conferenceNotificationService.sendPingNotifications(conferenceService.findAll(0, 100) + .getItems().stream().collect(Collectors.toList())); log.debug("ConferenceScheduler.checkPing finished"); } } diff --git a/src/main/java/ru/ulstu/activity/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/activity/conference/service/ConferenceService.java new file mode 100644 index 0000000..918d273 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/conference/service/ConferenceService.java @@ -0,0 +1,154 @@ +package ru.ulstu.activity.conference.service; + +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; +import ru.ulstu.activity.common.service.ActivityService; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.conference.model.ConferenceDashboardDto; +import ru.ulstu.activity.conference.model.ConferenceDto; +import ru.ulstu.activity.conference.model.ConferenceFilterDto; +import ru.ulstu.activity.conference.model.ConferenceListDto; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.deadline.service.DeadlineService; +import ru.ulstu.activity.paper.service.PaperService; +import ru.ulstu.activity.ping.service.PingService; +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.activity.timeline.service.EventService; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.util.Date; +import java.util.List; + +import static ru.ulstu.core.util.StreamApiUtils.convert; +import static ru.ulstu.core.util.StreamApiUtils.convertPageable; + +@Service +public class ConferenceService extends ActivityService { + + private final ConferenceRepository conferenceRepository; + private final ConferenceUserService conferenceUserService; + private final DeadlineService deadlineService; + private final PaperService paperService; + private final UserService userService; + private final PingService pingService; + private final ConferenceNotificationService conferenceNotificationService; + private final EventService eventService; + + public ConferenceService(ConferenceRepository conferenceRepository, + ConferenceUserService conferenceUserService, + DeadlineService deadlineService, + PaperService paperService, + UserService userService, + PingService pingService, + ConferenceNotificationService conferenceNotificationService, + EventService eventService) { + super(conferenceRepository, conferenceNotificationService, pingService, eventService); + this.conferenceRepository = conferenceRepository; + this.conferenceUserService = conferenceUserService; + this.deadlineService = deadlineService; + this.paperService = paperService; + this.userService = userService; + this.pingService = pingService; + this.conferenceNotificationService = conferenceNotificationService; + this.eventService = eventService; + } + + @Override + protected ConferenceListDto getActivityListDto(Conference entity) { + return new ConferenceListDto(entity); + } + + @Override + protected Conference getNewActivity() { + return new Conference(); + } + + @Override + protected ConferenceDto getNewActivityDto(Conference entity) { + return new ConferenceDto(entity); + } + + protected Conference copyFromDto(Conference conference, ConferenceDto conferenceDto) throws IOException { + conference.setTitle(conferenceDto.getTitle()); + conference.setDescription(conferenceDto.getDescription()); + conference.setUrl(conferenceDto.getUrl()); + conference.setBeginDate(conferenceDto.getBeginDate()); + conference.setEndDate(conferenceDto.getEndDate()); + conference.getPapers().clear(); + conferenceDto.getPaperIds().forEach(paperId -> conference.getPapers().add(paperService.findById(paperId))); + conference.setDeadlines(deadlineService.saveOrCreate(conferenceDto.getDeadlines())); + conference.setUsers(conferenceUserService.saveOrCreate(conferenceDto.getUsers())); + if (conferenceDto.getPaperIds() != null && !conferenceDto.getPaperIds().isEmpty()) { + conferenceDto.getPaperIds().forEach(paperId -> + conference.getPapers().add(paperService.findById(paperId))); + } + return conference; + } + + public List filter(ConferenceFilterDto conferenceFilterDto) { + return convert(conferenceRepository.findByUserAndYear( + conferenceFilterDto.getFilterUserId() == null ? null : userService.findById(conferenceFilterDto.getFilterUserId()), + conferenceFilterDto.getYear()), ConferenceDto::new); + + } + + public PageableItems findAllActiveDto(int offset, int count) { + return convertPageable(findAllActive(offset, count), ConferenceDashboardDto::new); + } + + @Override + public PageableItems findAllActive(int offset, int count) { + Page activeConferencePage = conferenceRepository + .findAllActive(new OffsetablePageRequest(offset, count), new Date()); + return new PageableItems<>(activeConferencePage.getTotalElements(), activeConferencePage.getContent()); + } + + public ConferenceDto findConferenceById(Integer id) { + return new ConferenceDto(findById(id)); + } + + public Conference findById(Integer id) { + return conferenceRepository.getOne(id); + } + + public Conference getActiveConferenceByUser(User user) { + return conferenceRepository.findActiveByUser(user); + } + + @Override + protected void doActionsOnDiffObjects(Conference oldEntity, Conference entity) { + if (!entity.getBeginDate().equals(oldEntity.getBeginDate()) + || !entity.getEndDate().equals(oldEntity.getEndDate())) { + conferenceNotificationService.updateConferencesDatesNotification(entity, oldEntity.getBeginDate(), oldEntity.getEndDate()); + } + entity.getActivityMembers().forEach(author -> { + if (!oldEntity.getActivityMembers().contains(author)) { + conferenceNotificationService.sendCreateNotification(entity); + } + }); + sendNotificationAfterUpdateDeadlines(entity, oldEntity.getDeadlines()); + } + + private void sendNotificationAfterUpdateDeadlines(Conference conference, List oldDeadlines) { + if (oldDeadlines.size() != conference.getDeadlines().size()) { + conferenceNotificationService.updateDeadlineNotification(conference); + return; + } + + if (conference.getDeadlines() + .stream() + .filter(deadline -> !oldDeadlines.contains(deadline)) + .count() > 0) { + conferenceNotificationService.updateDeadlineNotification(conference); + } + } + + @Override + protected List getEvents(Conference entity) { + return eventService.findByConference(entity); + } +} diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java b/src/main/java/ru/ulstu/activity/conference/service/ConferenceUserService.java similarity index 89% rename from src/main/java/ru/ulstu/conference/service/ConferenceUserService.java rename to src/main/java/ru/ulstu/activity/conference/service/ConferenceUserService.java index 01d02d6..c9b5742 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java +++ b/src/main/java/ru/ulstu/activity/conference/service/ConferenceUserService.java @@ -1,9 +1,9 @@ -package ru.ulstu.conference.service; +package ru.ulstu.activity.conference.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import ru.ulstu.conference.model.ConferenceUser; -import ru.ulstu.conference.repository.ConferenceUserRepository; +import ru.ulstu.activity.conference.model.ConferenceUser; +import ru.ulstu.activity.conference.repository.ConferenceUserRepository; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/activity/deadline/model/Deadline.java similarity index 93% rename from src/main/java/ru/ulstu/deadline/model/Deadline.java rename to src/main/java/ru/ulstu/activity/deadline/model/Deadline.java index d0564a0..c4b07fa 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/activity/deadline/model/Deadline.java @@ -1,4 +1,4 @@ -package ru.ulstu.deadline.model; +package ru.ulstu.activity.deadline.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -11,6 +11,7 @@ import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; @@ -24,8 +25,8 @@ public class Deadline extends BaseEntity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; - @OneToMany(targetEntity = User.class, fetch = FetchType.EAGER) - private List executors; + @OneToMany(targetEntity = User.class, fetch = FetchType.LAZY) + private List executors = new ArrayList<>(); private Boolean done; @@ -81,7 +82,7 @@ public class Deadline extends BaseEntity { this.executors = executors; } - public Boolean getDone() { + public Boolean isDone() { return done; } diff --git a/src/main/java/ru/ulstu/activity/deadline/model/DeadlineDto.java b/src/main/java/ru/ulstu/activity/deadline/model/DeadlineDto.java new file mode 100644 index 0000000..31b77fb --- /dev/null +++ b/src/main/java/ru/ulstu/activity/deadline/model/DeadlineDto.java @@ -0,0 +1,61 @@ +package ru.ulstu.activity.deadline.model; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +public class DeadlineDto { + private final Integer id; + private final Date date; + private final String description; + private final List executorsIds; + private final Boolean done; + + public DeadlineDto() { + this.id = null; + this.date = null; + this.description = null; + this.executorsIds = new ArrayList<>(); + this.done = false; + } + + public DeadlineDto(Deadline deadline) { + this.id = deadline.getId(); + this.date = deadline.getDate(); + this.description = deadline.getDescription(); + this.executorsIds = deadline.getExecutors() + .stream() + .map(executor -> executor.getId()) + .collect(Collectors.toList()); + this.done = deadline.isDone(); + } + + public DeadlineDto(Date date, String description) { + this.id = null; + this.date = date; + this.description = description; + this.executorsIds = new ArrayList<>(); + this.done = false; + } + + public Integer getId() { + return id; + } + + public Date getDate() { + return date; + } + + public String getDescription() { + return description; + } + + public List getExecutorsIds() { + return executorsIds; + } + + public Boolean isDone() { + return done; + } +} diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/activity/deadline/service/DeadlineRepository.java similarity index 70% rename from src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java rename to src/main/java/ru/ulstu/activity/deadline/service/DeadlineRepository.java index 652f01d..128fe0b 100644 --- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java +++ b/src/main/java/ru/ulstu/activity/deadline/service/DeadlineRepository.java @@ -1,14 +1,14 @@ -package ru.ulstu.deadline.repository; +package ru.ulstu.activity.deadline.service; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.activity.deadline.model.Deadline; import java.util.Date; -public interface DeadlineRepository extends JpaRepository { +interface DeadlineRepository extends JpaRepository { @Query("SELECT d.date FROM Grant g JOIN g.deadlines d WHERE (g.id = :id) AND (d.date = :date)") Date findByGrantIdAndDate(@Param("id") Integer grantId, @Param("date") Date date); diff --git a/src/main/java/ru/ulstu/activity/deadline/service/DeadlineService.java b/src/main/java/ru/ulstu/activity/deadline/service/DeadlineService.java new file mode 100644 index 0000000..cf78f54 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/deadline/service/DeadlineService.java @@ -0,0 +1,65 @@ +package ru.ulstu.activity.deadline.service; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.deadline.model.DeadlineDto; +import ru.ulstu.user.service.UserService; + +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class DeadlineService { + private final DeadlineRepository deadlineRepository; + private final UserService userService; + + public DeadlineService(DeadlineRepository deadlineRepository, + UserService userService) { + this.deadlineRepository = deadlineRepository; + this.userService = userService; + } + + public List saveOrCreate(List deadlines) { + return deadlines + .stream() + .map(deadline -> { + return deadline.getId() != null ? update(deadline) : create(deadline); + }).collect(Collectors.toList()); + } + + @Transactional + public Deadline update(DeadlineDto deadlineDto) { + Deadline updateDeadline = deadlineRepository.getOne(deadlineDto.getId()); + deadlineRepository.save(copyFromDto(updateDeadline, deadlineDto)); + return updateDeadline; + } + + @Transactional + public Deadline create(DeadlineDto deadlineDto) { + return deadlineRepository.save(copyFromDto(new Deadline(), deadlineDto)); + } + + @Transactional + public Deadline create(Deadline deadline) { + return deadlineRepository.save(deadline); + } + + @Transactional + public void remove(Integer deadlineId) { + deadlineRepository.deleteById(deadlineId); + } + + private Deadline copyFromDto(Deadline deadline, DeadlineDto deadlineDto) { + deadline.setDate(deadlineDto.getDate()); + deadline.setDescription(deadlineDto.getDescription()); + deadline.setExecutors(userService.findByIds(deadlineDto.getExecutorsIds())); + deadline.setDone(deadlineDto.isDone()); + return deadline; + } + + public Date findByGrantIdAndDate(Integer id, Date date) { + return deadlineRepository.findByGrantIdAndDate(id, date); + } +} diff --git a/src/main/java/ru/ulstu/file/FileController.java b/src/main/java/ru/ulstu/activity/file/FileController.java similarity index 92% rename from src/main/java/ru/ulstu/file/FileController.java rename to src/main/java/ru/ulstu/activity/file/FileController.java index 02421aa..82ffb82 100644 --- a/src/main/java/ru/ulstu/file/FileController.java +++ b/src/main/java/ru/ulstu/activity/file/FileController.java @@ -1,4 +1,4 @@ -package ru.ulstu.file; +package ru.ulstu.activity.file; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -10,11 +10,11 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; +import ru.ulstu.activity.file.model.FileData; +import ru.ulstu.activity.file.model.FileDataDto; +import ru.ulstu.activity.file.service.FileService; import ru.ulstu.configuration.Constants; import ru.ulstu.core.model.response.Response; -import ru.ulstu.file.model.FileData; -import ru.ulstu.file.model.FileDataDto; -import ru.ulstu.file.service.FileService; import java.io.IOException; import java.io.UnsupportedEncodingException; diff --git a/src/main/java/ru/ulstu/file/model/FileData.java b/src/main/java/ru/ulstu/activity/file/model/FileData.java similarity index 96% rename from src/main/java/ru/ulstu/file/model/FileData.java rename to src/main/java/ru/ulstu/activity/file/model/FileData.java index 3f97130..2177f58 100644 --- a/src/main/java/ru/ulstu/file/model/FileData.java +++ b/src/main/java/ru/ulstu/activity/file/model/FileData.java @@ -1,4 +1,4 @@ -package ru.ulstu.file.model; +package ru.ulstu.activity.file.model; import ru.ulstu.core.model.BaseEntity; diff --git a/src/main/java/ru/ulstu/file/model/FileDataDto.java b/src/main/java/ru/ulstu/activity/file/model/FileDataDto.java similarity index 98% rename from src/main/java/ru/ulstu/file/model/FileDataDto.java rename to src/main/java/ru/ulstu/activity/file/model/FileDataDto.java index e83bf12..853e536 100644 --- a/src/main/java/ru/ulstu/file/model/FileDataDto.java +++ b/src/main/java/ru/ulstu/activity/file/model/FileDataDto.java @@ -1,4 +1,4 @@ -package ru.ulstu.file.model; +package ru.ulstu.activity.file.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/ru/ulstu/activity/file/service/FileRepository.java b/src/main/java/ru/ulstu/activity/file/service/FileRepository.java new file mode 100644 index 0000000..b1e91ae --- /dev/null +++ b/src/main/java/ru/ulstu/activity/file/service/FileRepository.java @@ -0,0 +1,7 @@ +package ru.ulstu.activity.file.service; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.activity.file.model.FileData; + +interface FileRepository extends JpaRepository { +} diff --git a/src/main/java/ru/ulstu/file/service/FileService.java b/src/main/java/ru/ulstu/activity/file/service/FileService.java similarity index 94% rename from src/main/java/ru/ulstu/file/service/FileService.java rename to src/main/java/ru/ulstu/activity/file/service/FileService.java index c7d7dc2..e20a48b 100644 --- a/src/main/java/ru/ulstu/file/service/FileService.java +++ b/src/main/java/ru/ulstu/activity/file/service/FileService.java @@ -1,12 +1,11 @@ -package ru.ulstu.file.service; +package ru.ulstu.activity.file.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; -import ru.ulstu.file.model.FileData; -import ru.ulstu.file.model.FileDataDto; -import ru.ulstu.file.repostory.FileRepository; -import ru.ulstu.paper.model.PaperDto; +import ru.ulstu.activity.file.model.FileData; +import ru.ulstu.activity.file.model.FileDataDto; +import ru.ulstu.activity.paper.model.PaperDto; import java.io.BufferedWriter; import java.io.File; @@ -97,13 +96,13 @@ public class FileService { } @Transactional - private FileData update(FileDataDto fileDataDto) { + public FileData update(FileDataDto fileDataDto) { FileData file = fileRepository.getOne(fileDataDto.getId()); return fileRepository.save(copyFromDto(file, fileDataDto)); } @Transactional - private FileData create(FileDataDto fileDataDto) throws IOException { + public FileData create(FileDataDto fileDataDto) throws IOException { FileData newFile = createFileFromTmp(fileDataDto.getTmpFileName()); copyFromDto(newFile, fileDataDto); return fileRepository.save(newFile); diff --git a/src/main/java/ru/ulstu/activity/grant/controller/GrantController.java b/src/main/java/ru/ulstu/activity/grant/controller/GrantController.java new file mode 100644 index 0000000..21b1d9b --- /dev/null +++ b/src/main/java/ru/ulstu/activity/grant/controller/GrantController.java @@ -0,0 +1,82 @@ +package ru.ulstu.activity.grant.controller; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import ru.ulstu.activity.api.ActivityController; +import ru.ulstu.activity.grant.model.GrantDashboardDto; +import ru.ulstu.activity.grant.model.GrantDto; +import ru.ulstu.activity.grant.model.GrantListDto; +import ru.ulstu.activity.grant.service.GrantService; +import ru.ulstu.configuration.Constants; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.core.model.response.Response; + +import javax.validation.Valid; +import java.io.IOException; +import java.text.ParseException; + +@RestController +@RequestMapping(Constants.API_1_0 + "grants") +public class GrantController implements ActivityController { + private final GrantService grantService; + + public GrantController(GrantService grantService) { + this.grantService = grantService; + } + + @GetMapping("grab") + public void grab() throws IOException, ParseException { + grantService.createFromKias(); + } + + @Override + @GetMapping("list") + public Response> getList(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "0") int count) { + return new Response<>(grantService.findAllDto(offset, count)); + } + + @Override + @GetMapping("dashboard") + public Response> getDashboard(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "0") int count) { + return new Response<>(grantService.findAllActiveDto(offset, count)); + } + + @Override + @GetMapping("{grant-id}") + public Response get(@PathVariable("grant-id") Integer entityId) { + return new Response<>(grantService.findDtoById(entityId)); + } + + @Override + @PostMapping + public Response create(@RequestBody @Valid GrantDto entity) { + return new Response<>(grantService.create(entity)); + } + + @Override + @PutMapping + public Response update(@RequestBody @Valid GrantDto entity) { + return new Response<>(grantService.update(entity)); + } + + @Override + @DeleteMapping("{grant-id}") + public Response delete(@PathVariable("grant-id") Integer entityId) { + return new Response<>(grantService.delete(entityId)); + } + + @Override + @PostMapping("ping/{grant-id}") + public void ping(@PathVariable("grant-id") int entityId) { + grantService.ping(entityId); + } +} diff --git a/src/main/java/ru/ulstu/grant/model/Grant.java b/src/main/java/ru/ulstu/activity/grant/model/Grant.java similarity index 89% rename from src/main/java/ru/ulstu/grant/model/Grant.java rename to src/main/java/ru/ulstu/activity/grant/model/Grant.java index 0d16f77..9d12b3a 100644 --- a/src/main/java/ru/ulstu/grant/model/Grant.java +++ b/src/main/java/ru/ulstu/activity/grant/model/Grant.java @@ -1,15 +1,14 @@ -package ru.ulstu.grant.model; +package ru.ulstu.activity.grant.model; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.EventSource; -import ru.ulstu.core.model.UserActivity; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.file.model.FileData; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.project.model.Project; -import ru.ulstu.timeline.model.Event; +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.common.model.EventSource; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.file.model.FileData; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.activity.project.model.Project; +import ru.ulstu.activity.timeline.model.Event; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; @@ -39,7 +38,7 @@ import java.util.Set; @Entity @Table(name = "grants") @DiscriminatorValue("GRANT") -public class Grant extends BaseEntity implements UserActivity, EventSource { +public class Grant extends AbstractActivity implements EventSource { public enum GrantStatus { APPLICATION("Заявка"), ON_COMPETITION("Отправлен на конкурс"), @@ -138,18 +137,23 @@ public class Grant extends BaseEntity implements UserActivity, EventSource { return title; } + public void setTitle(String title) { + this.title = title; + } + @Override public List getRecipients() { return authors != null ? new ArrayList<>(authors) : Collections.emptyList(); } @Override - public void addObjectToEvent(Event event) { - event.setGrant(this); + public String getSuffix() { + return "гранта"; } - public void setTitle(String title) { - this.title = title; + @Override + public void addObjectToEvent(Event event) { + event.setGrant(this); } public Project getProject() { @@ -169,8 +173,8 @@ public class Grant extends BaseEntity implements UserActivity, EventSource { } @Override - public Set getActivityUsers() { - return getAuthors(); + public Set getActivityMembers() { + return authors; } public User getLeader() { diff --git a/src/main/java/ru/ulstu/activity/grant/model/GrantDashboardDto.java b/src/main/java/ru/ulstu/activity/grant/model/GrantDashboardDto.java new file mode 100644 index 0000000..eff0cc1 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/grant/model/GrantDashboardDto.java @@ -0,0 +1,27 @@ +package ru.ulstu.activity.grant.model; + +import ru.ulstu.activity.api.model.ActivityDashboardDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; + +import java.util.Set; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class GrantDashboardDto extends ActivityDashboardDto { + private final Grant.GrantStatus status; + private final Set members; + + public GrantDashboardDto(Grant grant) { + super(grant.getId(), grant.getTitle()); + this.status = grant.getStatus(); + this.members = convert(grant.getActivityMembers(), ScienceGroupMemberDto::new); + } + + public Grant.GrantStatus getStatus() { + return status; + } + + public Set getAuthors() { + return members; + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/activity/grant/model/GrantDto.java b/src/main/java/ru/ulstu/activity/grant/model/GrantDto.java new file mode 100644 index 0000000..03dcee6 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/grant/model/GrantDto.java @@ -0,0 +1,145 @@ +package ru.ulstu.activity.grant.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import ru.ulstu.activity.api.model.ActivityDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; +import ru.ulstu.activity.deadline.model.DeadlineDto; +import ru.ulstu.activity.file.model.FileDataDto; + +import javax.validation.constraints.NotEmpty; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class GrantDto extends ActivityDto { + @NotEmpty + private String title; + private Grant.GrantStatus status; + private List deadlines = new ArrayList<>(); + private String comment; + private List files = new ArrayList<>(); + private List projectIds; + private Set members; + private Integer leaderId; + private List paperIds = new ArrayList<>(); + + @JsonCreator + public GrantDto(@JsonProperty("id") Integer id, + @JsonProperty("title") String title, + @JsonProperty("status") Grant.GrantStatus status, + @JsonProperty("deadlines") List deadlines, + @JsonProperty("comment") String comment, + @JsonProperty("files") List files, + @JsonProperty("members") Set members, + @JsonProperty("leaderId") Integer leaderId, + @JsonProperty("paperIds") List paperIds) { + super(id); + this.title = title; + this.status = status; + this.deadlines = deadlines; + this.comment = comment; + this.files = files; + this.members = members; + this.leaderId = leaderId; + this.paperIds = paperIds; + } + + public GrantDto(Integer id) { + super(id); + } + + public GrantDto(Grant grant) { + super(grant.getId()); + this.title = grant.getTitle(); + this.status = grant.getStatus(); + this.deadlines = convert(grant.getDeadlines(), DeadlineDto::new); + this.comment = grant.getComment(); + this.files = convert(grant.getFiles(), FileDataDto::new); + this.members = convert(grant.getAuthors(), ScienceGroupMemberDto::new); + this.leaderId = grant.getLeader().getId(); + this.paperIds = convert(grant.getPapers(), paper -> paper.getId()); + } + + public GrantDto(String grantTitle, Date deadlineDate) { + super(null); + this.title = grantTitle; + this.deadlines.add(new DeadlineDto(deadlineDate, "Окончание приёма заявок")); + this.status = Grant.GrantStatus.LOADED_FROM_KIAS; + } + + public GrantDto() { + super(null); + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Grant.GrantStatus getStatus() { + return status; + } + + public void setStatus(Grant.GrantStatus status) { + this.status = status; + } + + public List getDeadlines() { + return deadlines; + } + + public void setDeadlines(List deadlines) { + this.deadlines = deadlines; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public List getFiles() { + return files; + } + + public void setFiles(List files) { + this.files = files; + } + + public Set getMembers() { + return members; + } + + public void setMembers(Set members) { + this.members = members; + } + + public Integer getLeaderId() { + return leaderId; + } + + public void setLeaderId(Integer leaderId) { + this.leaderId = leaderId; + } + + public List getPaperIds() { + return paperIds; + } + + public void setPaperIds(List paperIds) { + this.paperIds = paperIds; + } + + public List getProjectIds() { + return projectIds; + } +} diff --git a/src/main/java/ru/ulstu/activity/grant/model/GrantListDto.java b/src/main/java/ru/ulstu/activity/grant/model/GrantListDto.java new file mode 100644 index 0000000..237b572 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/grant/model/GrantListDto.java @@ -0,0 +1,28 @@ +package ru.ulstu.activity.grant.model; + +import ru.ulstu.activity.api.model.ActivityListDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; + +import java.util.Set; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class GrantListDto extends ActivityListDto { + + private final Grant.GrantStatus status; + private final Set members; + + public GrantListDto(Grant grant) { + super(grant.getId(), grant.getTitle()); + this.status = grant.getStatus(); + this.members = convert(grant.getActivityMembers(), ScienceGroupMemberDto::new); + } + + public Grant.GrantStatus getStatus() { + return status; + } + + public Set getAuthors() { + return members; + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/activity/grant/page/KiasPage.java similarity index 97% rename from src/main/java/ru/ulstu/grant/page/KiasPage.java rename to src/main/java/ru/ulstu/activity/grant/page/KiasPage.java index 49d54a0..ef152d6 100644 --- a/src/main/java/ru/ulstu/grant/page/KiasPage.java +++ b/src/main/java/ru/ulstu/activity/grant/page/KiasPage.java @@ -1,4 +1,4 @@ -package ru.ulstu.grant.page; +package ru.ulstu.activity.grant.page; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.HtmlElement; diff --git a/src/main/java/ru/ulstu/grant/service/GrantNotificationService.java b/src/main/java/ru/ulstu/activity/grant/service/GrantNotificationService.java similarity index 84% rename from src/main/java/ru/ulstu/grant/service/GrantNotificationService.java rename to src/main/java/ru/ulstu/activity/grant/service/GrantNotificationService.java index 677b38f..4c8202e 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantNotificationService.java +++ b/src/main/java/ru/ulstu/activity/grant/service/GrantNotificationService.java @@ -1,9 +1,10 @@ -package ru.ulstu.grant.service; +package ru.ulstu.activity.grant.service; import com.google.common.collect.ImmutableMap; import org.springframework.stereotype.Service; +import ru.ulstu.activity.common.service.ActivityNotificationService; +import ru.ulstu.activity.grant.model.Grant; import ru.ulstu.core.util.DateUtils; -import ru.ulstu.grant.model.Grant; import ru.ulstu.user.model.User; import ru.ulstu.user.service.MailService; @@ -13,7 +14,7 @@ import java.util.Map; import java.util.Set; @Service -public class GrantNotificationService { +public class GrantNotificationService extends ActivityNotificationService { private final static int DAYS_TO_DEADLINE_NOTIFICATION = 7; private final static String TEMPLATE_DEADLINE = "grantDeadlineNotification"; private final static String TEMPLATE_CREATE = "grantCreateNotification"; @@ -25,10 +26,8 @@ public class GrantNotificationService { private final static String TITLE_AUTHORS_CHANGED = "Изменился состав рабочей группы гранта: %s"; private final static String TITLE_LEADER_CHANGED = "Изменился руководитель гранта: %s"; - private final MailService mailService; - public GrantNotificationService(MailService mailService) { - this.mailService = mailService; + super(mailService); } public void sendDeadlineNotifications(List grants, boolean isDeadlineBeforeWeek) { @@ -64,10 +63,4 @@ public class GrantNotificationService { Map variables = ImmutableMap.of("grant", grant, "oldLeader", oldLeader); sendForAllAuthors(variables, grant, TEMPLATE_LEADER_CHANGED, String.format(TITLE_LEADER_CHANGED, grant.getTitle())); } - - private void sendForAllAuthors(Map variables, Grant grant, String template, String title) { - Set allAuthors = grant.getAuthors(); - allAuthors.forEach(author -> mailService.sendEmailFromTemplate(variables, author, template, title)); - mailService.sendEmailFromTemplate(variables, grant.getLeader(), template, title); - } } diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/activity/grant/service/GrantRepository.java similarity index 56% rename from src/main/java/ru/ulstu/grant/repository/GrantRepository.java rename to src/main/java/ru/ulstu/activity/grant/service/GrantRepository.java index 50fad13..76961ec 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/activity/grant/service/GrantRepository.java @@ -1,14 +1,16 @@ -package ru.ulstu.grant.repository; +package ru.ulstu.activity.grant.service; -import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; 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 ru.ulstu.activity.api.ActivityRepository; +import ru.ulstu.activity.grant.model.Grant; +import ru.ulstu.core.repository.JpaDetachableRepository; import java.util.List; -public interface GrantRepository extends JpaRepository, BaseRepository { +interface GrantRepository extends JpaDetachableRepository, ActivityRepository { List findByStatus(Grant.GrantStatus status); @@ -21,5 +23,5 @@ public interface GrantRepository extends JpaRepository, BaseRepo String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); @Query("SELECT g FROM Grant g WHERE (g.status <> 'SKIPPED') AND (g.status <> 'COMPLETED')") - List findAllActive(); + Page findAllActive(Pageable pageable); } diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/activity/grant/service/GrantScheduler.java similarity index 87% rename from src/main/java/ru/ulstu/grant/service/GrantScheduler.java rename to src/main/java/ru/ulstu/activity/grant/service/GrantScheduler.java index d026911..036b190 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java +++ b/src/main/java/ru/ulstu/activity/grant/service/GrantScheduler.java @@ -1,4 +1,4 @@ -package ru.ulstu.grant.service; +package ru.ulstu.activity.grant.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -7,6 +7,7 @@ import org.springframework.stereotype.Service; import java.io.IOException; import java.text.ParseException; +import java.util.stream.Collectors; @Service public class GrantScheduler { @@ -27,7 +28,8 @@ public class GrantScheduler { @Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara") public void checkDeadlineBeforeWeek() { log.debug("GrantScheduler.checkDeadlineBeforeWeek started"); - grantNotificationService.sendDeadlineNotifications(grantService.findAllActive(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); + grantNotificationService.sendDeadlineNotifications(grantService.findAllActive(0, 100) + .getItems().stream().collect(Collectors.toList()), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); } diff --git a/src/main/java/ru/ulstu/activity/grant/service/GrantService.java b/src/main/java/ru/ulstu/activity/grant/service/GrantService.java new file mode 100644 index 0000000..4b350bd --- /dev/null +++ b/src/main/java/ru/ulstu/activity/grant/service/GrantService.java @@ -0,0 +1,188 @@ +package ru.ulstu.activity.grant.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.activity.common.service.ActivityService; +import ru.ulstu.activity.deadline.service.DeadlineService; +import ru.ulstu.activity.file.service.FileService; +import ru.ulstu.activity.grant.model.Grant; +import ru.ulstu.activity.grant.model.GrantDashboardDto; +import ru.ulstu.activity.grant.model.GrantDto; +import ru.ulstu.activity.grant.model.GrantListDto; +import ru.ulstu.activity.paper.service.PaperService; +import ru.ulstu.activity.ping.service.PingService; +import ru.ulstu.activity.project.service.ProjectService; +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.activity.timeline.service.EventService; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.core.util.DateUtils; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.text.ParseException; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import static java.util.stream.Collectors.toList; +import static ru.ulstu.activity.grant.model.Grant.GrantStatus.APPLICATION; +import static ru.ulstu.core.util.StreamApiUtils.convertPageable; + +@Service +public class GrantService extends ActivityService { + private final Logger log = LoggerFactory.getLogger(GrantService.class); + + private final GrantRepository grantRepository; + private final ProjectService projectService; + private final DeadlineService deadlineService; + private final FileService fileService; + private final UserService userService; + private final PaperService paperService; + private final EventService eventService; + private final GrantNotificationService grantNotificationService; + private final KiasService kiasService; + private final PingService pingService; + + public GrantService(GrantRepository grantRepository, + FileService fileService, + DeadlineService deadlineService, + ProjectService projectService, + UserService userService, + PaperService paperService, + EventService eventService, + GrantNotificationService grantNotificationService, + KiasService kiasService, + PingService pingService) { + super(grantRepository, grantNotificationService, pingService, eventService); + this.grantRepository = grantRepository; + this.kiasService = kiasService; + this.fileService = fileService; + this.deadlineService = deadlineService; + this.projectService = projectService; + this.userService = userService; + this.paperService = paperService; + this.eventService = eventService; + this.grantNotificationService = grantNotificationService; + this.pingService = pingService; + } + + @Override + public PageableItems findAll(int offset, int count) { + final Page page = grantRepository.findAll(new OffsetablePageRequest(offset, count)); + return new PageableItems<>(page.getTotalElements(), page.getContent()); + } + + @Override + protected GrantListDto getActivityListDto(Grant entity) { + return new GrantListDto(entity); + } + + @Override + protected Grant getNewActivity() { + return new Grant(); + } + + @Override + protected GrantDto getNewActivityDto(Grant entity) { + return new GrantDto(entity); + } + + protected Grant copyFromDto(Grant grant, GrantDto grantDto) throws IOException { + grant.setId(grantDto.getId()); + grant.setComment(grantDto.getComment()); + grant.setStatus(grantDto.getStatus() == null ? APPLICATION : grantDto.getStatus()); + grant.setTitle(grantDto.getTitle()); + grant.setDeadlines(deadlineService.saveOrCreate(grantDto.getDeadlines())); + if (!grant.getFiles().isEmpty()) { + grant.setFiles(fileService.saveOrCreate(grantDto.getFiles().stream() + .filter(f -> !f.isDeleted()) + .collect(toList()))); + } + grant.getAuthors().clear(); + if (grantDto.getMembers() != null && !grantDto.getMembers().isEmpty()) { + grantDto.getMembers().forEach(memberDto -> grant.getAuthors().add(userService.findById(memberDto.getId()))); + } + if (grantDto.getLeaderId() != null) { + grant.setLeader(userService.findById(grantDto.getLeaderId())); + } + grant.getPapers().clear(); + if (grantDto.getPaperIds() != null && !grantDto.getPaperIds().isEmpty()) { + grantDto.getPaperIds().forEach(paperIds -> grant.getPapers().add(paperService.findById(paperIds))); + } + return grant; + } + + @Override + protected void doActionsOnDiffObjects(Grant oldEntity, Grant entity) { + entity.getAuthors().forEach(author -> { + if (!oldEntity.getAuthors().contains(author)) { + grantNotificationService.sendAuthorsChangeNotification(entity, oldEntity.getAuthors()); + } + }); + if (!entity.getLeader().equals(oldEntity.getLeader())) { + grantNotificationService.sendLeaderChangeNotification(entity, oldEntity.getLeader()); + } + } + + @Override + protected List getEvents(Grant entity) { + return eventService.findByGrant(entity); + } + + public List getGrantStatuses() { + return Arrays.asList(Grant.GrantStatus.values()); + } + + private boolean saveFromKias(GrantDto grantDto) throws IOException { + grantDto.setTitle(grantDto.getTitle()); + if (checkUniqueName(grantDto.getTitle(), grantDto.getId())) { + Grant grantFromDB = grantRepository.findByTitle(grantDto.getTitle()); //грант с таким же названием из бд + if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают + return false; + } else { //иначе грант уже был в системе, но в другом году, поэтому надо создать + create(grantDto); + return true; + } + } else { //иначе такого гранта ещё нет, поэтому надо создать + create(grantDto); + return true; + } + } + + private boolean checkSameDeadline(GrantDto grantDto, Integer id) { + Date date = DateUtils.clearTime(grantDto.getDeadlines().get(0).getDate()); //дата с сайта киас + Date foundGrantDate = DateUtils.clearTime(deadlineService.findByGrantIdAndDate(id, date)); + return foundGrantDate != null && foundGrantDate.compareTo(date) == 0; + } + + @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"); + } + } + } + + @Override + public PageableItems findAllActiveDto(int offset, int count) { + return convertPageable(findAllActive(offset, count), GrantDashboardDto::new); + } + + @Override + public PageableItems findAllActive(int offset, int count) { + Page activeGrantsPage = grantRepository.findAllActive(new OffsetablePageRequest(offset, count)); + return new PageableItems<>(activeGrantsPage.getTotalElements(), activeGrantsPage.getContent()); + } + + @Transactional + public void ping(int grantId) { + pingService.addPing(findById(grantId)); + } +} diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/activity/grant/service/KiasService.java similarity index 93% rename from src/main/java/ru/ulstu/grant/service/KiasService.java rename to src/main/java/ru/ulstu/activity/grant/service/KiasService.java index dea6f55..3b47d78 100644 --- a/src/main/java/ru/ulstu/grant/service/KiasService.java +++ b/src/main/java/ru/ulstu/activity/grant/service/KiasService.java @@ -1,12 +1,12 @@ -package ru.ulstu.grant.service; +package ru.ulstu.activity.grant.service; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.HtmlPage; import org.springframework.stereotype.Service; +import ru.ulstu.activity.grant.model.GrantDto; +import ru.ulstu.activity.grant.page.KiasPage; import ru.ulstu.configuration.ApplicationProperties; -import ru.ulstu.grant.model.GrantDto; -import ru.ulstu.grant.page.KiasPage; import ru.ulstu.user.service.UserService; import java.io.IOException; @@ -32,7 +32,7 @@ public class KiasService { public List getNewGrantsDto() throws ParseException, IOException { Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId(); List grants = new ArrayList<>(); - try (final WebClient webClient = new WebClient()) { + try (WebClient webClient = new WebClient()) { for (Integer year : generateGrantYears()) { final HtmlPage page = webClient.getPage(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year)); grants.addAll(getKiasGrants(page)); diff --git a/src/main/java/ru/ulstu/activity/paper/controller/PaperController.java b/src/main/java/ru/ulstu/activity/paper/controller/PaperController.java new file mode 100644 index 0000000..ff219e8 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/paper/controller/PaperController.java @@ -0,0 +1,87 @@ +package ru.ulstu.activity.paper.controller; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import ru.ulstu.activity.api.ActivityController; +import ru.ulstu.activity.paper.model.PaperDashboardDto; +import ru.ulstu.activity.paper.model.PaperDto; +import ru.ulstu.activity.paper.model.PaperListDto; +import ru.ulstu.activity.paper.model.PaperStatusDto; +import ru.ulstu.activity.paper.model.PaperTypeDto; +import ru.ulstu.activity.paper.service.PaperService; +import ru.ulstu.configuration.Constants; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.core.model.response.Response; +import ru.ulstu.user.model.User; + +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequestMapping(Constants.API_1_0 + "papers") +public class PaperController implements ActivityController { + private final PaperService paperService; + + public PaperController(PaperService paperService) { + this.paperService = paperService; + } + + @GetMapping("list") + public Response> getList(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "10") int count) { + return new Response<>(paperService.findAllDto(offset, count)); + } + + @GetMapping("dashboard") + public Response> getDashboard(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "10") int count) { + return new Response<>(paperService.findAllActiveDto(offset, count)); + } + + @GetMapping("{paper-id}") + public Response get(@PathVariable("paper-id") Integer paperId) { + return new Response<>(paperService.findDtoById(paperId)); + } + + @PostMapping + public Response create(@RequestBody @Valid PaperDto paperDto) { + return new Response<>(paperService.create(paperDto)); + } + + @PutMapping + public Response update(@RequestBody @Valid PaperDto paperDto) { + return new Response<>(paperService.update(paperDto)); + } + + @DeleteMapping("/{paper-id}") + public Response delete(@PathVariable("paper-id") Integer paperId) { + return new Response<>(paperService.delete(paperId)); + } + + @PostMapping("ping/{paper-id}") + public void ping(@PathVariable("paper-id") int paperId) { + paperService.ping(paperId); + } + + @GetMapping("allAuthors") + public Response> getAllAuthors() { + return new Response<>(paperService.getPaperAuthors()); + } + + @GetMapping("allTypes") + public Response> getPaperTypes() { + return new Response<>(paperService.getPaperTypes()); + } + + @GetMapping("allStatuses") + public Response> getPaperStatuses() { + return new Response<>(paperService.getPaperStatuses()); + } +} diff --git a/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java b/src/main/java/ru/ulstu/activity/paper/model/AutoCompleteData.java similarity index 96% rename from src/main/java/ru/ulstu/paper/model/AutoCompleteData.java rename to src/main/java/ru/ulstu/activity/paper/model/AutoCompleteData.java index 91c3bf4..859b265 100644 --- a/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java +++ b/src/main/java/ru/ulstu/activity/paper/model/AutoCompleteData.java @@ -1,4 +1,4 @@ -package ru.ulstu.paper.model; +package ru.ulstu.activity.paper.model; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/ru/ulstu/paper/model/Paper.java b/src/main/java/ru/ulstu/activity/paper/model/Paper.java similarity index 90% rename from src/main/java/ru/ulstu/paper/model/Paper.java rename to src/main/java/ru/ulstu/activity/paper/model/Paper.java index f7b851c..49f083f 100644 --- a/src/main/java/ru/ulstu/paper/model/Paper.java +++ b/src/main/java/ru/ulstu/activity/paper/model/Paper.java @@ -1,15 +1,14 @@ -package ru.ulstu.paper.model; +package ru.ulstu.activity.paper.model; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.EventSource; -import ru.ulstu.core.model.UserActivity; -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 ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.common.model.EventSource; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.file.model.FileData; +import ru.ulstu.activity.grant.model.Grant; +import ru.ulstu.activity.timeline.model.Event; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; @@ -37,7 +36,7 @@ import java.util.Set; @Entity @DiscriminatorValue("PAPER") -public class Paper extends BaseEntity implements UserActivity, EventSource { +public class Paper extends AbstractActivity implements EventSource { public enum PaperStatus { ATTENTION("Обратить внимание"), ON_PREPARATION("На подготовке"), @@ -93,7 +92,7 @@ public class Paper extends BaseEntity implements UserActivity, EventSource { @Temporal(TemporalType.TIMESTAMP) private Date updateDate = new Date(); - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "paper_id", unique = true) @Fetch(FetchMode.SUBSELECT) @OrderBy("date") @@ -109,12 +108,12 @@ public class Paper extends BaseEntity implements UserActivity, EventSource { @JoinColumn(name = "paper_id") private List events = new ArrayList<>(); - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "paper_id", unique = true) @Fetch(FetchMode.SUBSELECT) private List files = new ArrayList<>(); - @ManyToMany(fetch = FetchType.EAGER) + @ManyToMany(fetch = FetchType.LAZY) private Set authors = new HashSet<>(); @Column(name = "latex_text") @@ -126,7 +125,7 @@ public class Paper extends BaseEntity implements UserActivity, EventSource { @ManyToMany(mappedBy = "papers") private List grants; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "paper_id", unique = true) @Fetch(FetchMode.SUBSELECT) private List references = new ArrayList<>(); @@ -199,6 +198,10 @@ public class Paper extends BaseEntity implements UserActivity, EventSource { return title; } + public void setTitle(String title) { + this.title = title; + } + @Override public List getRecipients() { return new ArrayList<>(authors); @@ -209,10 +212,6 @@ public class Paper extends BaseEntity implements UserActivity, EventSource { event.setPaper(this); } - public void setTitle(String title) { - this.title = title; - } - public Set getAuthors() { return authors; } @@ -262,8 +261,8 @@ public class Paper extends BaseEntity implements UserActivity, EventSource { } @Override - public Set getActivityUsers() { - return getAuthors(); + public Set getActivityMembers() { + return authors; } public List getReferences() { @@ -323,4 +322,9 @@ public class Paper extends BaseEntity implements UserActivity, EventSource { public int hashCode() { return Objects.hash(super.hashCode(), title, status, type, createDate, updateDate, deadlines, comment, url, locked, events, files, authors, latexText, conferences, grants); } + + @Override + public String getSuffix() { + return "статьи"; + } } diff --git a/src/main/java/ru/ulstu/activity/paper/model/PaperDashboardDto.java b/src/main/java/ru/ulstu/activity/paper/model/PaperDashboardDto.java new file mode 100644 index 0000000..ef9d0e2 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/paper/model/PaperDashboardDto.java @@ -0,0 +1,45 @@ +package ru.ulstu.activity.paper.model; + +import ru.ulstu.activity.api.model.ActivityDashboardDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; + +import java.util.Set; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class PaperDashboardDto extends ActivityDashboardDto { + private Paper.PaperStatus status; + private Set authors; + private String url; + + public PaperDashboardDto(Paper paper) { + super(paper.getId(), paper.getTitle()); + this.status = paper.getStatus(); + this.authors = convert(paper.getAuthors(), ScienceGroupMemberDto::new); + this.url = paper.getUrl(); + } + + public Paper.PaperStatus getStatus() { + return status; + } + + public void setStatus(Paper.PaperStatus status) { + this.status = status; + } + + public Set getAuthors() { + return authors; + } + + public void setAuthors(Set authors) { + this.authors = authors; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } +} diff --git a/src/main/java/ru/ulstu/paper/model/PaperDto.java b/src/main/java/ru/ulstu/activity/paper/model/PaperDto.java similarity index 54% rename from src/main/java/ru/ulstu/paper/model/PaperDto.java rename to src/main/java/ru/ulstu/activity/paper/model/PaperDto.java index cc44af5..89ceb8e 100644 --- a/src/main/java/ru/ulstu/paper/model/PaperDto.java +++ b/src/main/java/ru/ulstu/activity/paper/model/PaperDto.java @@ -1,11 +1,11 @@ -package ru.ulstu.paper.model; +package ru.ulstu.activity.paper.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.StringUtils; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.file.model.FileDataDto; -import ru.ulstu.user.model.UserDto; +import ru.ulstu.activity.api.model.ActivityDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; +import ru.ulstu.activity.deadline.model.DeadlineDto; +import ru.ulstu.activity.file.model.FileDataDto; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; @@ -13,14 +13,10 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; -import java.util.stream.Collectors; import static ru.ulstu.core.util.StreamApiUtils.convert; -public class PaperDto { - private final static int MAX_AUTHORS_LENGTH = 60; - - private Integer id; +public class PaperDto extends ActivityDto { @NotEmpty @Size(min = 3, max = 254) private String title; @@ -29,22 +25,19 @@ public class PaperDto { private Date createDate; private Date updateDate; @NotEmpty - private List deadlines = new ArrayList<>(); + private List deadlines = new ArrayList<>(); private String comment; private String url; private Boolean locked; private List files = new ArrayList<>(); - private Set authorIds; - private Set authors; - private Integer filterAuthorId; - private String latexText; - private List references = new ArrayList<>(); - private ReferenceDto.FormatStandard formatStandard = ReferenceDto.FormatStandard.GOST; + private Set authors; - public PaperDto() { - deadlines.add(new Deadline()); + public String getLatexText() { + return latexText; } + private String latexText; + @JsonCreator public PaperDto(@JsonProperty("id") Integer id, @JsonProperty("title") String title, @@ -52,17 +45,13 @@ public class PaperDto { @JsonProperty("type") Paper.PaperType type, @JsonProperty("createDate") Date createDate, @JsonProperty("updateDate") Date updateDate, - @JsonProperty("deadlines") List deadlines, + @JsonProperty("deadlines") List deadlines, @JsonProperty("comment") String comment, - @JsonProperty("latex_text") String latexText, @JsonProperty("url") String url, @JsonProperty("locked") Boolean locked, @JsonProperty("files") List files, - @JsonProperty("authorIds") Set authorIds, - @JsonProperty("authors") Set authors, - @JsonProperty("references") List references, - @JsonProperty("formatStandard") ReferenceDto.FormatStandard formatStandard) { - this.id = id; + @JsonProperty("authors") Set authors) { + super(id); this.title = title; this.status = status; this.type = type; @@ -71,38 +60,24 @@ public class PaperDto { this.deadlines = deadlines; this.comment = comment; this.url = url; - this.latexText = latexText; this.locked = locked; this.files = files; this.authors = authors; - this.references = references; - this.formatStandard = formatStandard; } public PaperDto(Paper paper) { - this.id = paper.getId(); + super(paper.getId()); this.title = paper.getTitle(); this.status = paper.getStatus(); this.type = paper.getType(); this.createDate = paper.getCreateDate(); this.updateDate = paper.getUpdateDate(); - this.deadlines = paper.getDeadlines(); + this.deadlines = convert(paper.getDeadlines(), DeadlineDto::new); this.comment = paper.getComment(); this.url = paper.getUrl(); - this.latexText = paper.getLatexText(); this.locked = paper.getLocked(); 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() { - return id; - } - - public void setId(Integer id) { - this.id = id; + this.authors = convert(paper.getAuthors(), ScienceGroupMemberDto::new); } public String getTitle() { @@ -145,11 +120,11 @@ public class PaperDto { this.updateDate = updateDate; } - public List getDeadlines() { + public List getDeadlines() { return deadlines; } - public void setDeadlines(List deadlines) { + public void setDeadlines(List deadlines) { this.deadlines = deadlines; } @@ -177,22 +152,14 @@ public class PaperDto { this.files = files; } - public Set getAuthors() { + public Set getAuthors() { return authors; } - public void setAuthors(Set authors) { + public void setAuthors(Set authors) { this.authors = authors; } - public Set getAuthorIds() { - return authorIds; - } - - public void setAuthorIds(Set authorIds) { - this.authorIds = authorIds; - } - public String getUrl() { return url; } @@ -200,43 +167,4 @@ public class PaperDto { public void setUrl(String url) { this.url = url; } - - public String getLatexText() { - return latexText; - } - - public void setLatexText(String latexText) { - this.latexText = latexText; - } - - public String getAuthorsString() { - return StringUtils.abbreviate(authors - .stream() - .map(author -> author.getLastName()) - .collect(Collectors.joining(", ")), MAX_AUTHORS_LENGTH); - } - - public Integer getFilterAuthorId() { - return filterAuthorId; - } - - 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/PaperListDto.java b/src/main/java/ru/ulstu/activity/paper/model/PaperFilterListDto.java similarity index 70% rename from src/main/java/ru/ulstu/paper/model/PaperListDto.java rename to src/main/java/ru/ulstu/activity/paper/model/PaperFilterListDto.java index 871047a..d7cf82c 100644 --- a/src/main/java/ru/ulstu/paper/model/PaperListDto.java +++ b/src/main/java/ru/ulstu/activity/paper/model/PaperFilterListDto.java @@ -1,27 +1,27 @@ -package ru.ulstu.paper.model; +package ru.ulstu.activity.paper.model; import java.util.List; -public class PaperListDto { - private List papers; +public class PaperFilterListDto { + private List papers; private Integer filterAuthorId; private Integer paperDeleteId; private Integer year; - public PaperListDto() { + public PaperFilterListDto() { } - public PaperListDto(List paperDtos, Integer filterAuthorId, Integer year) { + public PaperFilterListDto(List paperDtos, Integer filterAuthorId, Integer year) { this.papers = paperDtos; this.filterAuthorId = filterAuthorId; this.year = year; } - public List getPapers() { + public List getPapers() { return papers; } - public void setPapers(List papers) { + public void setPapers(List papers) { this.papers = papers; } diff --git a/src/main/java/ru/ulstu/activity/paper/model/PaperListDto.java b/src/main/java/ru/ulstu/activity/paper/model/PaperListDto.java new file mode 100644 index 0000000..605c523 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/paper/model/PaperListDto.java @@ -0,0 +1,27 @@ +package ru.ulstu.activity.paper.model; + +import ru.ulstu.activity.api.model.ActivityListDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; + +import java.util.Set; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class PaperListDto extends ActivityListDto { + private final Paper.PaperStatus status; + private final Set authors; + + public PaperListDto(Paper paper) { + super(paper.getId(), paper.getTitle()); + this.status = paper.getStatus(); + this.authors = convert(paper.getAuthors(), ScienceGroupMemberDto::new); + } + + public Paper.PaperStatus getStatus() { + return status; + } + + public Set getAuthors() { + return authors; + } +} diff --git a/src/main/java/ru/ulstu/activity/paper/model/PaperStatusDto.java b/src/main/java/ru/ulstu/activity/paper/model/PaperStatusDto.java new file mode 100644 index 0000000..a2cbf52 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/paper/model/PaperStatusDto.java @@ -0,0 +1,19 @@ +package ru.ulstu.activity.paper.model; + +public class PaperStatusDto { + private final String id; + private final String name; + + public PaperStatusDto(Paper.PaperStatus status) { + this.id = status.name(); + this.name = status.getStatusName(); + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/src/main/java/ru/ulstu/activity/paper/model/PaperTypeDto.java b/src/main/java/ru/ulstu/activity/paper/model/PaperTypeDto.java new file mode 100644 index 0000000..1f48f60 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/paper/model/PaperTypeDto.java @@ -0,0 +1,19 @@ +package ru.ulstu.activity.paper.model; + +public class PaperTypeDto { + private final String id; + private final String name; + + public PaperTypeDto(Paper.PaperType type) { + this.id = type.name(); + this.name = type.getTypeName(); + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/src/main/java/ru/ulstu/paper/model/Reference.java b/src/main/java/ru/ulstu/activity/paper/model/Reference.java similarity index 98% rename from src/main/java/ru/ulstu/paper/model/Reference.java rename to src/main/java/ru/ulstu/activity/paper/model/Reference.java index 289cdc1..f64c013 100644 --- a/src/main/java/ru/ulstu/paper/model/Reference.java +++ b/src/main/java/ru/ulstu/activity/paper/model/Reference.java @@ -1,4 +1,4 @@ -package ru.ulstu.paper.model; +package ru.ulstu.activity.paper.model; import ru.ulstu.core.model.BaseEntity; diff --git a/src/main/java/ru/ulstu/paper/model/ReferenceDto.java b/src/main/java/ru/ulstu/activity/paper/model/ReferenceDto.java similarity index 99% rename from src/main/java/ru/ulstu/paper/model/ReferenceDto.java rename to src/main/java/ru/ulstu/activity/paper/model/ReferenceDto.java index bf7fed2..737465e 100644 --- a/src/main/java/ru/ulstu/paper/model/ReferenceDto.java +++ b/src/main/java/ru/ulstu/activity/paper/model/ReferenceDto.java @@ -1,4 +1,4 @@ -package ru.ulstu.paper.model; +package ru.ulstu.activity.paper.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/ru/ulstu/paper/service/LatexService.java b/src/main/java/ru/ulstu/activity/paper/service/LatexService.java similarity index 95% rename from src/main/java/ru/ulstu/paper/service/LatexService.java rename to src/main/java/ru/ulstu/activity/paper/service/LatexService.java index ea1bcfc..3b63150 100644 --- a/src/main/java/ru/ulstu/paper/service/LatexService.java +++ b/src/main/java/ru/ulstu/activity/paper/service/LatexService.java @@ -1,8 +1,8 @@ -package ru.ulstu.paper.service; +package ru.ulstu.activity.paper.service; import org.springframework.stereotype.Service; -import ru.ulstu.file.service.FileService; -import ru.ulstu.paper.model.PaperDto; +import ru.ulstu.activity.file.service.FileService; +import ru.ulstu.activity.paper.model.PaperDto; import java.io.BufferedReader; import java.io.File; diff --git a/src/main/java/ru/ulstu/paper/service/PaperCreateStrategy.java b/src/main/java/ru/ulstu/activity/paper/service/PaperCreateStrategy.java similarity index 79% rename from src/main/java/ru/ulstu/paper/service/PaperCreateStrategy.java rename to src/main/java/ru/ulstu/activity/paper/service/PaperCreateStrategy.java index d819d80..18dc8a6 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperCreateStrategy.java +++ b/src/main/java/ru/ulstu/activity/paper/service/PaperCreateStrategy.java @@ -1,9 +1,9 @@ -package ru.ulstu.paper.service; +package ru.ulstu.activity.paper.service; import org.springframework.stereotype.Service; +import ru.ulstu.activity.common.strategy.api.EntityCreateStrategy; +import ru.ulstu.activity.paper.model.Paper; import ru.ulstu.core.util.DateUtils; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.strategy.api.EntityCreateStrategy; import ru.ulstu.user.model.User; import java.util.Date; @@ -21,7 +21,7 @@ public class PaperCreateStrategy extends EntityCreateStrategy { @Override protected List getActiveEntities() { - return paperService.findAll(); + return (List) paperService.findAll(0, 100).getItems(); } @Override diff --git a/src/main/java/ru/ulstu/paper/service/PaperNotificationService.java b/src/main/java/ru/ulstu/activity/paper/service/PaperNotificationService.java similarity index 64% rename from src/main/java/ru/ulstu/paper/service/PaperNotificationService.java rename to src/main/java/ru/ulstu/activity/paper/service/PaperNotificationService.java index 5628c46..0b9f78e 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperNotificationService.java +++ b/src/main/java/ru/ulstu/activity/paper/service/PaperNotificationService.java @@ -1,17 +1,20 @@ -package ru.ulstu.paper.service; +package ru.ulstu.activity.paper.service; import com.google.common.collect.ImmutableMap; import org.springframework.stereotype.Service; +import ru.ulstu.activity.common.service.ActivityNotificationService; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.core.model.response.PageableItems; import ru.ulstu.core.util.DateUtils; -import ru.ulstu.paper.model.Paper; +import ru.ulstu.user.model.User; import ru.ulstu.user.service.MailService; import java.util.Date; -import java.util.List; import java.util.Map; +import java.util.Set; @Service -public class PaperNotificationService { +public class PaperNotificationService extends ActivityNotificationService { private final static int DAYS_TO_DEADLINE_NOTIFICATION = 7; private final static String TEMPLATE_DEADLINE = "paperDeadlineNotification"; private final static String TEMPLATE_CREATE = "paperCreateNotification"; @@ -23,16 +26,13 @@ public class PaperNotificationService { private final static String TITLE_STATUS_CHANGED = "Изменился статус статьи"; private final static String TITLE_FAILED = "Статья провалена"; - - private final MailService mailService; - public PaperNotificationService(MailService mailService) { - this.mailService = mailService; + super(mailService); } - public void sendDeadlineNotifications(List papers, boolean isDeadlineBeforeWeek) { + public void sendDeadlineNotifications(PageableItems papers, boolean isDeadlineBeforeWeek) { Date now = DateUtils.addDays(new Date(), DAYS_TO_DEADLINE_NOTIFICATION); - papers + papers.getItems() .stream() .filter(paper -> needToSendDeadlineNotification(paper, now, isDeadlineBeforeWeek)) .forEach(paper -> sendMessageDeadline(paper)); @@ -47,25 +47,35 @@ public class PaperNotificationService { private void sendMessageDeadline(Paper paper) { Map variables = ImmutableMap.of("paper", paper); - sendForAllAuhtors(variables, paper, TEMPLATE_DEADLINE, TITLE_DEADLINE); + sendForAllAuthors(variables, paper, TEMPLATE_DEADLINE, TITLE_DEADLINE); } public void sendCreateNotification(Paper paper) { Map variables = ImmutableMap.of("paper", paper); - sendForAllAuhtors(variables, paper, TEMPLATE_CREATE, TITLE_CREATE); + sendForAllAuthors(variables, paper, TEMPLATE_CREATE, TITLE_CREATE); + } + + public void sendCreateNotification(Paper paper, User author) { + Map variables = ImmutableMap.of("paper", paper); + sendForAuthor(variables, author, TEMPLATE_CREATE, TITLE_CREATE); + } + + public void sendCreateNotification(Paper paper, Set oldAuthors) { + paper.getAuthors() + .stream() + .filter(author -> !oldAuthors.contains(author)) + .forEach(author -> sendCreateNotification(paper, author)); } public void statusChangeNotification(Paper paper, Paper.PaperStatus oldStatus) { - Map variables = ImmutableMap.of("paper", paper, "oldStatus", oldStatus); - sendForAllAuhtors(variables, paper, TEMPLATE_STATUS_CHANGED, TITLE_STATUS_CHANGED); + if (paper.getStatus() != oldStatus) { + Map variables = ImmutableMap.of("paper", paper, "oldStatus", oldStatus); + sendForAllAuthors(variables, paper, TEMPLATE_STATUS_CHANGED, TITLE_STATUS_CHANGED); + } } public void sendFailedNotification(Paper paper, Paper.PaperStatus oldStatus) { Map variables = ImmutableMap.of("paper", paper, "oldStatus", oldStatus); - sendForAllAuhtors(variables, paper, TEMPLATE_FAILED, TITLE_FAILED); - } - - private void sendForAllAuhtors(Map variables, Paper paper, String template, String title) { - paper.getAuthors().forEach(author -> mailService.sendEmailFromTemplate(variables, author, template, title)); + sendForAllAuthors(variables, paper, TEMPLATE_FAILED, TITLE_FAILED); } } diff --git a/src/main/java/ru/ulstu/paper/repository/PaperRepository.java b/src/main/java/ru/ulstu/activity/paper/service/PaperRepository.java similarity index 50% rename from src/main/java/ru/ulstu/paper/repository/PaperRepository.java rename to src/main/java/ru/ulstu/activity/paper/service/PaperRepository.java index 42d3703..14b25bf 100644 --- a/src/main/java/ru/ulstu/paper/repository/PaperRepository.java +++ b/src/main/java/ru/ulstu/activity/paper/service/PaperRepository.java @@ -1,14 +1,17 @@ -package ru.ulstu.paper.repository; +package ru.ulstu.activity.paper.service; -import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import ru.ulstu.paper.model.Paper; +import ru.ulstu.activity.api.ActivityRepository; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.core.repository.JpaDetachableRepository; import ru.ulstu.user.model.User; import java.util.List; -public interface PaperRepository extends JpaRepository { +interface PaperRepository extends JpaDetachableRepository, ActivityRepository { @Query("SELECT p FROM Paper p WHERE (:author IS NULL OR :author MEMBER OF p.authors) AND (YEAR(p.createDate) = :year OR :year IS NULL)") List filter(@Param("author") User author, @Param("year") Integer year); @@ -24,4 +27,13 @@ public interface PaperRepository extends JpaRepository { List findByConferencesIsNullAndStatusNot(Paper.PaperStatus status); List findByIdNotInAndConferencesIsNullAndStatusNot(List paperIds, Paper.PaperStatus status); + + @Query("SELECT p FROM Paper p WHERE p.status NOT IN (:statuses)") + Page findAllWithoutStatuses(Pageable pageable, @Param("statuses") Paper.PaperStatus... statuses); + + @Query("SELECT p FROM Paper p ") + Page findAll(Pageable pageable); + + @Query("SELECT title FROM Paper p WHERE (p.title = :name) AND (:id IS NULL OR p.id != :id) ") + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); } diff --git a/src/main/java/ru/ulstu/paper/service/PaperScheduler.java b/src/main/java/ru/ulstu/activity/paper/service/PaperScheduler.java similarity index 90% rename from src/main/java/ru/ulstu/paper/service/PaperScheduler.java rename to src/main/java/ru/ulstu/activity/paper/service/PaperScheduler.java index a5acf63..936ed57 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperScheduler.java +++ b/src/main/java/ru/ulstu/activity/paper/service/PaperScheduler.java @@ -1,4 +1,4 @@ -package ru.ulstu.paper.service; +package ru.ulstu.activity.paper.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,14 +24,14 @@ public class PaperScheduler { @Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara") public void checkDeadlineBeforeWeek() { log.debug("PaperScheduler.checkDeadlineBeforeWeek started"); - paperNotificationService.sendDeadlineNotifications(paperService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); + paperNotificationService.sendDeadlineNotifications(paperService.findAll(0, 100), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); log.debug("PaperScheduler.checkDeadlineBeforeWeek finished"); } @Scheduled(cron = "0 0 8 * * ?", zone = "Europe/Samara") public void checkDeadlineAfterWeek() { log.debug("PaperScheduler.checkDeadlineAfterWeek started"); - paperNotificationService.sendDeadlineNotifications(paperService.findAll(), !IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); + paperNotificationService.sendDeadlineNotifications(paperService.findAll(0, 100), !IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); log.debug("PaperScheduler.checkDeadlineAfterWeek finished"); } diff --git a/src/main/java/ru/ulstu/activity/paper/service/PaperService.java b/src/main/java/ru/ulstu/activity/paper/service/PaperService.java new file mode 100644 index 0000000..40e7b48 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/paper/service/PaperService.java @@ -0,0 +1,201 @@ +package ru.ulstu.activity.paper.service; + +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.activity.common.service.ActivityService; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.deadline.service.DeadlineService; +import ru.ulstu.activity.file.service.FileService; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.activity.paper.model.PaperDashboardDto; +import ru.ulstu.activity.paper.model.PaperDto; +import ru.ulstu.activity.paper.model.PaperListDto; +import ru.ulstu.activity.paper.model.PaperStatusDto; +import ru.ulstu.activity.paper.model.PaperTypeDto; +import ru.ulstu.activity.ping.service.PingService; +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.activity.timeline.service.EventService; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import static java.util.stream.Collectors.toList; +import static org.hibernate.internal.util.collections.CollectionHelper.isNotEmpty; +import static org.springframework.util.ObjectUtils.isEmpty; +import static ru.ulstu.activity.paper.model.Paper.PaperStatus.ATTENTION; +import static ru.ulstu.activity.paper.model.Paper.PaperStatus.COMPLETED; +import static ru.ulstu.activity.paper.model.Paper.PaperStatus.DRAFT; +import static ru.ulstu.activity.paper.model.Paper.PaperStatus.FAILED; +import static ru.ulstu.activity.paper.model.Paper.PaperStatus.ON_PREPARATION; +import static ru.ulstu.activity.paper.model.Paper.PaperType.OTHER; +import static ru.ulstu.core.util.StreamApiUtils.convert; +import static ru.ulstu.core.util.StreamApiUtils.convertPageable; + +@Service +public class PaperService extends ActivityService { + private final PaperNotificationService paperNotificationService; + private final PaperRepository paperRepository; + private final UserService userService; + private final DeadlineService deadlineService; + private final FileService fileService; + private final EventService eventService; + private final PingService pingService; + + public PaperService(PaperRepository paperRepository, + FileService fileService, + PaperNotificationService paperNotificationService, + UserService userService, + DeadlineService deadlineService, + EventService eventService, + PingService pingService) { + super(paperRepository, paperNotificationService, pingService, eventService); + this.paperRepository = paperRepository; + this.fileService = fileService; + this.paperNotificationService = paperNotificationService; + this.userService = userService; + this.deadlineService = deadlineService; + this.eventService = eventService; + this.pingService = pingService; + } + + public PageableItems findAllActiveDto(int offset, int count) { + return convertPageable(findAllActive(offset, count), PaperDashboardDto::new); + } + + public PageableItems findAll(int offset, int count) { + final Page page = paperRepository.findAll(new OffsetablePageRequest(offset, count)); + return new PageableItems<>(page.getTotalElements(), sortPapers(page.getContent())); + } + + @Override + protected PaperListDto getActivityListDto(Paper entity) { + return new PaperListDto(entity); + } + + @Override + protected Paper getNewActivity() { + return new Paper(); + } + + @Override + protected PaperDto getNewActivityDto(Paper entity) { + return new PaperDto(entity); + } + + @Override + public PageableItems findAllActive(int offset, int count) { + Page activePapersPage = paperRepository.findAllWithoutStatuses(new OffsetablePageRequest(offset, count), COMPLETED, FAILED); + return new PageableItems<>(activePapersPage.getTotalElements(), sortPapers(activePapersPage.getContent())); + } + + @Override + protected List getEvents(Paper entity) { + return eventService.findByPaper(entity); + } + + @Override + protected void doActionsOnDiffObjects(Paper oldEntity, Paper entity) { + if (oldEntity.getStatus() != entity.getStatus()) { + paperNotificationService.statusChangeNotification(entity, oldEntity.getStatus()); + } + if (!oldEntity.getAuthors().equals(entity.getAuthors())) { + paperNotificationService.sendCreateNotification(entity, oldEntity.getAuthors()); + } + } + + protected Paper copyFromDto(Paper paper, PaperDto paperDto) { + paper.setComment(paperDto.getComment()); + paper.setUrl(paperDto.getUrl()); + paper.setCreateDate(paper.getCreateDate() == null ? new Date() : paper.getCreateDate()); + paper.setLocked(paperDto.getLocked()); + paper.setStatus(paperDto.getStatus() == null ? DRAFT : paperDto.getStatus()); + paper.setType(paperDto.getType() == null ? OTHER : paperDto.getType()); + paper.setTitle(paperDto.getTitle()); + paper.setUpdateDate(new Date()); + paper.setDeadlines(deadlineService.saveOrCreate(paperDto.getDeadlines())); + //TODO: move to service + try { + if (paperDto.getFiles() != null) { + paper.setFiles(fileService.saveOrCreate(paperDto.getFiles().stream() + .filter(f -> !f.isDeleted()) + .collect(toList()))); + } + } catch (IOException ex) { + throw new RuntimeException(ex); + } + paper.getAuthors().clear(); + if (isNotEmpty(paperDto.getAuthors())) { + paperDto.getAuthors().forEach(authors -> paper.getAuthors().add(userService.findById(authors.getId()))); + } + return paper; + } + + public List getPaperStatuses() { + return convert(Arrays.asList(Paper.PaperStatus.values()), PaperStatusDto::new); + } + + public List getPaperTypes() { + return convert(Arrays.asList(Paper.PaperType.values()), PaperTypeDto::new); + } + + @Transactional + public Paper create(String title, User user, Date deadlineDate) { + Paper paper = new Paper(); + paper.setTitle(title); + paper.getAuthors().add(user); + paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); + paper.setCreateDate(new Date()); + paper.setUpdateDate(new Date()); + paper.setStatus(DRAFT); + paper.setType(OTHER); + + return create(paper); + } + + private List sortPapers(List papers) { + return papers.stream().sorted((paper1, paper2) -> { + int statusCompareResult = + Integer.valueOf(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper1.getStatus())) + .compareTo(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper2.getStatus())); + if (statusCompareResult != 0) { + return statusCompareResult; + } + return paper1.getTitle().compareTo(paper2.getTitle()); + }).collect(toList()); + } + + public void closeFailedPapers() { + List papers = paperRepository.findAll() + .stream() + .filter(paper -> paper.lastDeadlineFailed() + && (paper.getStatus() == ON_PREPARATION + || paper.getStatus() == DRAFT + || paper.getStatus() == ATTENTION)) + .collect(toList()); + papers.forEach(paper -> { + Paper.PaperStatus oldStatus = paper.getStatus(); + paper.setStatus(Paper.PaperStatus.FAILED); + paperRepository.save(paper); + paperNotificationService.sendFailedNotification(paper, oldStatus); + }); + } + + public void save(PaperDto paperDto) { + if (isEmpty(paperDto.getId())) { + create(paperDto); + } else { + update(paperDto); + } + } + + public List getPaperAuthors() { + return userService.findAll(); + } +} diff --git a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java b/src/main/java/ru/ulstu/activity/paper/service/ReferenceRepository.java similarity index 89% rename from src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java rename to src/main/java/ru/ulstu/activity/paper/service/ReferenceRepository.java index 942a5b8..d613eb4 100644 --- a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java +++ b/src/main/java/ru/ulstu/activity/paper/service/ReferenceRepository.java @@ -1,8 +1,8 @@ -package ru.ulstu.paper.repository; +package ru.ulstu.activity.paper.service; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; -import ru.ulstu.paper.model.Reference; +import ru.ulstu.activity.paper.model.Reference; import java.util.List; diff --git a/src/main/java/ru/ulstu/ping/model/Ping.java b/src/main/java/ru/ulstu/activity/ping/model/Ping.java similarity index 82% rename from src/main/java/ru/ulstu/ping/model/Ping.java rename to src/main/java/ru/ulstu/activity/ping/model/Ping.java index 7118c22..1ec8c28 100644 --- a/src/main/java/ru/ulstu/ping/model/Ping.java +++ b/src/main/java/ru/ulstu/activity/ping/model/Ping.java @@ -1,15 +1,15 @@ -package ru.ulstu.ping.model; +package ru.ulstu.activity.ping.model; import org.hibernate.annotations.Any; import org.hibernate.annotations.AnyMetaDef; import org.hibernate.annotations.MetaValue; import org.springframework.format.annotation.DateTimeFormat; -import ru.ulstu.conference.model.Conference; +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.grant.model.Grant; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.activity.project.model.Project; import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.UserActivity; -import ru.ulstu.grant.model.Grant; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.project.model.Project; import ru.ulstu.user.model.User; import javax.persistence.Column; @@ -50,7 +50,7 @@ public class Ping extends BaseEntity { } ) @JoinColumn(name = "activity_id") - private UserActivity activity; + private AbstractActivity activity; public Ping() { } @@ -76,11 +76,11 @@ public class Ping extends BaseEntity { this.user = user; } - public UserActivity getActivity() { + public AbstractActivity getActivity() { return this.activity; } - public void setActivity(UserActivity activity) { + public void setActivity(AbstractActivity activity) { this.activity = activity; } } diff --git a/src/main/java/ru/ulstu/ping/model/PingInfo.java b/src/main/java/ru/ulstu/activity/ping/model/PingInfo.java similarity index 94% rename from src/main/java/ru/ulstu/ping/model/PingInfo.java rename to src/main/java/ru/ulstu/activity/ping/model/PingInfo.java index e8b943b..2b51d93 100644 --- a/src/main/java/ru/ulstu/ping/model/PingInfo.java +++ b/src/main/java/ru/ulstu/activity/ping/model/PingInfo.java @@ -1,4 +1,4 @@ -package ru.ulstu.ping.model; +package ru.ulstu.activity.ping.model; import ru.ulstu.user.model.User; diff --git a/src/main/java/ru/ulstu/ping/repository/PingRepository.java b/src/main/java/ru/ulstu/activity/ping/service/PingRepository.java similarity index 81% rename from src/main/java/ru/ulstu/ping/repository/PingRepository.java rename to src/main/java/ru/ulstu/activity/ping/service/PingRepository.java index cec24e7..2fbe51e 100644 --- a/src/main/java/ru/ulstu/ping/repository/PingRepository.java +++ b/src/main/java/ru/ulstu/activity/ping/service/PingRepository.java @@ -1,15 +1,15 @@ -package ru.ulstu.ping.repository; +package ru.ulstu.activity.ping.service; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.ping.model.Ping; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.ping.model.Ping; import java.util.Date; import java.util.List; -public interface PingRepository extends JpaRepository { +interface PingRepository extends JpaRepository { @Query("SELECT count(*) FROM Ping p WHERE (DAY(p.date) = :day) AND (MONTH(p.date) = :month) AND (YEAR(p.date) = :year) AND (p.activityType = 'conference') AND (p.activity = :conference)") long countByConferenceAndDate(@Param("conference") Conference conference, @Param("day") Integer day, @Param("month") Integer month, @Param("year") Integer year); diff --git a/src/main/java/ru/ulstu/ping/service/PingScheduler.java b/src/main/java/ru/ulstu/activity/ping/service/PingScheduler.java similarity index 84% rename from src/main/java/ru/ulstu/ping/service/PingScheduler.java rename to src/main/java/ru/ulstu/activity/ping/service/PingScheduler.java index ca8724d..17d3bfb 100644 --- a/src/main/java/ru/ulstu/ping/service/PingScheduler.java +++ b/src/main/java/ru/ulstu/activity/ping/service/PingScheduler.java @@ -1,14 +1,13 @@ -package ru.ulstu.ping.service; +package ru.ulstu.activity.ping.service; import com.google.common.collect.ImmutableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import ru.ulstu.core.model.UserActivity; -import ru.ulstu.ping.model.Ping; -import ru.ulstu.ping.model.PingInfo; -import ru.ulstu.ping.repository.PingRepository; +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.ping.model.Ping; +import ru.ulstu.activity.ping.model.PingInfo; import ru.ulstu.user.model.User; import ru.ulstu.user.service.MailService; @@ -19,10 +18,10 @@ import java.util.Set; @Service public class PingScheduler { + private final static String PING_MAIL_SUBJECT = "Ping статистика"; private final Logger log = LoggerFactory.getLogger(PingScheduler.class); private final PingRepository pingRepository; private final MailService mailService; - private final static String PING_MAIL_SUBJECT = "Ping статистика"; public PingScheduler(PingRepository pingRepository, MailService mailService) { this.pingRepository = pingRepository; @@ -37,8 +36,8 @@ public class PingScheduler { List pingInfos = new ArrayList<>(); for (Ping ping : pingRepository.findByDate(java.sql.Date.valueOf(LocalDate.now().minusWeeks(1)))) { - UserActivity pingActivity = ping.getActivity(); - Set users = pingActivity.getActivityUsers(); + AbstractActivity pingActivity = ping.getActivity(); + Set users = pingActivity.getActivityMembers(); for (User user : users) { PingInfo userPing = pingInfos.stream().filter(u -> u.getUser() == user).findFirst().orElse(null); diff --git a/src/main/java/ru/ulstu/ping/service/PingService.java b/src/main/java/ru/ulstu/activity/ping/service/PingService.java similarity index 73% rename from src/main/java/ru/ulstu/ping/service/PingService.java rename to src/main/java/ru/ulstu/activity/ping/service/PingService.java index 99ca26f..a4aed0e 100644 --- a/src/main/java/ru/ulstu/ping/service/PingService.java +++ b/src/main/java/ru/ulstu/activity/ping/service/PingService.java @@ -1,14 +1,12 @@ -package ru.ulstu.ping.service; +package ru.ulstu.activity.ping.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.core.model.UserActivity; -import ru.ulstu.ping.model.Ping; -import ru.ulstu.ping.repository.PingRepository; +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.ping.model.Ping; import ru.ulstu.user.service.UserService; -import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -19,14 +17,13 @@ public class PingService { private final UserService userService; public PingService(PingRepository pingRepository, - UserService userService, - PingScheduler pingScheduler) { + UserService userService) { this.pingRepository = pingRepository; this.userService = userService; } @Transactional - public Ping addPing(UserActivity activity) throws IOException { + public Ping addPing(AbstractActivity activity) { Ping newPing = new Ping(new Date(), userService.getCurrentUser()); newPing.setActivity(activity); return pingRepository.save(newPing); diff --git a/src/main/java/ru/ulstu/activity/project/controller/ProjectController.java b/src/main/java/ru/ulstu/activity/project/controller/ProjectController.java new file mode 100644 index 0000000..9a0b16e --- /dev/null +++ b/src/main/java/ru/ulstu/activity/project/controller/ProjectController.java @@ -0,0 +1,68 @@ +package ru.ulstu.activity.project.controller; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import ru.ulstu.activity.api.ActivityController; +import ru.ulstu.activity.project.model.ProjectDashboardDto; +import ru.ulstu.activity.project.model.ProjectDto; +import ru.ulstu.activity.project.model.ProjectListDto; +import ru.ulstu.activity.project.service.ProjectService; +import ru.ulstu.configuration.Constants; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.core.model.response.Response; + +import javax.validation.Valid; + +@RestController +@RequestMapping(Constants.API_1_0 + "projects") +public class ProjectController implements ActivityController { + private final ProjectService projectService; + + public ProjectController(ProjectService projectService) { + this.projectService = projectService; + } + + @GetMapping("list") + public Response> getList(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "10") int count) { + return new Response<>(projectService.findAllDto(offset, count)); + } + + @GetMapping("dashboard") + public Response> getDashboard(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "10") int count) { + return new Response<>(projectService.findAllActiveDto(offset, count)); + } + + @GetMapping("{project-id}") + public Response get(@PathVariable("project-id") Integer projectId) { + return new Response<>(projectService.findDtoById(projectId)); + } + + @PostMapping + public Response create(@RequestBody @Valid ProjectDto projectDto) { + return new Response<>(projectService.create(projectDto)); + } + + @PutMapping + public Response update(@RequestBody @Valid ProjectDto projectDto) { + return new Response<>(projectService.update(projectDto)); + } + + @DeleteMapping("/{project-id}") + public Response delete(@PathVariable("project-id") Integer projectId) { + return new Response<>(projectService.delete(projectId)); + } + + @PostMapping("ping/{project-id}") + public void ping(@PathVariable("project-id") int projectId) { + projectService.ping(projectId); + } +} diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/activity/project/model/Project.java similarity index 89% rename from src/main/java/ru/ulstu/project/model/Project.java rename to src/main/java/ru/ulstu/activity/project/model/Project.java index 0ddb982..46840cb 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/activity/project/model/Project.java @@ -1,14 +1,13 @@ -package ru.ulstu.project.model; +package ru.ulstu.activity.project.model; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.EventSource; -import ru.ulstu.core.model.UserActivity; -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 ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.common.model.EventSource; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.file.model.FileData; +import ru.ulstu.activity.grant.model.Grant; +import ru.ulstu.activity.timeline.model.Event; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; @@ -32,7 +31,7 @@ import java.util.Set; @Entity @DiscriminatorValue("PROJECT") -public class Project extends BaseEntity implements UserActivity, EventSource { +public class Project extends AbstractActivity implements EventSource { public enum ProjectStatus { TECHNICAL_TASK("Техническое задание"), @@ -96,6 +95,10 @@ public class Project extends BaseEntity implements UserActivity, EventSource { return title; } + public void setTitle(String title) { + this.title = title; + } + @Override public List getRecipients() { return executors != null ? new ArrayList<>(executors) : Collections.emptyList(); @@ -106,8 +109,9 @@ public class Project extends BaseEntity implements UserActivity, EventSource { event.setProject(this); } - public void setTitle(String title) { - this.title = title; + @Override + public String getSuffix() { + return "проекта"; } public ProjectStatus getStatus() { @@ -179,7 +183,7 @@ public class Project extends BaseEntity implements UserActivity, EventSource { } @Override - public Set getActivityUsers() { + public Set getActivityMembers() { return new HashSet<>(); } diff --git a/src/main/java/ru/ulstu/activity/project/model/ProjectDashboardDto.java b/src/main/java/ru/ulstu/activity/project/model/ProjectDashboardDto.java new file mode 100644 index 0000000..ce3c46b --- /dev/null +++ b/src/main/java/ru/ulstu/activity/project/model/ProjectDashboardDto.java @@ -0,0 +1,27 @@ +package ru.ulstu.activity.project.model; + +import ru.ulstu.activity.api.model.ActivityDashboardDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; + +import java.util.List; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class ProjectDashboardDto extends ActivityDashboardDto { + private final Project.ProjectStatus status; + private final List executors; + + public ProjectDashboardDto(Project project) { + super(project.getId(), project.getTitle()); + this.status = project.getStatus(); + this.executors = convert(project.getExecutors(), ScienceGroupMemberDto::new); + } + + public Project.ProjectStatus getStatus() { + return status; + } + + public List getExecutors() { + return executors; + } +} diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/activity/project/model/ProjectDto.java similarity index 54% rename from src/main/java/ru/ulstu/project/model/ProjectDto.java rename to src/main/java/ru/ulstu/activity/project/model/ProjectDto.java index d5a8345..f97b10d 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/activity/project/model/ProjectDto.java @@ -1,99 +1,64 @@ -package ru.ulstu.project.model; +package ru.ulstu.activity.project.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import org.thymeleaf.util.StringUtils; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.file.model.FileDataDto; -import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.activity.api.model.ActivityDto; +import ru.ulstu.activity.deadline.model.DeadlineDto; +import ru.ulstu.activity.file.model.FileDataDto; import ru.ulstu.user.model.User; -import ru.ulstu.user.model.UserDto; import javax.validation.constraints.NotEmpty; import java.util.ArrayList; import java.util.HashSet; 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; - +public class ProjectDto extends ActivityDto { @NotEmpty private String title; private Project.ProjectStatus status; private String description; - private List deadlines = new ArrayList<>(); - private GrantDto grant; + private List deadlines = new ArrayList<>(); private String repository; private List files = new ArrayList<>(); - private List removedDeadlineIds = new ArrayList<>(); private Set executorIds; - private List executors; private List grantIds; - private List grants; - - private final static int MAX_EXECUTORS_LENGTH = 40; - - public ProjectDto() { - } - - public ProjectDto(String title) { - this.title = title; - } @JsonCreator public ProjectDto(@JsonProperty("id") Integer id, @JsonProperty("title") String title, @JsonProperty("status") Project.ProjectStatus status, @JsonProperty("description") String description, - @JsonProperty("grant") GrantDto grant, @JsonProperty("repository") String repository, @JsonProperty("files") List files, - @JsonProperty("deadlines") List deadlines, + @JsonProperty("deadlines") List deadlines, @JsonProperty("executorIds") Set executorIds, - @JsonProperty("executors") List executors, - @JsonProperty("grantIds") List grantIds, - @JsonProperty("grants") List grants) { - this.id = id; + @JsonProperty("grantIds") List grantIds) { + super(id); this.title = title; this.status = status; this.description = description; - this.grant = grant; this.repository = repository; this.deadlines = deadlines; this.files = files; this.executorIds = executorIds; - this.executors = executors; this.grantIds = grantIds; - this.grants = grants; } public ProjectDto(Project project) { - Set users = new HashSet(project.getExecutors()); - this.id = project.getId(); + super(project.getId()); + Set users = new HashSet<>(project.getExecutors()); this.title = project.getTitle(); this.status = project.getStatus(); this.description = project.getDescription(); this.files = convert(project.getFiles(), FileDataDto::new); - this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant()); this.repository = project.getRepository(); - this.deadlines = project.getDeadlines(); + this.deadlines = convert(project.getDeadlines(), DeadlineDto::new); this.executorIds = convert(users, user -> user.getId()); - this.executors = convert(project.getExecutors(), UserDto::new); this.grantIds = convert(project.getGrants(), grant -> grant.getId()); - this.grants = convert(project.getGrants(), GrantDto::new); - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; } public String getTitle() { @@ -120,14 +85,6 @@ public class ProjectDto { this.description = description; } - public GrantDto getGrant() { - return grant; - } - - public void setGrant(GrantDto grant) { - this.grant = grant; - } - public String getRepository() { return repository; } @@ -136,11 +93,11 @@ public class ProjectDto { this.repository = repository; } - public List getDeadlines() { + public List getDeadlines() { return deadlines; } - public void setDeadlines(List deadlines) { + public void setDeadlines(List deadlines) { this.deadlines = deadlines; } @@ -152,14 +109,6 @@ public class ProjectDto { this.files = files; } - public List getRemovedDeadlineIds() { - return removedDeadlineIds; - } - - public void setRemovedDeadlineIds(List removedDeadlineIds) { - this.removedDeadlineIds = removedDeadlineIds; - } - public Set getExecutorIds() { return executorIds; } @@ -168,21 +117,6 @@ public class ProjectDto { this.executorIds = executorIds; } - public List getExecutors() { - return executors; - } - - public void setExecutors(List executors) { - this.executors = executors; - } - - public String getExecutorsString() { - return StringUtils.abbreviate(executors - .stream() - .map(executor -> executor.getLastName()) - .collect(Collectors.joining(", ")), MAX_EXECUTORS_LENGTH); - } - public List getGrantIds() { return grantIds; } @@ -190,12 +124,4 @@ public class ProjectDto { public void setGrantIds(List grantIds) { this.grantIds = grantIds; } - - public List getGrants() { - return grants; - } - - public void setGrants(List grants) { - this.grants = grants; - } } diff --git a/src/main/java/ru/ulstu/activity/project/model/ProjectListDto.java b/src/main/java/ru/ulstu/activity/project/model/ProjectListDto.java new file mode 100644 index 0000000..b1cd440 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/project/model/ProjectListDto.java @@ -0,0 +1,27 @@ +package ru.ulstu.activity.project.model; + +import ru.ulstu.activity.api.model.ActivityListDto; +import ru.ulstu.activity.common.model.ScienceGroupMemberDto; + +import java.util.List; + +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class ProjectListDto extends ActivityListDto { + private final Project.ProjectStatus status; + private final List executors; + + public ProjectListDto(Project project) { + super(project.getId(), project.getTitle()); + this.status = project.getStatus(); + this.executors = convert(project.getExecutors(), ScienceGroupMemberDto::new); + } + + public Project.ProjectStatus getStatus() { + return status; + } + + public List getExecutors() { + return executors; + } +} diff --git a/src/main/java/ru/ulstu/activity/project/service/ProjectNotificationService.java b/src/main/java/ru/ulstu/activity/project/service/ProjectNotificationService.java new file mode 100644 index 0000000..c8d6fcb --- /dev/null +++ b/src/main/java/ru/ulstu/activity/project/service/ProjectNotificationService.java @@ -0,0 +1,18 @@ +package ru.ulstu.activity.project.service; + +import org.springframework.stereotype.Service; +import ru.ulstu.activity.common.service.ActivityNotificationService; +import ru.ulstu.activity.project.model.Project; +import ru.ulstu.user.service.MailService; + +@Service +public class ProjectNotificationService extends ActivityNotificationService { + + public ProjectNotificationService(MailService mailService) { + super(mailService); + } + + public void sendCreateNotification(Project project) { + throw new RuntimeException("not implemented yet"); + } +} diff --git a/src/main/java/ru/ulstu/activity/project/service/ProjectRepository.java b/src/main/java/ru/ulstu/activity/project/service/ProjectRepository.java new file mode 100644 index 0000000..5e4dde4 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/project/service/ProjectRepository.java @@ -0,0 +1,17 @@ +package ru.ulstu.activity.project.service; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.ulstu.activity.api.ActivityRepository; +import ru.ulstu.activity.project.model.Project; + +interface ProjectRepository extends JpaRepository, ActivityRepository { + @Query("SELECT p FROM Project p WHERE p.status NOT IN (:statuses)") + Page findAllWithoutStatuses(Pageable pageable, @Param("statuses") Project.ProjectStatus... statuses); + + @Query("SELECT p.title FROM Project p WHERE (p.title = :name) AND (:id IS NULL OR p.id != :id) ") + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); +} diff --git a/src/main/java/ru/ulstu/activity/project/service/ProjectService.java b/src/main/java/ru/ulstu/activity/project/service/ProjectService.java new file mode 100644 index 0000000..79c9d47 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/project/service/ProjectService.java @@ -0,0 +1,96 @@ +package ru.ulstu.activity.project.service; + +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; +import ru.ulstu.activity.common.service.ActivityService; +import ru.ulstu.activity.deadline.service.DeadlineService; +import ru.ulstu.activity.file.service.FileService; +import ru.ulstu.activity.ping.service.PingService; +import ru.ulstu.activity.project.model.Project; +import ru.ulstu.activity.project.model.ProjectDashboardDto; +import ru.ulstu.activity.project.model.ProjectDto; +import ru.ulstu.activity.project.model.ProjectListDto; +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.activity.timeline.service.EventService; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.response.PageableItems; + +import java.io.IOException; +import java.util.List; + +import static java.util.stream.Collectors.toList; +import static ru.ulstu.activity.project.model.Project.ProjectStatus.CLOSED; +import static ru.ulstu.activity.project.model.Project.ProjectStatus.FAILED; +import static ru.ulstu.activity.project.model.Project.ProjectStatus.TECHNICAL_TASK; +import static ru.ulstu.core.util.StreamApiUtils.convertPageable; + +@Service +public class ProjectService extends ActivityService { + private final ProjectRepository projectRepository; + private final DeadlineService deadlineService; + private final FileService fileService; + private final PingService pingService; + private final EventService eventService; + + public ProjectService(ProjectRepository projectRepository, + ProjectNotificationService projectNotificationService, + DeadlineService deadlineService, + FileService fileService, + PingService pingService, EventService eventService) { + super(projectRepository, projectNotificationService, pingService, eventService); + this.projectRepository = projectRepository; + this.deadlineService = deadlineService; + this.fileService = fileService; + this.pingService = pingService; + this.eventService = eventService; + } + + @Override + public PageableItems findAllActiveDto(int offset, int count) { + return convertPageable(findAllActive(offset, count), ProjectDashboardDto::new); + } + + @Override + public PageableItems findAllActive(int offset, int count) { + Page activeProjectPage = projectRepository.findAllWithoutStatuses(new OffsetablePageRequest(offset, count), CLOSED, FAILED); + return new PageableItems<>(activeProjectPage.getTotalElements(), activeProjectPage.getContent()); + } + + @Override + protected void doActionsOnDiffObjects(Project oldEntity, Project entity) { + //TODO + } + + @Override + protected List getEvents(Project entity) { + return eventService.findByProject(entity); + } + + protected Project copyFromDto(Project project, ProjectDto projectDto) throws IOException { + project.setDescription(projectDto.getDescription()); + project.setStatus(projectDto.getStatus() == null ? TECHNICAL_TASK : projectDto.getStatus()); + project.setTitle(projectDto.getTitle()); + project.setRepository(projectDto.getRepository()); + project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines())); + project.setFiles(fileService.saveOrCreate(projectDto.getFiles().stream() + .filter(f -> !f.isDeleted()) + .collect(toList()))); + project.getGrants().clear(); + return project; + } + + @Override + protected ProjectListDto getActivityListDto(Project entity) { + return new ProjectListDto(entity); + } + + @Override + protected Project getNewActivity() { + return new Project(); + } + + @Override + protected ProjectDto getNewActivityDto(Project entity) { + return new ProjectDto(entity); + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/activity/students/controller/TaskController.java b/src/main/java/ru/ulstu/activity/students/controller/TaskController.java new file mode 100644 index 0000000..8cf808a --- /dev/null +++ b/src/main/java/ru/ulstu/activity/students/controller/TaskController.java @@ -0,0 +1,69 @@ +package ru.ulstu.activity.students.controller; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import ru.ulstu.activity.api.ActivityController; +import ru.ulstu.activity.students.model.TaskDashboardDto; +import ru.ulstu.activity.students.model.TaskDto; +import ru.ulstu.activity.students.model.TaskListDto; +import ru.ulstu.activity.students.service.TaskService; +import ru.ulstu.configuration.Constants; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.core.model.response.Response; + +import javax.validation.Valid; + +@RestController +@RequestMapping(Constants.API_1_0 + "students") +public class TaskController implements ActivityController { + + private final TaskService taskService; + + public TaskController(TaskService taskService) { + this.taskService = taskService; + } + + @GetMapping("list") + public Response> getList(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "10") int count) { + return new Response<>(taskService.findAllDto(offset, count)); + } + + @GetMapping("dashboard") + public Response> getDashboard(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "10") int count) { + return new Response<>(taskService.findAllActiveDto(offset, count)); + } + + @GetMapping("{task-id}") + public Response get(@PathVariable("task-id") Integer taskId) { + return new Response<>(taskService.findDtoById(taskId)); + } + + @PostMapping + public Response create(@RequestBody @Valid TaskDto taskDto) { + return new Response<>(taskService.create(taskDto)); + } + + @PutMapping + public Response update(@RequestBody @Valid TaskDto paperDto) { + return new Response<>(taskService.update(paperDto)); + } + + @DeleteMapping("{task-id}") + public Response delete(@PathVariable("task-id") Integer taskId) { + return new Response<>(taskService.delete(taskId)); + } + + @PostMapping("ping/{task-id}") + public void ping(@PathVariable("task-id") int taskId) { + taskService.ping(taskId); + } +} diff --git a/src/main/java/ru/ulstu/students/model/Scheduler.java b/src/main/java/ru/ulstu/activity/students/model/Scheduler.java similarity index 96% rename from src/main/java/ru/ulstu/students/model/Scheduler.java rename to src/main/java/ru/ulstu/activity/students/model/Scheduler.java index 67005b1..e886f91 100644 --- a/src/main/java/ru/ulstu/students/model/Scheduler.java +++ b/src/main/java/ru/ulstu/activity/students/model/Scheduler.java @@ -1,4 +1,4 @@ -package ru.ulstu.students.model; +package ru.ulstu.activity.students.model; import org.springframework.format.annotation.DateTimeFormat; import ru.ulstu.core.model.BaseEntity; diff --git a/src/main/java/ru/ulstu/students/model/Task.java b/src/main/java/ru/ulstu/activity/students/model/Task.java similarity index 83% rename from src/main/java/ru/ulstu/students/model/Task.java rename to src/main/java/ru/ulstu/activity/students/model/Task.java index 4da0aa2..4ae6a56 100644 --- a/src/main/java/ru/ulstu/students/model/Task.java +++ b/src/main/java/ru/ulstu/activity/students/model/Task.java @@ -1,12 +1,12 @@ -package ru.ulstu.students.model; +package ru.ulstu.activity.students.model; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.EventSource; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.tags.model.Tag; -import ru.ulstu.timeline.model.Event; +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.common.model.EventSource; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.tags.model.Tag; +import ru.ulstu.activity.timeline.model.Event; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; @@ -27,9 +27,10 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.Set; @Entity -public class Task extends BaseEntity implements EventSource { +public class Task extends AbstractActivity implements EventSource { public enum TaskStatus { IN_WORK("В работе"), @@ -90,6 +91,11 @@ public class Task extends BaseEntity implements EventSource { return Collections.emptyList(); } + @Override + public String getSuffix() { + return "задачи"; + } + @Override public void addObjectToEvent(Event event) { event.setTask(this); @@ -99,6 +105,16 @@ public class Task extends BaseEntity implements EventSource { this.title = title; } + @Override + public Set getActivityMembers() { + return Collections.emptySet(); + } + + @Override + public List getEvents() { + return Collections.emptyList(); + } + public TaskStatus getStatus() { return status; } diff --git a/src/main/java/ru/ulstu/activity/students/model/TaskDashboardDto.java b/src/main/java/ru/ulstu/activity/students/model/TaskDashboardDto.java new file mode 100644 index 0000000..014753e --- /dev/null +++ b/src/main/java/ru/ulstu/activity/students/model/TaskDashboardDto.java @@ -0,0 +1,16 @@ +package ru.ulstu.activity.students.model; + +import ru.ulstu.activity.api.model.ActivityDashboardDto; + +public class TaskDashboardDto extends ActivityDashboardDto { + private final Task.TaskStatus status; + + public TaskDashboardDto(Task task) { + super(task.getId(), task.getTitle()); + this.status = task.getStatus(); + } + + public Task.TaskStatus getStatus() { + return status; + } +} diff --git a/src/main/java/ru/ulstu/students/model/TaskDto.java b/src/main/java/ru/ulstu/activity/students/model/TaskDto.java similarity index 51% rename from src/main/java/ru/ulstu/students/model/TaskDto.java rename to src/main/java/ru/ulstu/activity/students/model/TaskDto.java index 24ad204..e80df80 100644 --- a/src/main/java/ru/ulstu/students/model/TaskDto.java +++ b/src/main/java/ru/ulstu/activity/students/model/TaskDto.java @@ -1,37 +1,30 @@ -package ru.ulstu.students.model; +package ru.ulstu.activity.students.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.StringUtils; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.tags.model.Tag; +import ru.ulstu.activity.api.model.ActivityDto; +import ru.ulstu.activity.deadline.model.DeadlineDto; import javax.validation.constraints.NotEmpty; 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; -public class TaskDto { +import static ru.ulstu.core.util.StreamApiUtils.convert; + +public class TaskDto extends ActivityDto { private final static int MAX_TAGS_LENGTH = 50; - private Integer id; @NotEmpty private String title; private String description; private Task.TaskStatus status; - private List deadlines = new ArrayList<>(); + private List deadlines = new ArrayList<>(); private Date createDate; private Date updateDate; private Set tagIds; - private List tags = new ArrayList<>(); - - public TaskDto() { - deadlines.add(new Deadline()); - } @JsonCreator public TaskDto(@JsonProperty("id") Integer id, @@ -40,36 +33,25 @@ public class TaskDto { @JsonProperty("createDate") Date createDate, @JsonProperty("updateDate") Date updateDate, @JsonProperty("status") Task.TaskStatus status, - @JsonProperty("deadlines") List deadlines, - @JsonProperty("tagIds") Set tagIds, - @JsonProperty("tags") List tags) { - this.id = id; + @JsonProperty("deadlines") List deadlines, + @JsonProperty("tagIds") Set tagIds) { + super(id); this.title = title; this.status = status; this.deadlines = deadlines; this.createDate = createDate; this.updateDate = updateDate; this.description = description; - this.tags = tags; } public TaskDto(Task task) { - this.id = task.getId(); + super(task.getId()); this.title = task.getTitle(); this.status = task.getStatus(); - this.deadlines = task.getDeadlines(); + this.deadlines = convert(task.getDeadlines(), DeadlineDto::new); this.createDate = task.getCreateDate(); this.updateDate = task.getUpdateDate(); this.description = task.getDescription(); - this.tags = task.getTags(); - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; } public String getTitle() { @@ -96,14 +78,6 @@ public class TaskDto { this.status = status; } - public List getDeadlines() { - return deadlines; - } - - public void setDeadlines(List deadlines) { - this.deadlines = deadlines; - } - public Date getCreateDate() { return createDate; } @@ -128,41 +102,7 @@ public class TaskDto { this.tagIds = tagIds; } - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - TaskDto taskDto = (TaskDto) o; - return Objects.equals(id, taskDto.id) && - Objects.equals(title, taskDto.title) && - Objects.equals(description, taskDto.description) && - status == taskDto.status && - Objects.equals(deadlines, taskDto.deadlines) && - Objects.equals(tagIds, taskDto.tagIds) && - Objects.equals(tags, taskDto.tags); - } - - @Override - public int hashCode() { - return Objects.hash(id, title, description, status, deadlines, createDate, updateDate, tagIds, tags); - } - - public String getTagsString() { - return StringUtils.abbreviate(tags - .stream() - .map(tag -> tag.getTagName()) - .collect(Collectors.joining(", ")), MAX_TAGS_LENGTH); + public List getDeadlines() { + return deadlines; } } diff --git a/src/main/java/ru/ulstu/students/model/TaskFilterDto.java b/src/main/java/ru/ulstu/activity/students/model/TaskFilterDto.java similarity index 96% rename from src/main/java/ru/ulstu/students/model/TaskFilterDto.java rename to src/main/java/ru/ulstu/activity/students/model/TaskFilterDto.java index 21bd5ac..6b4cb42 100644 --- a/src/main/java/ru/ulstu/students/model/TaskFilterDto.java +++ b/src/main/java/ru/ulstu/activity/students/model/TaskFilterDto.java @@ -1,4 +1,4 @@ -package ru.ulstu.students.model; +package ru.ulstu.activity.students.model; import java.util.List; diff --git a/src/main/java/ru/ulstu/activity/students/model/TaskListDto.java b/src/main/java/ru/ulstu/activity/students/model/TaskListDto.java new file mode 100644 index 0000000..0a0e954 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/students/model/TaskListDto.java @@ -0,0 +1,16 @@ +package ru.ulstu.activity.students.model; + +import ru.ulstu.activity.api.model.ActivityListDto; + +public class TaskListDto extends ActivityListDto { + private final Task.TaskStatus status; + + public TaskListDto(Task task) { + super(task.getId(), task.getTitle()); + this.status = task.getStatus(); + } + + public Task.TaskStatus getStatus() { + return status; + } +} diff --git a/src/main/java/ru/ulstu/activity/students/service/SchedulerRepository.java b/src/main/java/ru/ulstu/activity/students/service/SchedulerRepository.java new file mode 100644 index 0000000..4ca820d --- /dev/null +++ b/src/main/java/ru/ulstu/activity/students/service/SchedulerRepository.java @@ -0,0 +1,11 @@ +package ru.ulstu.activity.students.service; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.activity.students.model.Scheduler; +import ru.ulstu.activity.students.model.Task; + +interface SchedulerRepository extends JpaRepository { + + Scheduler findOneByTask(Task task); + +} diff --git a/src/main/java/ru/ulstu/students/service/SchedulerService.java b/src/main/java/ru/ulstu/activity/students/service/SchedulerService.java similarity index 91% rename from src/main/java/ru/ulstu/students/service/SchedulerService.java rename to src/main/java/ru/ulstu/activity/students/service/SchedulerService.java index b192130..2113f8f 100644 --- a/src/main/java/ru/ulstu/students/service/SchedulerService.java +++ b/src/main/java/ru/ulstu/activity/students/service/SchedulerService.java @@ -1,11 +1,10 @@ -package ru.ulstu.students.service; +package ru.ulstu.activity.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 ru.ulstu.activity.students.model.Scheduler; +import ru.ulstu.activity.students.model.Task; +import ru.ulstu.activity.tags.model.Tag; import java.util.Date; import java.util.List; @@ -31,13 +30,13 @@ public class SchedulerService { @Transactional - private Scheduler create(Task task) { + public 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) { + public void delete(Integer schedulerId) { if (schedulerRepository.existsById(schedulerId)) { schedulerRepository.deleteById(schedulerId); } diff --git a/src/main/java/ru/ulstu/students/service/TaskGenerationService.java b/src/main/java/ru/ulstu/activity/students/service/TaskGenerationService.java similarity index 95% rename from src/main/java/ru/ulstu/students/service/TaskGenerationService.java rename to src/main/java/ru/ulstu/activity/students/service/TaskGenerationService.java index 1c04c20..7119194 100644 --- a/src/main/java/ru/ulstu/students/service/TaskGenerationService.java +++ b/src/main/java/ru/ulstu/activity/students/service/TaskGenerationService.java @@ -1,4 +1,4 @@ -package ru.ulstu.students.service; +package ru.ulstu.activity.students.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/ru/ulstu/activity/students/service/TaskNotificationService.java b/src/main/java/ru/ulstu/activity/students/service/TaskNotificationService.java new file mode 100644 index 0000000..621cd6d --- /dev/null +++ b/src/main/java/ru/ulstu/activity/students/service/TaskNotificationService.java @@ -0,0 +1,24 @@ +package ru.ulstu.activity.students.service; + +import com.google.common.collect.ImmutableMap; +import org.springframework.stereotype.Service; +import ru.ulstu.activity.common.service.ActivityNotificationService; +import ru.ulstu.activity.students.model.Task; +import ru.ulstu.user.service.MailService; + +import java.util.Map; + +@Service +public class TaskNotificationService extends ActivityNotificationService { + private final static String TEMPLATE_CREATE = "taskCreateNotification"; + private final static String TITLE_CREATE = "Создана задача"; + + public TaskNotificationService(MailService mailService) { + super(mailService); + } + + public void sendCreateNotification(Task task) { + Map variables = ImmutableMap.of("task", task); + sendForAllAuthors(variables, task, TEMPLATE_CREATE, TITLE_CREATE); + } +} diff --git a/src/main/java/ru/ulstu/students/repository/TaskRepository.java b/src/main/java/ru/ulstu/activity/students/service/TaskRepository.java similarity index 68% rename from src/main/java/ru/ulstu/students/repository/TaskRepository.java rename to src/main/java/ru/ulstu/activity/students/service/TaskRepository.java index af277d1..2bc4329 100644 --- a/src/main/java/ru/ulstu/students/repository/TaskRepository.java +++ b/src/main/java/ru/ulstu/activity/students/service/TaskRepository.java @@ -1,15 +1,16 @@ -package ru.ulstu.students.repository; +package ru.ulstu.activity.students.service; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import ru.ulstu.students.model.Task; -import ru.ulstu.tags.model.Tag; +import ru.ulstu.activity.api.ActivityRepository; +import ru.ulstu.activity.students.model.Task; +import ru.ulstu.activity.tags.model.Tag; import java.util.Date; import java.util.List; -public interface TaskRepository extends JpaRepository { +interface TaskRepository extends JpaRepository, ActivityRepository { @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 DESC") List filterNew(@Param("status") Task.TaskStatus status, @Param("tag") Tag tag); @@ -23,5 +24,7 @@ public interface TaskRepository extends JpaRepository { @Query("SELECT t FROM Task t WHERE (t.createDate >= :date) ORDER BY create_date DESC") List findAllYear(@Param("date") Date date); - + @Override + @Query("SELECT title FROM Task t WHERE (t.title = :name) AND (:id IS NULL OR t.id != :id) ") + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); } diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/activity/students/service/TaskService.java similarity index 64% rename from src/main/java/ru/ulstu/students/service/TaskService.java rename to src/main/java/ru/ulstu/activity/students/service/TaskService.java index c3b4f3a..5b1a62f 100644 --- a/src/main/java/ru/ulstu/students/service/TaskService.java +++ b/src/main/java/ru/ulstu/activity/students/service/TaskService.java @@ -1,27 +1,28 @@ -package ru.ulstu.students.service; +package ru.ulstu.activity.students.service; -import org.apache.commons.lang3.StringUtils; -import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.activity.common.service.ActivityService; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.deadline.service.DeadlineService; +import ru.ulstu.activity.ping.service.PingService; +import ru.ulstu.activity.students.model.Scheduler; +import ru.ulstu.activity.students.model.Task; +import ru.ulstu.activity.students.model.TaskDashboardDto; +import ru.ulstu.activity.students.model.TaskDto; +import ru.ulstu.activity.students.model.TaskListDto; +import ru.ulstu.activity.tags.model.Tag; +import ru.ulstu.activity.tags.service.TagService; +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.activity.timeline.service.EventService; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.response.PageableItems; 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.Collections; import java.util.Date; import java.util.List; import java.util.Map; @@ -29,66 +30,58 @@ 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; -import static ru.ulstu.students.model.Task.TaskStatus.IN_WORK; +import static ru.ulstu.activity.students.model.Task.TaskStatus.IN_WORK; +import static ru.ulstu.core.util.StreamApiUtils.convertPageable; @Service -public class TaskService { - - private final static int MAX_DISPLAY_SIZE = 40; - +public class TaskService extends ActivityService { private final TaskRepository taskRepository; + private final TaskNotificationService taskNotificationService; private final SchedulerRepository schedulerRepository; private final DeadlineService deadlineService; private final TagService tagService; private final EventService eventService; + private final PingService pingService; public TaskService(TaskRepository taskRepository, - DeadlineService deadlineService, TagService tagService, SchedulerRepository schedulerRepository, EventService eventService) { + TaskNotificationService taskNotificationService, + DeadlineService deadlineService, + TagService tagService, + SchedulerRepository schedulerRepository, + EventService eventService, + PingService pingService) { + super(taskRepository, taskNotificationService, pingService, eventService); this.taskRepository = taskRepository; + this.taskNotificationService = taskNotificationService; this.deadlineService = deadlineService; this.tagService = tagService; this.eventService = eventService; this.schedulerRepository = schedulerRepository; + this.pingService = pingService; } - public List findAll() { - return taskRepository.findAll(new Sort(Sort.Direction.DESC, "createDate")); + public PageableItems findAll(int offset, int count) { + final Page page = taskRepository.findAll(new OffsetablePageRequest(offset, count)); + return new PageableItems<>(page.getTotalElements(), page.getContent()); } - public List findAllDto() { - List tasks = convert(findAll(), TaskDto::new); - tasks.forEach(taskDto -> taskDto.setTitle(StringUtils.abbreviate(taskDto.getTitle(), MAX_DISPLAY_SIZE))); - return tasks; + @Override + protected TaskListDto getActivityListDto(Task entity) { + return new TaskListDto(entity); } - public TaskDto findOneDto(Integer id) { - return new TaskDto(taskRepository.getOne(id)); - } - - public List filter(TaskFilterDto filterDto) { - if (filterDto.getOrder().compareTo("new") == 0) { - return convert(taskRepository.filterNew( - filterDto.getStatus(), - filterDto.getTag() == null ? null : tagService.findById(filterDto.getTag())), TaskDto::new); - } else { - return convert(taskRepository.filterOld( - filterDto.getStatus(), - filterDto.getTag() == null ? null : tagService.findById(filterDto.getTag())), TaskDto::new); - } + @Override + protected Task getNewActivity() { + return new Task(); } - @Transactional - public Integer create(TaskDto taskDto) throws IOException { - Task newTask = copyFromDto(new Task(), taskDto); - newTask = taskRepository.save(newTask); - eventService.createFromObject(newTask, Collections.emptyList(), true, "задачи"); - return newTask.getId(); + @Override + protected TaskDto getNewActivityDto(Task entity) { + return new TaskDto(entity); } - private Task copyFromDto(Task task, TaskDto taskDto) throws IOException { + protected Task copyFromDto(Task task, TaskDto taskDto) { task.setTitle(taskDto.getTitle()); task.setDescription(taskDto.getDescription()); task.setStatus(taskDto.getStatus() == null ? IN_WORK : taskDto.getStatus()); @@ -96,39 +89,18 @@ public class TaskService { task.setCreateDate(task.getCreateDate() == null ? new Date() : task.getCreateDate()); task.setUpdateDate(new Date()); task.getTags().clear(); - task.setTags(tagService.saveOrCreate(taskDto.getTags())); + //task.setTags(tagService.saveOrCreate(taskDto.getTags())); return task; } - @Transactional - private Integer update(TaskDto taskDto) throws IOException { - Task task = taskRepository.getOne(taskDto.getId()); - taskRepository.save(copyFromDto(task, taskDto)); - eventService.updateTaskDeadlines(task); - return task.getId(); - } - - @Transactional - public boolean delete(Integer taskId) throws IOException { - if (taskRepository.existsById(taskId)) { - Task scheduleTask = taskRepository.getOne(taskId); - Scheduler sch = schedulerRepository.findOneByTask(scheduleTask); - if (sch != null) { - schedulerRepository.deleteById(sch.getId()); - } - taskRepository.deleteById(taskId); - return true; - } - return false; - + @Override + protected void doActionsOnDiffObjects(Task oldEntity, Task entity) { + //TODO } - public void save(TaskDto taskDto) throws IOException { - if (isEmpty(taskDto.getId())) { - create(taskDto); - } else { - update(taskDto); - } + @Override + protected List getEvents(Task entity) { + return eventService.findByTask(entity); } private void copyMainPart(Task newTask, Task task) { @@ -255,4 +227,14 @@ public class TaskService { taskRepository.save(newTask); return newTask; } + + @Override + public PageableItems findAllActiveDto(int offset, int count) { + return convertPageable(findAllActive(offset, count), TaskDashboardDto::new); + } + + @Override + public PageableItems findAllActive(int offset, int count) { + return findAll(offset, count); + } } diff --git a/src/main/java/ru/ulstu/tags/model/Tag.java b/src/main/java/ru/ulstu/activity/tags/model/Tag.java similarity index 97% rename from src/main/java/ru/ulstu/tags/model/Tag.java rename to src/main/java/ru/ulstu/activity/tags/model/Tag.java index 023cfb4..b2081e6 100644 --- a/src/main/java/ru/ulstu/tags/model/Tag.java +++ b/src/main/java/ru/ulstu/activity/tags/model/Tag.java @@ -1,4 +1,4 @@ -package ru.ulstu.tags.model; +package ru.ulstu.activity.tags.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/java/ru/ulstu/tags/repository/TagRepository.java b/src/main/java/ru/ulstu/activity/tags/service/TagRepository.java similarity index 67% rename from src/main/java/ru/ulstu/tags/repository/TagRepository.java rename to src/main/java/ru/ulstu/activity/tags/service/TagRepository.java index 213abae..069905f 100644 --- a/src/main/java/ru/ulstu/tags/repository/TagRepository.java +++ b/src/main/java/ru/ulstu/activity/tags/service/TagRepository.java @@ -1,11 +1,11 @@ -package ru.ulstu.tags.repository; +package ru.ulstu.activity.tags.service; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import ru.ulstu.tags.model.Tag; +import ru.ulstu.activity.tags.model.Tag; -public interface TagRepository extends JpaRepository { +interface TagRepository extends JpaRepository { @Query("SELECT t FROM Tag t WHERE (t.tagName = :tagName)") Tag findByName(@Param("tagName") String tagName); diff --git a/src/main/java/ru/ulstu/tags/service/TagService.java b/src/main/java/ru/ulstu/activity/tags/service/TagService.java similarity index 84% rename from src/main/java/ru/ulstu/tags/service/TagService.java rename to src/main/java/ru/ulstu/activity/tags/service/TagService.java index f85889d..b24663c 100644 --- a/src/main/java/ru/ulstu/tags/service/TagService.java +++ b/src/main/java/ru/ulstu/activity/tags/service/TagService.java @@ -1,8 +1,7 @@ -package ru.ulstu.tags.service; +package ru.ulstu.activity.tags.service; import org.springframework.stereotype.Service; -import ru.ulstu.tags.model.Tag; -import ru.ulstu.tags.repository.TagRepository; +import ru.ulstu.activity.tags.model.Tag; import javax.transaction.Transactional; import java.util.List; @@ -10,12 +9,9 @@ import java.util.stream.Collectors; @Service public class TagService { - private final TagRepository tagRepository; - public TagService(TagRepository tagRepository) { - this.tagRepository = tagRepository; } @@ -33,17 +29,17 @@ public class TagService { } @Transactional - private Tag getExistById(Tag tag) { + public Tag getExistById(Tag tag) { return tagRepository.getOne(tag.getId()); } @Transactional - private Tag isExistByName(String tagName) { + public Tag isExistByName(String tagName) { return tagRepository.findByName(tagName); } @Transactional - private Tag create(Tag tag) { + public Tag create(Tag tag) { Tag newTag = new Tag(); newTag.setTagName(tag.getTagName()); newTag = tagRepository.save(newTag); diff --git a/src/main/java/ru/ulstu/activity/timeline/controller/EventController.java b/src/main/java/ru/ulstu/activity/timeline/controller/EventController.java new file mode 100644 index 0000000..cd66147 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/timeline/controller/EventController.java @@ -0,0 +1,49 @@ +package ru.ulstu.activity.timeline.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import ru.ulstu.activity.timeline.model.EventDto; +import ru.ulstu.activity.timeline.service.EventService; +import ru.ulstu.configuration.Constants; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.core.model.response.Response; + +@RestController +@RequestMapping(Constants.API_1_0 + "events") +public class EventController { + + private final EventService eventService; + + public EventController(EventService eventService) { + this.eventService = eventService; + } + + @GetMapping + public Response> getEvents(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "0") int count) { + return new Response<>(eventService.getAllEvents(offset, count)); + } + + @GetMapping("future") + public Response> getFutureEvents(@RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "0") int count) { + return new Response<>(eventService.getFutureEvents(offset, count)); + } + + @GetMapping("all-by-user") + public Response> getUserEvents(@RequestParam(value = "user-id") int userId, + @RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "0") int count) { + return new Response<>(eventService.getUserEvents(userId, offset, count)); + } + + @GetMapping("future-by-user") + public Response> getUserFutureEvents(@RequestParam(value = "user-id") int userId, + @RequestParam(value = "offset", defaultValue = "0") int offset, + @RequestParam(value = "count", defaultValue = "0") int count) { + return new Response<>(eventService.getUserFutureEvents(userId, offset, count)); + } + +} diff --git a/src/main/java/ru/ulstu/timeline/model/Event.java b/src/main/java/ru/ulstu/activity/timeline/model/Event.java similarity index 79% rename from src/main/java/ru/ulstu/timeline/model/Event.java rename to src/main/java/ru/ulstu/activity/timeline/model/Event.java index bf69a70..f882bf9 100644 --- a/src/main/java/ru/ulstu/timeline/model/Event.java +++ b/src/main/java/ru/ulstu/activity/timeline/model/Event.java @@ -1,14 +1,13 @@ -package ru.ulstu.timeline.model; +package ru.ulstu.activity.timeline.model; -import ru.ulstu.conference.model.Conference; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.grant.model.Grant; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.activity.project.model.Project; +import ru.ulstu.activity.students.model.Task; import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.grant.model.Grant; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.project.model.Project; -import ru.ulstu.students.model.Task; import ru.ulstu.user.model.User; -import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; @@ -17,7 +16,6 @@ import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotBlank; @@ -45,9 +43,6 @@ public class Event extends BaseEntity { @NotBlank private String title; - @Enumerated(value = EnumType.STRING) - private PeriodEvent period; - @Enumerated(value = EnumType.STRING) private EventStatus status; @@ -69,14 +64,6 @@ public class Event extends BaseEntity { @ManyToMany(fetch = FetchType.LAZY) private List recipients = new ArrayList<>(); - @ManyToOne - @JoinColumn(name = "child_id") - private Event child; - - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "child_id") - private List parents; - @ManyToOne @JoinColumn(name = "paper_id") private Paper paper; @@ -113,14 +100,6 @@ public class Event extends BaseEntity { this.status = status; } - public PeriodEvent getPeriod() { - return period; - } - - public void setPeriod(PeriodEvent period) { - this.period = period; - } - public Date getCreateDate() { return createDate; } @@ -161,22 +140,6 @@ public class Event extends BaseEntity { this.executeDate = executeDate; } - public Event getChild() { - return child; - } - - public void setChild(Event child) { - this.child = child; - } - - public List getParents() { - return parents; - } - - public void setParents(List parents) { - this.parents = parents; - } - public Paper getPaper() { return paper; } diff --git a/src/main/java/ru/ulstu/activity/timeline/model/EventDto.java b/src/main/java/ru/ulstu/activity/timeline/model/EventDto.java new file mode 100644 index 0000000..51741b2 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/timeline/model/EventDto.java @@ -0,0 +1,31 @@ +package ru.ulstu.activity.timeline.model; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.util.Date; + +public class EventDto { + @NotBlank + private final String title; + @NotNull + private final Date executeDate; + private final String description; + + public EventDto(Event event) { + this.title = event.getTitle(); + this.description = event.getDescription(); + this.executeDate = event.getExecuteDate(); + } + + public String getTitle() { + return title; + } + + public String getDescription() { + return description; + } + + public Date getExecuteDate() { + return executeDate; + } +} diff --git a/src/main/java/ru/ulstu/activity/timeline/service/EventRepository.java b/src/main/java/ru/ulstu/activity/timeline/service/EventRepository.java new file mode 100644 index 0000000..54660e7 --- /dev/null +++ b/src/main/java/ru/ulstu/activity/timeline/service/EventRepository.java @@ -0,0 +1,41 @@ +package ru.ulstu.activity.timeline.service; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.grant.model.Grant; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.activity.project.model.Project; +import ru.ulstu.activity.students.model.Task; +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.user.model.User; + +import java.util.List; + +interface EventRepository extends JpaRepository { + @Query("SELECT e FROM Event e WHERE e.executeDate = CURRENT_DATE") + List findByCurrentDate(); + + @Query("SELECT e FROM Event e WHERE e.executeDate > CURRENT_DATE ORDER BY e.executeDate") + Page findAllFuture(OffsetablePageRequest offsetablePageRequest); + + List findAllByPaper(Paper paper); + + List findAllByConference(Conference conference); + + List findAllByGrant(Grant grant); + + List findAllByProject(Project project); + + List findAllByTask(Task task); + + @Query("SELECT e FROM Event e WHERE (:user MEMBER OF e.recipients) ORDER BY e.executeDate") + Page findByUser(Pageable offsetablePageRequest, @Param("user") User user); + + @Query("SELECT e FROM Event e WHERE (:user MEMBER OF e.recipients) AND e.executeDate > CURRENT_DATE ORDER BY e.executeDate") + Page findUserFuture(Pageable offsetablePageRequest, @Param("user") User user); +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/activity/timeline/service/EventService.java b/src/main/java/ru/ulstu/activity/timeline/service/EventService.java new file mode 100644 index 0000000..a9a3f7d --- /dev/null +++ b/src/main/java/ru/ulstu/activity/timeline/service/EventService.java @@ -0,0 +1,102 @@ +package ru.ulstu.activity.timeline.service; + +import org.apache.commons.lang3.time.DateUtils; +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; +import ru.ulstu.activity.common.model.EventSource; +import ru.ulstu.activity.conference.model.Conference; +import ru.ulstu.activity.deadline.model.Deadline; +import ru.ulstu.activity.grant.model.Grant; +import ru.ulstu.activity.paper.model.Paper; +import ru.ulstu.activity.project.model.Project; +import ru.ulstu.activity.students.model.Task; +import ru.ulstu.activity.timeline.model.Event; +import ru.ulstu.activity.timeline.model.EventDto; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.user.service.UserService; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +import static ru.ulstu.core.util.StreamApiUtils.convertPageable; + +@Service +public class EventService { + private final UserService userService; + private final EventRepository eventRepository; + + public EventService(UserService userService, + EventRepository eventRepository) { + this.userService = userService; + this.eventRepository = eventRepository; + } + + public PageableItems getAllEvents(int offset, int count) { + return createPageable(eventRepository.findAll(new OffsetablePageRequest(offset, count))); + } + + public PageableItems getFutureEvents(int offset, int count) { + return createPageable(eventRepository.findAllFuture(new OffsetablePageRequest(offset, count))); + } + + public PageableItems getUserEvents(int userId, int offset, int count) { + return createPageable(eventRepository.findByUser(new OffsetablePageRequest(offset, count), userService.findById(userId))); + } + + public PageableItems getUserFutureEvents(int userId, int offset, int count) { + return createPageable(eventRepository.findUserFuture(new OffsetablePageRequest(offset, count), userService.findById(userId))); + } + + public void createFromObject(EventSource eventSource) { + List newEvents = new ArrayList<>(); + for (Deadline deadline : eventSource.getDeadlines() + .stream() + .filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date())) + .collect(Collectors.toList())) { + Event newEvent = new Event(); + newEvent.setTitle("Дедлайн " + eventSource.getSuffix()); + newEvent.setStatus(Event.EventStatus.NEW); + newEvent.setExecuteDate(deadline.getDate()); + newEvent.setCreateDate(new Date()); + newEvent.setUpdateDate(new Date()); + newEvent.setDescription("Дедлайн '" + + deadline.getDescription() + + "' " + eventSource.getSuffix() + " '" + + eventSource.getTitle() + "'"); + eventSource.addObjectToEvent(newEvent); + newEvent.setRecipients(eventSource.getRecipients()); + } + eventRepository.saveAll(newEvents); + } + + private PageableItems createPageable(Page page) { + return convertPageable(new PageableItems<>(page.getTotalElements(), page.getContent()), EventDto::new); + } + + public void deleteAll(List events) { + eventRepository.deleteAll(events); + } + + public List findByConference(Conference conference) { + return eventRepository.findAllByConference(conference); + } + + public List findByGrant(Grant entity) { + return eventRepository.findAllByGrant(entity); + } + + public List findByProject(Project entity) { + return eventRepository.findAllByProject(entity); + } + + public List findByPaper(Paper entity) { + return eventRepository.findAllByPaper(entity); + } + + public List findByTask(Task entity) { + return eventRepository.findAllByTask(entity); + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/conference/controller/ConferenceController.java b/src/main/java/ru/ulstu/conference/controller/ConferenceController.java deleted file mode 100644 index f9a4bac..0000000 --- a/src/main/java/ru/ulstu/conference/controller/ConferenceController.java +++ /dev/null @@ -1,165 +0,0 @@ -package ru.ulstu.conference.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.ModelAttribute; -import org.springframework.web.bind.annotation.PostMapping; -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.model.ConferenceUser; -import ru.ulstu.conference.service.ConferenceService; -import ru.ulstu.user.model.User; -import springfox.documentation.annotations.ApiIgnore; - -import javax.validation.Valid; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - -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() -@RequestMapping(value = "/conferences") -@ApiIgnore -public class ConferenceController { - - private final ConferenceService conferenceService; - - public ConferenceController(ConferenceService conferenceService) { - this.conferenceService = conferenceService; - } - - @GetMapping("/conferences") - public void getConferences(ModelMap modelMap) { - modelMap.put("filteredConferences", new ConferenceFilterDto(conferenceService.findAllDto())); - } - - @PostMapping("/conferences") - public void filterConferences(@Valid ConferenceFilterDto conferenceFilterDto, ModelMap modelMap) { - modelMap.put("filteredConferences", new ConferenceFilterDto(conferenceService.filter(conferenceFilterDto), - conferenceFilterDto.getFilterUserId(), - conferenceFilterDto.getYear())); - } - - @GetMapping("/dashboard") - public void getDashboard(ModelMap modelMap) { - modelMap.put("conferences", conferenceService.findAllActiveDto()); - - conferenceService.setChartData(modelMap); // example - } - - @GetMapping("/conference") - public void getConference(ModelMap modelMap, @RequestParam(value = "id") Integer id) { - if (id != null && id > 0) { - modelMap.put("conferenceDto", conferenceService.getExistConferenceById(id)); - } else { - modelMap.put("conferenceDto", conferenceService.getNewConference()); - } - } - - @PostMapping(value = "/conferences", params = "deleteConference") - public String delete(@RequestParam("deleteConference") Integer conferenceId) throws IOException { - conferenceService.delete(conferenceId); - return String.format(REDIRECT_TO, CONFERENCES_PAGE); - } - - @PostMapping(value = "/conference", params = "save") - public String save(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { - if (!conferenceService.save(conferenceDto, errors)) { - return CONFERENCE_PAGE; - } - return String.format(REDIRECT_TO, CONFERENCES_PAGE); - } - - @PostMapping(value = "/conference", params = "addDeadline") - public String addDeadline(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { - conferenceService.filterEmptyDeadlines(conferenceDto); - if (errors.hasErrors()) { - return CONFERENCE_PAGE; - } - conferenceService.addDeadline(conferenceDto); - return CONFERENCE_PAGE; - } - - @PostMapping(value = "/conference", params = "removeDeadline") - public String removeDeadline(@Valid ConferenceDto conferenceDto, Errors errors, - @RequestParam(value = "removeDeadline") Integer deadlineIndex) throws IOException { - if (errors.hasErrors()) { - return CONFERENCE_PAGE; - } - conferenceService.removeDeadline(conferenceDto, deadlineIndex); - return CONFERENCE_PAGE; - } - - @PostMapping(value = "/conference", params = "addPaper") - public String addPaper(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { - if (errors.hasErrors()) { - return CONFERENCE_PAGE; - } - conferenceService.addPaper(conferenceDto); - - return CONFERENCE_PAGE; - } - - @PostMapping(value = "/conference", params = "removePaper") - public String removePaper(@Valid ConferenceDto conferenceDto, Errors errors, - @RequestParam(value = "removePaper") Integer paperIndex) throws IOException { - if (errors.hasErrors()) { - return CONFERENCE_PAGE; - } - conferenceService.removePaper(conferenceDto, paperIndex); - return CONFERENCE_PAGE; - } - - @PostMapping(value = "/conference", params = "takePart") - public String takePart(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { - if (errors.hasErrors()) { - return CONFERENCE_PAGE; - } - conferenceService.takePart(conferenceDto); - return CONFERENCE_PAGE; - } - - @PostMapping(value = "/conference", params = "pingConference") - public String ping(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { - if (errors.hasErrors()) { - return CONFERENCE_PAGE; - } - conferenceService.ping(conferenceDto); - return CONFERENCE_PAGE; - } - - @ModelAttribute("allParticipation") - public List getAllParticipation() { - return conferenceService.getAllParticipations(); - } - - @ModelAttribute("allDeposit") - public List getAllDeposit() { - return conferenceService.getAllDeposit(); - } - - @ModelAttribute("allUsers") - public List getAllUsers() { - return conferenceService.getAllUsers(); - } - - @ModelAttribute("allYears") - public List getAllYears() { - List years = new ArrayList<>(); - for (int i = Calendar.getInstance().get(Calendar.YEAR); i > 2010; i--) { - years.add(i); - } - return years; - } - -} diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java deleted file mode 100644 index 470e712..0000000 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ /dev/null @@ -1,318 +0,0 @@ -package ru.ulstu.conference.service; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.data.domain.Sort; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.ui.ModelMap; -import org.springframework.validation.Errors; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.conference.model.ConferenceDto; -import ru.ulstu.conference.model.ConferenceFilterDto; -import ru.ulstu.conference.model.ConferenceUser; -import ru.ulstu.conference.repository.ConferenceRepository; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.deadline.service.DeadlineService; -import ru.ulstu.name.BaseService; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.paper.service.PaperService; -import ru.ulstu.ping.service.PingService; -import ru.ulstu.timeline.service.EventService; -import ru.ulstu.user.model.User; -import ru.ulstu.user.service.UserService; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.stream.Collectors; - -import static org.springframework.util.ObjectUtils.isEmpty; -import static ru.ulstu.core.util.StreamApiUtils.convert; - -@Service -public class ConferenceService extends BaseService { - private final static int MAX_DISPLAY_SIZE = 40; - - private final ConferenceRepository conferenceRepository; - private final ConferenceUserService conferenceUserService; - private final DeadlineService deadlineService; - private final PaperService paperService; - private final UserService userService; - private final PingService pingService; - private final ConferenceNotificationService conferenceNotificationService; - private final EventService eventService; - - public ConferenceService(ConferenceRepository conferenceRepository, - ConferenceUserService conferenceUserService, - DeadlineService deadlineService, - PaperService paperService, - UserService userService, - PingService pingService, - ConferenceNotificationService conferenceNotificationService, - EventService eventService) { - this.baseRepository = conferenceRepository; - this.conferenceRepository = conferenceRepository; - this.conferenceUserService = conferenceUserService; - this.deadlineService = deadlineService; - this.paperService = paperService; - this.userService = userService; - this.pingService = pingService; - this.conferenceNotificationService = conferenceNotificationService; - this.eventService = eventService; - } - - public ConferenceDto getExistConferenceById(Integer id) { - ConferenceDto conferenceDto = new ConferenceDto(conferenceRepository.getOne(id)); - conferenceDto.setNotSelectedPapers(getNotSelectPapers(conferenceDto.getPaperIds())); - conferenceDto.setDisabledTakePart(isCurrentUserParticipant(conferenceDto.getUsers())); - return conferenceDto; - } - - public ConferenceDto getNewConference() { - ConferenceDto conferenceDto = new ConferenceDto(); - conferenceDto.setNotSelectedPapers(getNotSelectPapers(new ArrayList<>())); - return conferenceDto; - } - - - public List findAll() { - return conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate")); - } - - public List findAllDto() { - List conferences = convert(findAll(), ConferenceDto::new); - conferences.forEach(conferenceDto -> conferenceDto.setTitle(StringUtils.abbreviate(conferenceDto.getTitle(), MAX_DISPLAY_SIZE))); - return conferences; - } - - public boolean save(ConferenceDto conferenceDto, Errors errors) throws IOException { - conferenceDto.setName(conferenceDto.getTitle()); - filterEmptyDeadlines(conferenceDto); - checkEmptyFieldsOfDeadline(conferenceDto, errors); - checkEmptyFieldsOfDates(conferenceDto, errors); - checkUniqueName(conferenceDto, - errors, - conferenceDto.getId(), - "Конференция с таким именем уже существует"); - if (errors.hasErrors()) { - return false; - } - - if (isEmpty(conferenceDto.getId())) { - create(conferenceDto); - } else { - update(conferenceDto); - } - - return true; - } - - @Transactional - public Conference create(ConferenceDto conferenceDto) throws IOException { - Conference newConference = copyFromDto(new Conference(), conferenceDto); - newConference = conferenceRepository.save(newConference); - conferenceNotificationService.sendCreateNotification(newConference); - eventService.createFromObject(newConference, Collections.emptyList(), false, "конференции"); - return newConference; - } - - @Transactional - private Conference update(ConferenceDto conferenceDto) throws IOException { - Conference conference = conferenceRepository.getOne(conferenceDto.getId()); - List oldDeadlines = conference.getDeadlines().stream() - .map(this::copyDeadline) - .collect(Collectors.toList()); - Date oldBeginDate = conference.getBeginDate(); - Date oldEndDate = conference.getEndDate(); - conferenceRepository.save(copyFromDto(conference, conferenceDto)); - eventService.updateConferenceDeadlines(conference); - sendNotificationAfterUpdateDeadlines(conference, oldDeadlines); - if (!conference.getBeginDate().equals(oldBeginDate) || !conference.getEndDate().equals(oldEndDate)) { - conferenceNotificationService.updateConferencesDatesNotification(conference, oldBeginDate, oldEndDate); - } - conferenceDto.getRemovedDeadlineIds().forEach(deadlineService::remove); - return conference; - } - - @Transactional - public boolean delete(Integer conferenceId) { - if (conferenceRepository.existsById(conferenceId)) { - eventService.removeConferencesEvent(conferenceRepository.getOne(conferenceId)); - conferenceRepository.deleteById(conferenceId); - return true; - } - return false; - } - - public ConferenceDto addDeadline(ConferenceDto conferenceDto) { - conferenceDto.getDeadlines().add(new Deadline()); - return conferenceDto; - } - - - public ConferenceDto removeDeadline(ConferenceDto conferenceDto, Integer deadlineIndex) throws IOException { - if (conferenceDto.getDeadlines().get(deadlineIndex).getId() != null) { - conferenceDto.getRemovedDeadlineIds().add(conferenceDto.getDeadlines().get(deadlineIndex).getId()); - } - conferenceDto.getDeadlines().remove((int) deadlineIndex); - return conferenceDto; - } - - public ConferenceDto addPaper(ConferenceDto conferenceDto) { - Paper paper = new Paper(); - paper.setTitle(userService.getCurrentUser().getLastName() + "_" + conferenceDto.getTitle() + "_" + (new Date()).getTime()); - paper.setStatus(Paper.PaperStatus.DRAFT); - conferenceDto.getPapers().add(paper); - return conferenceDto; - } - - public ConferenceDto removePaper(ConferenceDto conferenceDto, Integer paperIndex) throws IOException { - Paper removedPaper = conferenceDto.getPapers().remove((int) paperIndex); - if (removedPaper.getId() != null) { - conferenceDto.getNotSelectedPapers().add(removedPaper); - } - return conferenceDto; - } - - public ConferenceDto takePart(ConferenceDto conferenceDto) throws IOException { - conferenceDto.getUsers().add(new ConferenceUser(userService.getCurrentUser())); - conferenceDto.setDisabledTakePart(true); - return conferenceDto; - } - - private List getNotSelectPapers(List paperIds) { - return paperService.findAllNotSelect(paperIds); - } - - public List getAllUsers() { - return userService.findAll(); - } - - public List getAllParticipations() { - return Arrays.asList(ConferenceUser.Participation.values()); - } - - public List getAllDeposit() { - return Arrays.asList(ConferenceUser.Deposit.values()); - } - - private Conference copyFromDto(Conference conference, ConferenceDto conferenceDto) throws IOException { - conference.setTitle(conferenceDto.getTitle()); - conference.setDescription(conferenceDto.getDescription()); - conference.setUrl(conferenceDto.getUrl()); - conference.setBeginDate(conferenceDto.getBeginDate()); - conference.setEndDate(conferenceDto.getEndDate()); - conference.getPapers().clear(); - conferenceDto.getPapers().forEach(paper -> conference.getPapers().add(paper.getId() != null ? paperService.findPaperById(paper.getId()) : paperService.create(paper))); - conference.setDeadlines(deadlineService.saveOrCreate(conferenceDto.getDeadlines())); - conference.setUsers(conferenceUserService.saveOrCreate(conferenceDto.getUsers())); - if (conferenceDto.getPaperIds() != null && !conferenceDto.getPaperIds().isEmpty()) { - conferenceDto.getPaperIds().forEach(paperId -> - conference.getPapers().add(paperService.findPaperById(paperId))); - } - return conference; - } - - - private boolean isCurrentUserParticipant(List conferenceUsers) { - return conferenceUsers.stream().anyMatch(participant -> participant.getUser().equals(userService.getCurrentUser())); - } - - public List filter(ConferenceFilterDto conferenceFilterDto) { - return convert(conferenceRepository.findByUserAndYear( - conferenceFilterDto.getFilterUserId() == null ? null : userService.findById(conferenceFilterDto.getFilterUserId()), - conferenceFilterDto.getYear()), ConferenceDto::new); - - } - - public List findAllActiveDto() { - return convert(findAllActive(), ConferenceDto::new); - } - - private List findAllActive() { - return conferenceRepository.findAllActive(new Date()); - } - - public boolean isAttachedToConference(Integer paperId) { - return conferenceRepository.isPaperAttached(paperId); - } - - @Transactional - public void ping(ConferenceDto conferenceDto) throws IOException { - pingService.addPing(findOne(conferenceDto.getId())); - conferenceRepository.updatePingConference(conferenceDto.getId()); - } - - private Conference findOne(Integer conferenceId) { - return conferenceRepository.getOne(conferenceId); - } - - public void setChartData(ModelMap modelMap) { - //first, add the regional sales - Integer northeastSales = 17089; - Integer westSales = 10603; - Integer midwestSales = 5223; - Integer southSales = 10111; - - modelMap.addAttribute("northeastSales", northeastSales); - modelMap.addAttribute("southSales", southSales); - modelMap.addAttribute("midwestSales", midwestSales); - modelMap.addAttribute("westSales", westSales); - - //now add sales by lure type - List inshoreSales = Arrays.asList(4074, 3455, 4112); - List nearshoreSales = Arrays.asList(3222, 3011, 3788); - List offshoreSales = Arrays.asList(7811, 7098, 6455); - - modelMap.addAttribute("inshoreSales", inshoreSales); - modelMap.addAttribute("nearshoreSales", nearshoreSales); - modelMap.addAttribute("offshoreSales", offshoreSales); - } - - private void sendNotificationAfterUpdateDeadlines(Conference conference, List oldDeadlines) { - if (oldDeadlines.size() != conference.getDeadlines().size()) { - conferenceNotificationService.updateDeadlineNotification(conference); - return; - } - - if (conference.getDeadlines() - .stream() - .filter(deadline -> !oldDeadlines.contains(deadline)) - .count() > 0) { - conferenceNotificationService.updateDeadlineNotification(conference); - } - } - - private Deadline copyDeadline(Deadline oldDeadline) { - Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription()); - newDeadline.setId(oldDeadline.getId()); - return newDeadline; - } - - private void checkEmptyFieldsOfDeadline(ConferenceDto conferenceDto, Errors errors) { - for (Deadline deadline : conferenceDto.getDeadlines()) { - if (deadline.getDate() == null || deadline.getDescription().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Все поля дедлайна должны быть заполнены"); - } - } - } - - 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())) - .collect(Collectors.toList())); - } - - public Conference getActiveConferenceByUser(User user) { - return conferenceRepository.findActiveByUser(user); - } -} diff --git a/src/main/java/ru/ulstu/configuration/MvcConfiguration.java b/src/main/java/ru/ulstu/configuration/MvcConfiguration.java index 35e9ad2..e69de29 100644 --- a/src/main/java/ru/ulstu/configuration/MvcConfiguration.java +++ b/src/main/java/ru/ulstu/configuration/MvcConfiguration.java @@ -1,28 +0,0 @@ -package ru.ulstu.configuration; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class MvcConfiguration implements WebMvcConfigurer { - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/{articlename:\\w+}"); - registry.addViewController("/admin/{articlename:\\w+}"); - registry.addViewController("/papers/{articlename:\\w+}"); - registry.addViewController("/grants/{articlename:\\w+}"); - registry.addViewController("/conferences/{articlename:\\w+}"); - registry.addViewController("/students/{articlename:\\w+}"); - registry.addRedirectViewController("/", "/index"); - registry.addRedirectViewController("/default", "/index"); - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry - .addResourceHandler("/webjars/**") - .addResourceLocations("/webjars/"); - } -} diff --git a/src/main/java/ru/ulstu/core/controller/AdviceController.java b/src/main/java/ru/ulstu/core/controller/AdviceController.java index 27c9d5b..b02946f 100644 --- a/src/main/java/ru/ulstu/core/controller/AdviceController.java +++ b/src/main/java/ru/ulstu/core/controller/AdviceController.java @@ -1,121 +1,107 @@ -package ru.ulstu.core.controller; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ModelAttribute; -import ru.ulstu.core.error.EntityIdIsNullException; -import ru.ulstu.core.model.ErrorConstants; -import ru.ulstu.core.model.response.Response; -import ru.ulstu.core.model.response.ResponseExtended; -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.service.UserService; - -import java.util.Set; -import java.util.stream.Collectors; - -@ControllerAdvice -public class AdviceController { - private final Logger log = LoggerFactory.getLogger(AdviceController.class); - private final UserService userService; - - public AdviceController(UserService userService) { - this.userService = userService; - } - - @ModelAttribute("currentUser") - public String getCurrentUser() { - return userService.getCurrentUser().getUserAbbreviate(); - } - - @ModelAttribute("flashMessage") - public String getFlashMessage() { - return null; - } - - private Response handleException(ErrorConstants error) { - log.warn(error.toString()); - return new Response<>(error); - } - - private ResponseExtended handleException(ErrorConstants error, E errorData) { - log.warn(error.toString()); - return new ResponseExtended<>(error, errorData); - } - - @ExceptionHandler(EntityIdIsNullException.class) - public Response handleEntityIdIsNullException(Throwable e) { - return handleException(ErrorConstants.ID_IS_NULL); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseExtended> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { - final Set errors = e.getBindingResult().getAllErrors().stream() - .filter(error -> error instanceof FieldError) - .map(error -> ((FieldError) error).getField()) - .collect(Collectors.toSet()); - return handleException(ErrorConstants.VALIDATION_ERROR, errors); - } - - @ExceptionHandler(UserIdExistsException.class) - public Response handleUserIdExistsException(Throwable e) { - return handleException(ErrorConstants.USER_ID_EXISTS); - } - - @ExceptionHandler(UserActivationError.class) - public ResponseExtended handleUserActivationError(Throwable e) { - return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage()); - } - - @ExceptionHandler(UserLoginExistsException.class) - public ResponseExtended handleUserLoginExistsException(Throwable e) { - return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage()); - } - - @ExceptionHandler(UserEmailExistsException.class) - public ResponseExtended handleUserEmailExistsException(Throwable e) { - return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage()); - } - - @ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class) - public Response handleUserPasswordsNotValidOrNotMatchException(Throwable e) { - return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH); - } - - @ExceptionHandler(UserNotFoundException.class) - public ResponseExtended handleUserNotFoundException(Throwable e) { - return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage()); - } - - @ExceptionHandler(UserNotActivatedException.class) - public Response handleUserNotActivatedException(Throwable e) { - return handleException(ErrorConstants.USER_NOT_ACTIVATED); - } - - @ExceptionHandler(UserResetKeyError.class) - public ResponseExtended handleUserResetKeyError(Throwable e) { - return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage()); - } - - @ExceptionHandler(UserIsUndeadException.class) - public ResponseExtended handleUserIsUndeadException(Throwable e) { - return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage()); - } - - @ExceptionHandler(UserSendingMailException.class) - public ResponseExtended handleUserSendingMailException(Throwable e) { - return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage()); - } -} +package ru.ulstu.core.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestController; +import ru.ulstu.core.error.EntityIdIsNullException; +import ru.ulstu.core.model.ErrorConstants; +import ru.ulstu.core.model.response.Response; +import ru.ulstu.core.model.response.ResponseExtended; +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.service.UserService; + +import java.util.Set; +import java.util.stream.Collectors; + +@RestController +@ControllerAdvice +public class AdviceController { + private final Logger log = LoggerFactory.getLogger(AdviceController.class); + + private Response handleException(ErrorConstants error) { + log.warn(error.toString()); + return new Response<>(error); + } + + private ResponseExtended handleException(ErrorConstants error, E errorData) { + log.warn(error.toString()); + return new ResponseExtended<>(error, errorData); + } + + @ExceptionHandler(EntityIdIsNullException.class) + public Response handleEntityIdIsNullException(Throwable e) { + return handleException(ErrorConstants.ID_IS_NULL); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseExtended> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + final Set errors = e.getBindingResult().getAllErrors().stream() + .filter(error -> error instanceof FieldError) + .map(error -> ((FieldError) error).getField()) + .collect(Collectors.toSet()); + return handleException(ErrorConstants.VALIDATION_ERROR, errors); + } + + @ExceptionHandler(UserIdExistsException.class) + public Response handleUserIdExistsException(Throwable e) { + return handleException(ErrorConstants.USER_ID_EXISTS); + } + + @ExceptionHandler(UserActivationError.class) + public ResponseExtended handleUserActivationError(Throwable e) { + return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage()); + } + + @ExceptionHandler(UserLoginExistsException.class) + public ResponseExtended handleUserLoginExistsException(Throwable e) { + return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage()); + } + + @ExceptionHandler(UserEmailExistsException.class) + public ResponseExtended handleUserEmailExistsException(Throwable e) { + return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage()); + } + + @ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class) + public Response handleUserPasswordsNotValidOrNotMatchException(Throwable e) { + return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH); + } + + @ExceptionHandler(UserNotFoundException.class) + public ResponseExtended handleUserNotFoundException(Throwable e) { + return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage()); + } + + @ExceptionHandler(UserNotActivatedException.class) + public Response handleUserNotActivatedException(Throwable e) { + return handleException(ErrorConstants.USER_NOT_ACTIVATED); + } + + @ExceptionHandler(UserResetKeyError.class) + public ResponseExtended handleUserResetKeyError(Throwable e) { + return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage()); + } + + @ExceptionHandler(UserIsUndeadException.class) + public ResponseExtended handleUserIsUndeadException(Throwable e) { + return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage()); + } + + @ExceptionHandler(UserSendingMailException.class) + public ResponseExtended handleUserSendingMailException(Throwable e) { + return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage()); + } +} diff --git a/src/main/java/ru/ulstu/core/controller/ForwardingController.java b/src/main/java/ru/ulstu/core/controller/ForwardingController.java new file mode 100644 index 0000000..36e75df --- /dev/null +++ b/src/main/java/ru/ulstu/core/controller/ForwardingController.java @@ -0,0 +1,15 @@ +package ru.ulstu.core.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import springfox.documentation.annotations.ApiIgnore; + +@Controller +@ApiIgnore +public class ForwardingController { + @GetMapping(path = "/**/{url:[^\\.]+}") + public String forward(@PathVariable("url") String url) { + return "forward:/"; + } +} diff --git a/src/main/java/ru/ulstu/core/controller/Navigation.java b/src/main/java/ru/ulstu/core/controller/Navigation.java deleted file mode 100644 index caea429..0000000 --- a/src/main/java/ru/ulstu/core/controller/Navigation.java +++ /dev/null @@ -1,19 +0,0 @@ -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; - } -} diff --git a/src/main/java/ru/ulstu/core/jpa/OffsetablePageRequest.java b/src/main/java/ru/ulstu/core/jpa/OffsetablePageRequest.java index 148a931..a212689 100644 --- a/src/main/java/ru/ulstu/core/jpa/OffsetablePageRequest.java +++ b/src/main/java/ru/ulstu/core/jpa/OffsetablePageRequest.java @@ -11,7 +11,7 @@ public class OffsetablePageRequest implements Pageable, Serializable { private final Sort sort; public OffsetablePageRequest(long offset, int count) { - this(offset, count, null); + this(offset, count, Sort.unsorted()); } public OffsetablePageRequest(long offset, int count, Sort.Direction direction, String... properties) { diff --git a/src/main/java/ru/ulstu/core/model/UserActivity.java b/src/main/java/ru/ulstu/core/model/UserActivity.java deleted file mode 100644 index f45819d..0000000 --- a/src/main/java/ru/ulstu/core/model/UserActivity.java +++ /dev/null @@ -1,11 +0,0 @@ -package ru.ulstu.core.model; - -import ru.ulstu.user.model.User; - -import java.util.Set; - -public interface UserActivity { - String getTitle(); - - Set getActivityUsers(); -} diff --git a/src/main/java/ru/ulstu/core/util/StreamApiUtils.java b/src/main/java/ru/ulstu/core/util/StreamApiUtils.java index 9a6e58d..ca41e94 100644 --- a/src/main/java/ru/ulstu/core/util/StreamApiUtils.java +++ b/src/main/java/ru/ulstu/core/util/StreamApiUtils.java @@ -1,5 +1,7 @@ package ru.ulstu.core.util; +import ru.ulstu.core.model.response.PageableItems; + import java.util.Collections; import java.util.List; import java.util.Set; @@ -19,4 +21,10 @@ public class StreamApiUtils { ? Collections.emptySet() : entities.stream().map(converter).collect(Collectors.toSet()); } + + public static PageableItems convertPageable(PageableItems pageableEntities, Function converter) { + return pageableEntities == null + ? new PageableItems<>(0, Collections.emptyList()) + : new PageableItems<>(pageableEntities.getCount(), convert((List) pageableEntities.getItems(), converter)); + } } diff --git a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java deleted file mode 100644 index 039ddbf..0000000 --- a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java +++ /dev/null @@ -1,58 +0,0 @@ -package ru.ulstu.deadline.service; - -import org.springframework.stereotype.Service; -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; - -@Service -public class DeadlineService { - private final DeadlineRepository deadlineRepository; - - public DeadlineService(DeadlineRepository deadlineRepository) { - this.deadlineRepository = deadlineRepository; - } - - public List saveOrCreate(List deadlines) { - return deadlines - .stream() - .map(deadline -> { - return deadline.getId() != null ? update(deadline) : create(deadline); - }).collect(Collectors.toList()); - } - - @Transactional - private Deadline update(Deadline deadline) { - Deadline updateDeadline = deadlineRepository.getOne(deadline.getId()); - updateDeadline.setDate(deadline.getDate()); - updateDeadline.setDescription(deadline.getDescription()); - updateDeadline.setExecutors(deadline.getExecutors()); - updateDeadline.setDone(deadline.getDone()); - deadlineRepository.save(updateDeadline); - return updateDeadline; - } - - @Transactional - public Deadline create(Deadline deadline) { - Deadline newDeadline = new Deadline(); - newDeadline.setDate(deadline.getDate()); - newDeadline.setDescription(deadline.getDescription()); - newDeadline.setExecutors(deadline.getExecutors()); - newDeadline.setDone(deadline.getDone()); - newDeadline = deadlineRepository.save(newDeadline); - return newDeadline; - } - - @Transactional - public void remove(Integer deadlineId) { - deadlineRepository.deleteById(deadlineId); - } - - public Date findByGrantIdAndDate(Integer id, Date date) { - return deadlineRepository.findByGrantIdAndDate(id, date); - } -} diff --git a/src/main/java/ru/ulstu/file/repostory/FileRepository.java b/src/main/java/ru/ulstu/file/repostory/FileRepository.java deleted file mode 100644 index 7399239..0000000 --- a/src/main/java/ru/ulstu/file/repostory/FileRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package ru.ulstu.file.repostory; - -import org.springframework.data.jpa.repository.JpaRepository; -import ru.ulstu.file.model.FileData; - -public interface FileRepository extends JpaRepository { -} diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java deleted file mode 100644 index 48dee8e..0000000 --- a/src/main/java/ru/ulstu/grant/controller/GrantController.java +++ /dev/null @@ -1,133 +0,0 @@ -package ru.ulstu.grant.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.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.grant.model.Grant; -import ru.ulstu.grant.model.GrantDto; -import ru.ulstu.grant.service.GrantService; -import ru.ulstu.paper.model.PaperDto; -import ru.ulstu.user.model.User; -import springfox.documentation.annotations.ApiIgnore; - -import javax.validation.Valid; -import java.io.IOException; -import java.util.List; - -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; - - -@Controller() -@RequestMapping(value = "/grants") -@ApiIgnore -public class GrantController { - private final GrantService grantService; - - public GrantController(GrantService grantService) { - this.grantService = grantService; - } - - @GetMapping("/grants") - public void getGrants(ModelMap modelMap) { - modelMap.put("grants", grantService.findAllDto()); - } - - @GetMapping("/dashboard") - public void getDashboard(ModelMap modelMap) { - modelMap.put("grants", grantService.findAllActiveDto()); - } - - @GetMapping("/grant") - public void getGrant(ModelMap modelMap, @RequestParam(value = "id") Integer id) { - if (id != null && id > 0) { - GrantDto grantDto = grantService.getExistGrantById(id); - attachPaper(grantDto); - modelMap.put("grantDto", grantDto); - } else { - modelMap.put("grantDto", new GrantDto()); - } - } - - @PostMapping(value = "/grant", params = "save") - public String save(@Valid GrantDto grantDto, Errors errors) - throws IOException { - if (!grantService.save(grantDto, errors)) { - return GRANT_PAGE; - } - return String.format(REDIRECT_TO, GRANTS_PAGE); - } - - @PostMapping(value = "/grant", params = "filterUsers") - public String filterUsers() { - return GRANT_PAGE; - } - - @PostMapping(value = "/grant", params = "attachPaper") - public String attachPaper(GrantDto grantDto) { - grantService.attachPaper(grantDto); - return GRANT_PAGE; - } - - @PostMapping(value = "/grant", params = "addDeadline") - public String addDeadline(@Valid GrantDto grantDto, Errors errors) { - grantService.filterEmptyDeadlines(grantDto); - if (errors.hasErrors()) { - return GRANT_PAGE; - } - grantDto.getDeadlines().add(new Deadline()); - return GRANT_PAGE; - } - - @PostMapping(value = "/grant", params = "removeDeadline") - public String removeDeadline(GrantDto grantDto, - @RequestParam(value = "removeDeadline") Integer deadlineId) { - grantService.removeDeadline(grantDto, deadlineId); - return GRANT_PAGE; - } - - @PostMapping(value = "/grant", params = "createProject") - public String createProject(@Valid GrantDto grantDto, Errors errors) throws IOException { - if (errors.hasErrors()) { - return GRANT_PAGE; - } - grantService.createProject(grantDto); - return GRANT_PAGE; - } - - @GetMapping("/delete/{grant-id}") - public String delete(@PathVariable("grant-id") Integer grantId) throws IOException { - grantService.delete(grantId); - return String.format(REDIRECT_TO, GRANTS_PAGE); - } - - @ModelAttribute("allStatuses") - public List getGrantStatuses() { - return grantService.getGrantStatuses(); - } - - @ModelAttribute("allAuthors") - public List getAllAuthors(GrantDto grantDto) { - return grantService.getGrantAuthors(grantDto); - } - - @ModelAttribute("allPapers") - public List getAllPapers() { - return grantService.getAllUncompletedPapers(); - } - - @ResponseBody - @PostMapping(value = "/ping") - public void ping(@RequestParam("grantId") int grantId) throws IOException { - grantService.ping(grantId); - } -} diff --git a/src/main/java/ru/ulstu/grant/controller/GrantRestController.java b/src/main/java/ru/ulstu/grant/controller/GrantRestController.java deleted file mode 100644 index 9b90a4d..0000000 --- a/src/main/java/ru/ulstu/grant/controller/GrantRestController.java +++ /dev/null @@ -1,29 +0,0 @@ -package ru.ulstu.grant.controller; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import ru.ulstu.configuration.Constants; -import ru.ulstu.grant.service.GrantService; - -import java.io.IOException; -import java.text.ParseException; - -import static ru.ulstu.paper.controller.PaperRestController.URL; - -@RestController -@RequestMapping(URL) -public class GrantRestController { - public static final String URL = Constants.API_1_0 + "grants"; - - private final GrantService grantService; - - public GrantRestController(GrantService grantService) { - this.grantService = grantService; - } - - @GetMapping("/grab") - public void grab() throws IOException, ParseException { - grantService.createFromKias(); - } -} diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java deleted file mode 100644 index 541dae8..0000000 --- a/src/main/java/ru/ulstu/grant/model/GrantDto.java +++ /dev/null @@ -1,256 +0,0 @@ -package ru.ulstu.grant.model; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.StringUtils; -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; - -import javax.validation.constraints.NotEmpty; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import static ru.ulstu.core.util.StreamApiUtils.convert; - -public class GrantDto extends NameContainer { - private final static int MAX_AUTHORS_LENGTH = 60; - - private Integer id; - @NotEmpty - private String title; - private Grant.GrantStatus status; - private List deadlines = new ArrayList<>(); - private String comment; - private List files = new ArrayList<>(); - private ProjectDto project; - private Set authorIds; - private Set authors; - private Integer leaderId; - private boolean wasLeader; - private boolean hasAge; - private boolean hasDegree; - private boolean hasBAKPapers; - private boolean hasScopusPapers; - private List paperIds = new ArrayList<>(); - private List papers = new ArrayList<>(); - private List removedDeadlineIds = new ArrayList<>(); - - public GrantDto() { - deadlines.add(new Deadline()); - } - - @JsonCreator - public GrantDto(@JsonProperty("id") Integer id, - @JsonProperty("title") String title, - @JsonProperty("status") Grant.GrantStatus status, - @JsonProperty("deadlines") List deadlines, - @JsonProperty("comment") String comment, - @JsonProperty("files") List files, - @JsonProperty("project") ProjectDto project, - @JsonProperty("authorIds") Set authorIds, - @JsonProperty("authors") Set authors, - @JsonProperty("leaderId") Integer leaderId, - @JsonProperty("wasLeader") boolean wasLeader, - @JsonProperty("hasAge") boolean hasAge, - @JsonProperty("hasDegree") boolean hasDegree, - @JsonProperty("paperIds") List paperIds, - @JsonProperty("papers") List papers) { - this.id = id; - this.title = title; - this.status = status; - this.deadlines = deadlines; - this.comment = comment; - this.files = files; - this.project = project; - this.authorIds = authorIds; - this.authors = authors; - this.leaderId = leaderId; - this.wasLeader = wasLeader; - this.hasAge = hasAge; - this.hasDegree = hasDegree; - this.paperIds = paperIds; - this.papers = papers; - } - - public GrantDto(Grant grant) { - this.id = grant.getId(); - this.title = grant.getTitle(); - this.status = grant.getStatus(); - this.deadlines = grant.getDeadlines(); - this.comment = grant.getComment(); - this.files = convert(grant.getFiles(), FileDataDto::new); - this.project = grant.getProject() == null ? null : new ProjectDto(grant.getProject()); - this.authorIds = convert(grant.getAuthors(), user -> user.getId()); - this.authors = convert(grant.getAuthors(), UserDto::new); - this.leaderId = grant.getLeader().getId(); - this.wasLeader = false; - this.hasAge = false; - this.hasDegree = false; - this.paperIds = convert(grant.getPapers(), paper -> paper.getId()); - this.papers = convert(grant.getPapers(), PaperDto::new); - } - - public GrantDto(String grantTitle, Date deadLineDate) { - this.title = grantTitle; - deadlines.add(new Deadline(deadLineDate, "Окончание приёма заявок")); - status = Grant.GrantStatus.LOADED_FROM_KIAS; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Grant.GrantStatus getStatus() { - return status; - } - - public void setStatus(Grant.GrantStatus status) { - this.status = status; - } - - public List getDeadlines() { - return deadlines; - } - - public void setDeadlines(List deadlines) { - this.deadlines = deadlines; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - public List getFiles() { - return files; - } - - public void setFiles(List files) { - this.files = files; - } - - public ProjectDto getProject() { - return project; - } - - public void setProject(ProjectDto project) { - this.project = project; - } - - public Set getAuthorIds() { - return authorIds; - } - - public void setAuthorIds(Set authorIds) { - this.authorIds = authorIds; - } - - public Set getAuthors() { - return authors; - } - - public void setAuthors(Set authors) { - this.authors = authors; - } - - public String getAuthorsString() { - return StringUtils.abbreviate(authors - .stream() - .map(author -> author.getLastName()) - .collect(Collectors.joining(", ")), MAX_AUTHORS_LENGTH); - } - - public Integer getLeaderId() { - return leaderId; - } - - public void setLeaderId(Integer leaderId) { - this.leaderId = leaderId; - } - - public boolean isWasLeader() { - return wasLeader; - } - - public void setWasLeader(boolean wasLeader) { - this.wasLeader = wasLeader; - } - - public boolean isHasAge() { - return hasAge; - } - - public void setHasAge(boolean hasAge) { - this.hasAge = hasAge; - } - - public boolean isHasDegree() { - return hasDegree; - } - - public void setHasDegree(boolean hasDegree) { - this.hasDegree = hasDegree; - } - - public List getPaperIds() { - return paperIds; - } - - public void setPaperIds(List paperIds) { - this.paperIds = paperIds; - } - - public List getPapers() { - return papers; - } - - public void setPapers(List papers) { - this.papers = papers; - } - - public List getRemovedDeadlineIds() { - return removedDeadlineIds; - } - - public void setRemovedDeadlineIds(List removedDeadlineIds) { - this.removedDeadlineIds = removedDeadlineIds; - } - - public boolean isHasBAKPapers() { - return hasBAKPapers; - } - - public void setHasBAKPapers(boolean hasBAKPapers) { - this.hasBAKPapers = hasBAKPapers; - } - - public boolean isHasScopusPapers() { - return hasScopusPapers; - } - - public void setHasScopusPapers(boolean hasScopusPapers) { - this.hasScopusPapers = hasScopusPapers; - } -} diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java deleted file mode 100644 index 28d3f8c..0000000 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ /dev/null @@ -1,341 +0,0 @@ -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; -import ru.ulstu.core.util.DateUtils; -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.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; -import ru.ulstu.ping.service.PingService; -import ru.ulstu.project.model.ProjectDto; -import ru.ulstu.project.service.ProjectService; -import ru.ulstu.timeline.service.EventService; -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; -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; -import static ru.ulstu.core.util.StreamApiUtils.convert; -import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; - -@Service -public class GrantService extends BaseService { - private final Logger log = LoggerFactory.getLogger(GrantService.class); - - private final GrantRepository grantRepository; - private final ProjectService projectService; - private final DeadlineService deadlineService; - private final FileService fileService; - private final UserService userService; - private final PaperService paperService; - private final EventService eventService; - private final GrantNotificationService grantNotificationService; - private final KiasService kiasService; - private final PingService pingService; - - public GrantService(GrantRepository grantRepository, - FileService fileService, - DeadlineService deadlineService, - ProjectService projectService, - UserService userService, - PaperService paperService, - EventService eventService, - GrantNotificationService grantNotificationService, - KiasService kiasService, - PingService pingService) { - this.grantRepository = grantRepository; - this.kiasService = kiasService; - this.baseRepository = grantRepository; - this.fileService = fileService; - this.deadlineService = deadlineService; - this.projectService = projectService; - this.userService = userService; - this.paperService = paperService; - this.eventService = eventService; - this.grantNotificationService = grantNotificationService; - this.pingService = pingService; - } - - public GrantDto getExistGrantById(Integer id) { - return new GrantDto(findById(id)); - } - - public List findAll() { - return grantRepository.findAll(); - } - - public List findAllDto() { - return convert(findAll(), GrantDto::new); - } - - @Transactional - public Grant create(GrantDto grantDto) throws IOException { - Grant newGrant = copyFromDto(new Grant(), grantDto); - newGrant = grantRepository.save(newGrant); - eventService.createFromObject(newGrant, Collections.emptyList(), false, "гранта"); - grantNotificationService.sendCreateNotification(newGrant); - return newGrant; - } - - private Grant copyFromDto(Grant grant, GrantDto grantDto) throws IOException { - grant.setComment(grantDto.getComment()); - grant.setStatus(grantDto.getStatus() == null ? APPLICATION : grantDto.getStatus()); - grant.setTitle(grantDto.getTitle()); - if (grantDto.getProject() != null && grantDto.getProject().getId() != null) { - grant.setProject(projectService.findById(grantDto.getProject().getId())); - } - grant.setDeadlines(deadlineService.saveOrCreate(grantDto.getDeadlines())); - if (!grant.getFiles().isEmpty()) { - grant.setFiles(fileService.saveOrCreate(grantDto.getFiles().stream() - .filter(f -> !f.isDeleted()) - .collect(toList()))); - } - grant.getAuthors().clear(); - if (grantDto.getAuthorIds() != null && !grantDto.getAuthorIds().isEmpty()) { - grantDto.getAuthorIds().forEach(authorIds -> grant.getAuthors().add(userService.findById(authorIds))); - } - if (grantDto.getLeaderId() != null) { - grant.setLeader(userService.findById(grantDto.getLeaderId())); - } - grant.getPapers().clear(); - if (grantDto.getPaperIds() != null && !grantDto.getPaperIds().isEmpty()) { - grantDto.getPaperIds().forEach(paperIds -> grant.getPapers().add(paperService.findPaperById(paperIds))); - } - return grant; - } - - - public void createProject(GrantDto grantDto) throws IOException { - grantDto.setProject( - new ProjectDto(projectService.save(new ProjectDto(grantDto.getTitle())))); - } - - @Transactional - private Integer update(GrantDto grantDto) throws IOException { - Grant grant = findById(grantDto.getId()); - Set oldAuthors = new HashSet<>(grant.getAuthors()); - User oldLeader = grant.getLeader(); - for (FileDataDto file : grantDto.getFiles().stream() - .filter(f -> f.isDeleted() && f.getId() != null) - .collect(toList())) { - fileService.delete(file.getId()); - } - grantDto.getRemovedDeadlineIds().forEach(deadlineService::remove); - grantRepository.save(copyFromDto(grant, grantDto)); - - grant.getAuthors().forEach(author -> { - if (!oldAuthors.contains(author)) { - grantNotificationService.sendAuthorsChangeNotification(grant, oldAuthors); - } - }); - oldAuthors.forEach(oldAuthor -> { - if (!grant.getAuthors().contains(oldAuthor)) { - grantNotificationService.sendAuthorsChangeNotification(grant, oldAuthors); - } - }); - if (grant.getLeader() != oldLeader) { - grantNotificationService.sendLeaderChangeNotification(grant, oldLeader); - } - eventService.updateGrantDeadlines(grant); - return grant.getId(); - } - - @Transactional - public boolean delete(Integer grantId) throws IOException { - Grant grant = findById(grantId); - if (grant != null) { - grantRepository.delete(grant); - return true; - } - return false; - } - - public List getGrantStatuses() { - return Arrays.asList(Grant.GrantStatus.values()); - } - - 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(), "Грант с таким именем уже существует"); - if (errors.hasErrors()) { - return false; - } - if (isEmpty(grantDto.getId())) { - create(grantDto); - } else { - update(grantDto); - } - return true; - } - - private boolean saveFromKias(GrantDto grantDto) throws IOException { - grantDto.setName(grantDto.getTitle()); - String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени - if (title != null) { - Grant grantFromDB = grantRepository.findByTitle(title); //грант с таким же названием из бд - if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают - return false; - } else { //иначе грант уже был в системе, но в другом году, поэтому надо создать - create(grantDto); - return true; - } - } else { //иначе такого гранта ещё нет, поэтому надо создать - create(grantDto); - return true; - } - } - - private void checkEmptyLeader(GrantDto grantDto, Errors errors) { - if (grantDto.getLeaderId().equals(-1)) { - errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); - } - } - - private void checkEmptyDeadlines(GrantDto grantDto, Errors errors) { - if (grantDto.getDeadlines().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Не может быть пусто"); - } - } - - private boolean checkSameDeadline(GrantDto grantDto, Integer id) { - Date date = DateUtils.clearTime(grantDto.getDeadlines().get(0).getDate()); //дата с сайта киас - Date foundGrantDate = DateUtils.clearTime(deadlineService.findByGrantIdAndDate(id, date)); - return foundGrantDate != null && foundGrantDate.compareTo(date) == 0; - } - - public List getGrantAuthors(GrantDto grantDto) { - List filteredUsers = userService.filterByAgeAndDegree(grantDto.isHasAge(), grantDto.isHasDegree()); - if (grantDto.isWasLeader()) { - filteredUsers = checkContains(filteredUsers, getCompletedGrantLeaders()); - } - if (grantDto.isHasBAKPapers()) { - filteredUsers = checkContains(filteredUsers, getBAKAuthors()); - } - if (grantDto.isHasScopusPapers()) { - filteredUsers = checkContains(filteredUsers, getScopusAuthors()); - } - return filteredUsers; - } - - private List checkContains(List filteredUsers, List checkUsers) { - return filteredUsers.stream() - .filter(checkUsers::contains) - .collect(toList()); - } - - private List getCompletedGrantLeaders() { - return grantRepository.findByStatus(Grant.GrantStatus.COMPLETED) - .stream() - .map(Grant::getLeader) - .collect(toList()); - } - - public List getGrantPapers(List paperIds) { - return paperService.findAllSelect(paperIds); - } - - public List getAllUncompletedPapers() { - return paperService.findAllNotCompleted(); - } - - public List attachPaper(GrantDto grantDto) { - if (!grantDto.getPaperIds().isEmpty()) { - grantDto.getPapers().clear(); - grantDto.setPapers(getGrantPapers(grantDto.getPaperIds())); - } else { - grantDto.getPapers().clear(); - } - return grantDto.getPapers(); - } - - public GrantDto removeDeadline(GrantDto grantDto, Integer deadlineId) { - if (grantDto.getDeadlines().get(deadlineId).getId() != null) { - grantDto.getRemovedDeadlineIds().add(grantDto.getDeadlines().get(deadlineId).getId()); - } - grantDto.getDeadlines().remove((int) deadlineId); - return grantDto; - } - - private List getCompletedPapersAuthors(Paper.PaperType type) { - List papers = paperService.findAllCompletedByType(type); - return papers.stream() - .filter(paper -> paper.getAuthors() != null) - .flatMap(paper -> paper.getAuthors().stream()) - .collect(toList()); - } - - private List getBAKAuthors() { - return getCompletedPapersAuthors(Paper.PaperType.VAK) - .stream() - .distinct() - .collect(toList()); - } - - private List getScopusAuthors() { - List authors = getCompletedPapersAuthors(Paper.PaperType.SCOPUS); - return authors - .stream() - .filter(author -> Collections.frequency(authors, author) > 3) - .collect(toList()); - } - - public List filterEmptyDeadlines(GrantDto grantDto) { - grantDto.setDeadlines(grantDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !StringUtils.isEmpty(dto.getDescription())) - .collect(Collectors.toList())); - return grantDto.getDeadlines(); - } - - @Transactional - public void createFromKias() throws IOException, ParseException { - for (GrantDto grantDto : kiasService.getNewGrantsDto()) { - if (saveFromKias(grantDto)) { - log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded"); - } else { - log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists"); - } - } - } - - public List findAllActiveDto() { - return convert(findAllActive(), GrantDto::new); - } - - public List findAllActive() { - return grantRepository.findAllActive(); - } - - public Grant findById(Integer id) { - return grantRepository.getOne(id); - } - - @Transactional - public void ping(int grantId) throws IOException { - pingService.addPing(findById(grantId)); - } -} diff --git a/src/main/java/ru/ulstu/index/controller/IndexController.java b/src/main/java/ru/ulstu/index/controller/IndexController.java deleted file mode 100644 index f6ab100..0000000 --- a/src/main/java/ru/ulstu/index/controller/IndexController.java +++ /dev/null @@ -1,23 +0,0 @@ -package ru.ulstu.index.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import ru.ulstu.core.controller.AdviceController; -import ru.ulstu.user.service.UserService; -import springfox.documentation.annotations.ApiIgnore; - -@Controller() -@RequestMapping(value = "/index") -@ApiIgnore -public class IndexController extends AdviceController { - public IndexController(UserService userService) { - super(userService); - } - - @GetMapping - public void currentUser(ModelMap modelMap) { - //нужен здесь для добавления параметров на стартовой странице - } -} diff --git a/src/main/java/ru/ulstu/name/BaseRepository.java b/src/main/java/ru/ulstu/name/BaseRepository.java deleted file mode 100644 index b691ea2..0000000 --- a/src/main/java/ru/ulstu/name/BaseRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package ru.ulstu.name; - -import org.springframework.data.repository.query.Param; - -public interface BaseRepository { - 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 deleted file mode 100644 index adcdc74..0000000 --- a/src/main/java/ru/ulstu/name/BaseService.java +++ /dev/null @@ -1,23 +0,0 @@ -package ru.ulstu.name; - -import org.springframework.stereotype.Service; -import org.springframework.validation.Errors; - -@Service -public abstract class BaseService { - - public BaseRepository baseRepository; - - protected void checkUniqueName(NameContainer nameContainer, Errors errors, Integer id, String errorMessage) { - if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) { - errors.rejectValue("title", "errorCode", errorMessage); - } - } - - protected String checkUniqueName(NameContainer nameContainer, Integer id) { - if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) { - return baseRepository.findByNameAndNotId(nameContainer.getName(), id); - } - return null; - } -} diff --git a/src/main/java/ru/ulstu/name/NameContainer.java b/src/main/java/ru/ulstu/name/NameContainer.java deleted file mode 100644 index 4339fb2..0000000 --- a/src/main/java/ru/ulstu/name/NameContainer.java +++ /dev/null @@ -1,14 +0,0 @@ -package ru.ulstu.name; - -public abstract class NameContainer { - - private String name = ""; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java deleted file mode 100644 index 29da57d..0000000 --- a/src/main/java/ru/ulstu/paper/controller/PaperController.java +++ /dev/null @@ -1,176 +0,0 @@ -package ru.ulstu.paper.controller; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.ModelAttribute; -import org.springframework.web.bind.annotation.PostMapping; -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; -import ru.ulstu.paper.model.ReferenceDto; -import ru.ulstu.paper.service.LatexService; -import ru.ulstu.paper.service.PaperService; -import ru.ulstu.user.model.User; -import springfox.documentation.annotations.ApiIgnore; - -import javax.validation.Valid; -import java.io.IOException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.stream.Collectors; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.springframework.util.StringUtils.isEmpty; - - -@Controller() -@RequestMapping(value = "/papers") -@ApiIgnore -public class PaperController { - private final PaperService paperService; - private final ConferenceService conferenceService; - private final LatexService latexService; - - public PaperController(PaperService paperService, - ConferenceService conferenceService, - LatexService latexService) { - this.paperService = paperService; - this.conferenceService = conferenceService; - this.latexService = latexService; - } - - @GetMapping("/papers") - public void getPapers(ModelMap modelMap) { - modelMap.put("filteredPapers", new PaperListDto(paperService.findAllDto(), null, null)); - } - - @PostMapping("/papers") - public void listPapers(@Valid PaperListDto paperListDto, ModelMap modelMap) { - if (paperListDto.getPaperDeleteId() != null) { - if (conferenceService.isAttachedToConference(paperListDto.getPaperDeleteId())) { - modelMap.put("flashMessage", "Статью нельзя удалить, она прикреплена к конференции"); - } else { - paperService.delete(paperListDto.getPaperDeleteId()); - } - } - modelMap.put("filteredPapers", new PaperListDto(paperService.filter(paperListDto), - paperListDto.getFilterAuthorId(), - paperListDto.getYear())); - } - - @GetMapping("/dashboard") - public void getDashboard(ModelMap modelMap) { - modelMap.put("papers", paperService.findAllActiveDto()); - } - - @GetMapping("/paper") - public void getPapers(ModelMap modelMap, @RequestParam(value = "id") Integer id) { - if (id != null && id > 0) { - modelMap.put("paperDto", paperService.findOneDto(id)); - } else { - modelMap.put("paperDto", new PaperDto()); - } - } - - @PostMapping(value = "/paper", params = "save") - public String save(@Valid PaperDto paperDto, Errors errors) throws IOException { - filterEmptyDeadlines(paperDto); - if (paperDto.getDeadlines().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Не может быть пустым"); - } - if (errors.hasErrors()) { - return "/papers/paper"; - } - paperService.save(paperDto); - return "redirect:/papers/papers"; - } - - @PostMapping(value = "/paper", params = "addDeadline") - public String addDeadline(@Valid PaperDto paperDto, Errors errors) { - filterEmptyDeadlines(paperDto); - if (errors.hasErrors()) { - return "/papers/paper"; - } - paperDto.getDeadlines().add(new Deadline()); - 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(); - } - - @ModelAttribute("allTypes") - public List getPaperTypes() { - return paperService.getPaperTypes(); - } - - @ModelAttribute("allAuthors") - public List getAllAuthors() { - return paperService.getPaperAuthors(); - } - - @ModelAttribute("allYears") - public List getAllYears() { - List years = new ArrayList<>(); - for (int i = Calendar.getInstance().get(Calendar.YEAR); i > 2010; i--) { - years.add(i); - } - 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(); - headers.add("Content-Disposition", "attachment; filename='" + - URLEncoder.encode(paper.getTitle() + ".pdf", UTF_8.toString()) + "'"); - 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); - } - - @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())) - .collect(Collectors.toList())); - } -} diff --git a/src/main/java/ru/ulstu/paper/controller/PaperRestController.java b/src/main/java/ru/ulstu/paper/controller/PaperRestController.java deleted file mode 100644 index b6dd11d..0000000 --- a/src/main/java/ru/ulstu/paper/controller/PaperRestController.java +++ /dev/null @@ -1,81 +0,0 @@ -package ru.ulstu.paper.controller; - -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import ru.ulstu.configuration.Constants; -import ru.ulstu.core.model.response.Response; -import ru.ulstu.paper.model.PaperDto; -import ru.ulstu.paper.model.PaperListDto; -import ru.ulstu.paper.model.ReferenceDto; -import ru.ulstu.paper.service.PaperService; - -import javax.validation.Valid; -import java.io.IOException; -import java.util.List; - -import static ru.ulstu.paper.controller.PaperRestController.URL; - -@RestController -@RequestMapping(URL) -public class PaperRestController { - public static final String URL = Constants.API_1_0 + "papers"; - - private final PaperService paperService; - - public PaperRestController(PaperService paperService) { - this.paperService = paperService; - } - - @GetMapping - public Response> getPapers() { - return new Response<>(paperService.findAllDto()); - } - - @GetMapping("/{paper-id}") - public Response getPaper(@PathVariable("paper-id") Integer paperId) { - return new Response<>(paperService.findById(paperId)); - } - - @PostMapping - public Response createPaper(@RequestBody @Valid PaperDto paperDto) throws IOException { - return new Response<>(paperService.create(paperDto)); - } - - @PutMapping - public Response updatePaper(@RequestBody @Valid PaperDto paperDto) throws IOException { - return new Response<>(paperService.update(paperDto)); - } - - @DeleteMapping("/{paper-id}") - public Response delete(@PathVariable("paper-id") Integer paperId) throws IOException { - paperService.delete(paperId); - return new Response<>(Boolean.TRUE); - } - - @PostMapping("/filter") - public Response> filter(@RequestBody @Valid PaperListDto paperListDto) throws IOException { - return new Response<>(paperService.filter(paperListDto)); - } - - @GetMapping("formatted-list") - public Response> getFormattedPaperList() { - return new Response<>(paperService.getFormattedPaperList()); - } - - @PostMapping("/getFormattedReference") - public Response getFormattedReference(@RequestBody @Valid ReferenceDto referenceDto) { - return new Response<>(paperService.getFormattedReference(referenceDto)); - } - - @PostMapping(value = "/ping") - public void ping(@RequestParam("paperId") int paperId) throws IOException { - paperService.ping(paperId); - } -} diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java deleted file mode 100644 index 2fee949..0000000 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ /dev/null @@ -1,398 +0,0 @@ -package ru.ulstu.paper.service; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -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; -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.ping.service.PingService; -import ru.ulstu.timeline.service.EventService; -import ru.ulstu.user.model.User; -import ru.ulstu.user.service.UserService; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Arrays; -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; -import static ru.ulstu.core.util.StreamApiUtils.convert; -import static ru.ulstu.paper.model.Paper.PaperStatus.ATTENTION; -import static ru.ulstu.paper.model.Paper.PaperStatus.COMPLETED; -import static ru.ulstu.paper.model.Paper.PaperStatus.DRAFT; -import static ru.ulstu.paper.model.Paper.PaperStatus.FAILED; -import static ru.ulstu.paper.model.Paper.PaperStatus.ON_PREPARATION; -import static ru.ulstu.paper.model.Paper.PaperType.OTHER; -import static ru.ulstu.paper.model.ReferenceDto.FormatStandard.GOST; -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"; - - private final PaperNotificationService paperNotificationService; - private final PaperRepository paperRepository; - private final UserService userService; - private final DeadlineService deadlineService; - private final FileService fileService; - private final EventService eventService; - private final ReferenceRepository referenceRepository; - private final PingService pingService; - - public PaperService(PaperRepository paperRepository, - ReferenceRepository referenceRepository, - FileService fileService, - PaperNotificationService paperNotificationService, - UserService userService, - DeadlineService deadlineService, - EventService eventService, - PingService pingService) { - this.paperRepository = paperRepository; - this.referenceRepository = referenceRepository; - this.fileService = fileService; - this.paperNotificationService = paperNotificationService; - this.userService = userService; - this.deadlineService = deadlineService; - this.eventService = eventService; - this.pingService = pingService; - } - - public List findAll() { - return sortPapers(paperRepository.findAll()); - } - - public List findAllDto() { - List papers = convert(findAll(), PaperDto::new); - papers.forEach(paperDto -> paperDto.setTitle(StringUtils.abbreviate(paperDto.getTitle(), MAX_DISPLAY_SIZE))); - return papers; - } - - private List findAllActive() { - return findAll() - .stream() - .filter(paper -> paper.getStatus() != COMPLETED && paper.getStatus() != FAILED) - .collect(toList()); - } - - public List findAllActiveDto() { - return convert(findAllActive(), PaperDto::new); - } - - public PaperDto findOneDto(Integer id) { - return new PaperDto(paperRepository.getOne(id)); - } - - @Transactional - public Integer create(PaperDto paperDto) throws IOException { - Paper newPaper = copyFromDto(new Paper(), paperDto); - newPaper = paperRepository.save(newPaper); - paperNotificationService.sendCreateNotification(newPaper); - eventService.createFromPaper(newPaper); - return newPaper.getId(); - } - - @Transactional - public Paper create(Paper paper) { - Paper newPaper = paperRepository.save(paper); - paperNotificationService.sendCreateNotification(newPaper); - eventService.createFromPaper(newPaper); - return newPaper; - } - - private Paper copyFromDto(Paper paper, PaperDto paperDto) throws IOException { - paper.setComment(paperDto.getComment()); - paper.setUrl(paperDto.getUrl()); - paper.setLatexText(paperDto.getLatexText()); - paper.setCreateDate(paper.getCreateDate() == null ? new Date() : paper.getCreateDate()); - paper.setLocked(paperDto.getLocked()); - paper.setStatus(paperDto.getStatus() == null ? DRAFT : paperDto.getStatus()); - paper.setType(paperDto.getType() == null ? OTHER : paperDto.getType()); - 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()))); - paper.getAuthors().clear(); - if (paperDto.getAuthorIds() != null && !paperDto.getAuthorIds().isEmpty()) { - paperDto.getAuthorIds().forEach(authorIds -> paper.getAuthors().add(userService.findById(authorIds))); - } - return paper; - } - - private List saveOrCreateReferences(List references) { - return references - .stream() - .filter(reference -> !reference.getDeleted()) - .map(reference -> reference.getId() != null ? updateReference(reference) : createReference(reference)) - .collect(Collectors.toList()); - } - - @Transactional - private Reference updateReference(ReferenceDto referenceDto) { - Reference updateReference = referenceRepository.getOne(referenceDto.getId()); - copyFromDto(updateReference, referenceDto); - referenceRepository.save(updateReference); - return updateReference; - } - - @Transactional - private Reference createReference(ReferenceDto referenceDto) { - Reference newReference = new Reference(); - copyFromDto(newReference, referenceDto); - newReference = referenceRepository.save(newReference); - return newReference; - } - - private Reference copyFromDto(Reference reference, ReferenceDto referenceDto) { - reference.setAuthors(referenceDto.getAuthors()); - reference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle()); - reference.setPages(referenceDto.getPages()); - reference.setPublicationTitle(referenceDto.getPublicationTitle()); - reference.setPublicationYear(referenceDto.getPublicationYear()); - reference.setPublisher(referenceDto.getPublisher()); - reference.setReferenceType(referenceDto.getReferenceType()); - return reference; - } - - @Transactional - public Integer update(PaperDto paperDto) throws IOException { - Paper paper = paperRepository.getOne(paperDto.getId()); - Paper.PaperStatus oldStatus = paper.getStatus(); - Set oldAuthors = new HashSet<>(paper.getAuthors()); - - for (FileDataDto file : paperDto.getFiles().stream() - .filter(f -> f.isDeleted() && f.getId() != null) - .collect(toList())) { - 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 -> { - if (!oldAuthors.contains(author)) { - paperNotificationService.sendCreateNotification(paper); - } - }); - - if (paper.getStatus() != oldStatus) { - paperNotificationService.statusChangeNotification(paper, oldStatus); - } - - return paper.getId(); - } - - @Transactional - public void delete(Integer paperId) { - Paper paper = paperRepository.getOne(paperId); - paperRepository.delete(paper); - } - - public List getPaperStatuses() { - return Arrays.asList(Paper.PaperStatus.values()); - } - - public List getPaperTypes() { - 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(); - paper.setTitle(title); - paper.getAuthors().add(user); - paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); - paper.setCreateDate(new Date()); - paper.setUpdateDate(new Date()); - paper.setStatus(DRAFT); - paper.setType(OTHER); - paper = paperRepository.save(paper); - - paperNotificationService.sendCreateNotification(paper); - eventService.createFromPaper(paper); - - return paper; - } - - public List filter(PaperListDto filterDto) { - return convert(sortPapers(paperRepository.filter( - filterDto.getFilterAuthorId() == null ? null : userService.findById(filterDto.getFilterAuthorId()), - filterDto.getYear())), PaperDto::new); - } - - private List sortPapers(List papers) { - return papers.stream().sorted((paper1, paper2) -> { - int statusCompareResult = - Integer.valueOf(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper1.getStatus())) - .compareTo(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper2.getStatus())); - if (statusCompareResult != 0) { - return statusCompareResult; - } - return paper1.getTitle().compareTo(paper2.getTitle()); - }).collect(toList()); - } - - public PaperDto findPaper(int id) { - return new PaperDto(paperRepository.getOne(id)); - } - - public void closeFailedPapers() { - List papers = paperRepository.findAll() - .stream() - .filter(paper -> paper.lastDeadlineFailed() - && (paper.getStatus() == ON_PREPARATION - || paper.getStatus() == DRAFT - || paper.getStatus() == ATTENTION)) - .collect(toList()); - papers.forEach(paper -> { - Paper.PaperStatus oldStatus = paper.getStatus(); - paper.setStatus(Paper.PaperStatus.FAILED); - paperRepository.save(paper); - paperNotificationService.sendFailedNotification(paper, oldStatus); - }); - } - - public void save(PaperDto paperDto) throws IOException { - if (isEmpty(paperDto.getId())) { - create(paperDto); - } else { - update(paperDto); - } - } - - public PaperDto findById(Integer paperId) { - return new PaperDto(paperRepository.getOne(paperId)); - } - - public Paper findPaperById(Integer paperId) { - return paperRepository.getOne(paperId); - } - - public List findAllNotSelect(List paperIds) { - if (!paperIds.isEmpty()) { - return sortPapers(paperRepository.findByIdNotInAndConferencesIsNullAndStatusNot(paperIds, COMPLETED)); - } else { - return sortPapers(paperRepository.findByConferencesIsNullAndStatusNot(COMPLETED)); - } - } - - public List findAllNotCompleted() { - return convert(paperRepository.findByStatusNot(COMPLETED), PaperDto::new); - } - - public List findAllSelect(List paperIds) { - return convert(paperRepository.findAllByIdIn(paperIds), PaperDto::new); - } - - public List getPaperAuthors() { - return userService.findAll(); - } - - public List getFormattedPaperList() { - return findAllCompleted() - .stream() - .map(paper -> String.format(PAPER_FORMATTED_TEMPLATE, paper.getTitle(), getAuthors(paper))) - .collect(toList()); - } - - private List 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(", ")); - } - - public String getFormattedReference(ReferenceDto referenceDto) { - return referenceDto.getFormatStandard() == GOST - ? getGostReference(referenceDto) - : getSpringerReference(referenceDto); - } - - public String getFormattedReferences(PaperDto paperDto) { - return String.join("\r\n", paperDto.getReferences() - .stream() - .filter(r -> !r.getDeleted()) - .map(r -> { - r.setFormatStandard(paperDto.getFormatStandard()); - return getFormattedReference(r); - }) - .collect(Collectors.toList())); - } - - private String getGostReference(ReferenceDto referenceDto) { - return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.", - referenceDto.getAuthors(), - referenceDto.getPublicationTitle(), - StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", - referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", - referenceDto.getPages(), - StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + "."); - } - - private String getSpringerReference(ReferenceDto referenceDto) { - return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}", - referenceDto.getAuthors(), - referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", - referenceDto.getPublicationTitle(), - referenceDto.getReferenceType() == ARTICLE ? " " + referenceDto.getJournalOrCollectionTitle() + "," : "", - StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", - referenceDto.getPages()); - } - - 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; - } - - @Transactional - public void ping(int paperId) throws IOException { - pingService.addPing(findPaperById(paperId)); - } -} diff --git a/src/main/java/ru/ulstu/project/controller/ProjectController.java b/src/main/java/ru/ulstu/project/controller/ProjectController.java deleted file mode 100644 index 09438fd..0000000 --- a/src/main/java/ru/ulstu/project/controller/ProjectController.java +++ /dev/null @@ -1,127 +0,0 @@ -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.GetMapping; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.grant.model.GrantDto; -import ru.ulstu.project.model.Project; -import ru.ulstu.project.model.ProjectDto; -import ru.ulstu.project.service.ProjectService; -import ru.ulstu.user.model.User; -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; - -@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()); - } - - @GetMapping("/project") - public void getProject(ModelMap modelMap, @RequestParam(value = "id") Integer id) { - if (id != null && id > 0) { - ProjectDto projectDto = projectService.findOneDto(id); - attachGrant(projectDto); - modelMap.put("projectDto", projectService.findOneDto(id)); - } else { - modelMap.put("projectDto", new ProjectDto()); - } - } - - @ModelAttribute("allStatuses") - public List getProjectStatuses() { - return projectService.getProjectStatuses(); - } - - @PostMapping(value = "/project", params = "save") - public String save(@Valid ProjectDto projectDto, Errors errors) throws IOException { - filterEmptyDeadlines(projectDto); - if (projectDto.getDeadlines().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Не может быть пустым"); - } - if (errors.hasErrors()) { - return "/projects/project"; - } - projectService.save(projectDto); - return String.format("redirect:%s", "/projects/projects"); - } - - @PostMapping(value = "/project", params = "attachGrant") - public String attachGrant(ProjectDto projectDto) { - projectService.attachGrant(projectDto); - return "/projects/project"; - } - - @PostMapping(value = "/project", params = "addDeadline") - public String addDeadline(@Valid ProjectDto projectDto, Errors errors) { - filterEmptyDeadlines(projectDto); - if (errors.hasErrors()) { - return "/projects/project"; - } - projectDto.getDeadlines().add(new Deadline()); - 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); - return String.format("redirect:%s", "/projects/projects"); - } - - @ModelAttribute("allExecutors") - public List getAllExecutors(ProjectDto projectDto) { - return projectService.getProjectExecutors(projectDto); - } - - @ModelAttribute("allGrants") - public List getAllGrants() { - return projectService.getAllGrants(); - } - - private void filterEmptyDeadlines(ProjectDto projectDto) { - projectDto.setDeadlines(projectDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) - .collect(Collectors.toList())); - } - - @ResponseBody - @PostMapping(value = "/ping") - public void ping(@RequestParam("projectId") int projectId) throws IOException { - projectService.ping(projectId); - } -} diff --git a/src/main/java/ru/ulstu/project/repository/ProjectRepository.java b/src/main/java/ru/ulstu/project/repository/ProjectRepository.java deleted file mode 100644 index 6a78075..0000000 --- a/src/main/java/ru/ulstu/project/repository/ProjectRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package ru.ulstu.project.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import ru.ulstu.project.model.Project; - -public interface ProjectRepository extends JpaRepository { - -} diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java deleted file mode 100644 index 07b07fa..0000000 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ /dev/null @@ -1,171 +0,0 @@ -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.file.model.FileDataDto; -import ru.ulstu.file.service.FileService; -import ru.ulstu.grant.model.GrantDto; -import ru.ulstu.grant.repository.GrantRepository; -import ru.ulstu.ping.service.PingService; -import ru.ulstu.project.model.Project; -import ru.ulstu.project.model.ProjectDto; -import ru.ulstu.project.repository.ProjectRepository; -import ru.ulstu.timeline.service.EventService; -import ru.ulstu.user.model.User; -import ru.ulstu.user.service.UserService; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static java.util.stream.Collectors.toList; -import static org.springframework.util.ObjectUtils.isEmpty; -import static ru.ulstu.core.util.StreamApiUtils.convert; -import static ru.ulstu.project.model.Project.ProjectStatus.TECHNICAL_TASK; - -@Service -public class ProjectService { - private final static int MAX_DISPLAY_SIZE = 40; - - private final ProjectRepository projectRepository; - private final DeadlineService deadlineService; - private final GrantRepository grantRepository; - private final FileService fileService; - private final EventService eventService; - private final UserService userService; - private final PingService pingService; - - public ProjectService(ProjectRepository projectRepository, - DeadlineService deadlineService, - GrantRepository grantRepository, - FileService fileService, - EventService eventService, - UserService userService, - PingService pingService) { - this.projectRepository = projectRepository; - this.deadlineService = deadlineService; - this.grantRepository = grantRepository; - this.fileService = fileService; - this.eventService = eventService; - this.userService = userService; - this.pingService = pingService; - } - - public List findAll() { - 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; - } - - public ProjectDto findOneDto(Integer id) { - return new ProjectDto(projectRepository.getOne(id)); - } - - public List getProjectStatuses() { - return Arrays.asList(Project.ProjectStatus.values()); - } - - @Transactional - public Project create(ProjectDto projectDto) throws IOException { - Project newProject = copyFromDto(new Project(), projectDto); - newProject = projectRepository.save(newProject); - eventService.createFromObject(newProject, Collections.emptyList(), false, "проекта"); - return newProject; - } - - @Transactional - private Project update(ProjectDto projectDto) throws IOException { - Project project = projectRepository.getOne(projectDto.getId()); - projectRepository.save(copyFromDto(project, projectDto)); - eventService.updateProjectDeadlines(project); - for (FileDataDto file : projectDto.getFiles().stream() - .filter(f -> f.isDeleted() && f.getId() != null) - .collect(toList())) { - fileService.delete(file.getId()); - } - return project; - } - - @Transactional - public boolean delete(Integer projectId) throws IOException { - if (projectRepository.existsById(projectId)) { - Project project = projectRepository.getOne(projectId); - projectRepository.delete(project); - return true; - } - return false; - } - - private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException { - project.setDescription(projectDto.getDescription()); - project.setStatus(projectDto.getStatus() == null ? TECHNICAL_TASK : projectDto.getStatus()); - project.setTitle(projectDto.getTitle()); - if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) { - project.setGrant(grantRepository.getOne(projectDto.getGrant().getId())); - } - project.setRepository(projectDto.getRepository()); - project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines())); - project.setFiles(fileService.saveOrCreate(projectDto.getFiles().stream() - .filter(f -> !f.isDeleted()) - .collect(toList()))); - project.getGrants().clear(); - if (projectDto.getGrantIds() != null && !projectDto.getGrantIds().isEmpty()) { - projectDto.getGrantIds().forEach(grantIds -> project.getGrants().add(grantRepository.findGrantById(grantIds))); - } - return project; - } - - public Project save(ProjectDto projectDto) throws IOException { - if (isEmpty(projectDto.getId())) { - return create(projectDto); - } else { - return update(projectDto); - } - } - - public ProjectDto removeDeadline(ProjectDto projectDto, Integer deadlineId) { - if (deadlineId != null) { - projectDto.getRemovedDeadlineIds().add(deadlineId); - } - projectDto.getDeadlines().remove((int) deadlineId); - return projectDto; - } - - public Project findById(Integer id) { - return projectRepository.getOne(id); - } - - public List getProjectExecutors(ProjectDto projectDto) { - return userService.findAll(); - } - - @Transactional - public void ping(int projectId) throws IOException { - pingService.addPing(findById(projectId)); - } - - public List getAllGrants() { - return convert(grantRepository.findAll(), GrantDto::new); - } - - private List getProjectGrants(List grantIds) { - return convert(grantRepository.findAllById(grantIds), GrantDto::new); - } - - public void attachGrant(ProjectDto projectDto) { - if (!projectDto.getGrantIds().isEmpty()) { - projectDto.getGrants().clear(); - projectDto.setGrants(getProjectGrants(projectDto.getGrantIds())); - } else { - projectDto.getGrants().clear(); - } - } - -} diff --git a/src/main/java/ru/ulstu/students/controller/Navigation.java b/src/main/java/ru/ulstu/students/controller/Navigation.java deleted file mode 100644 index 348f062..0000000 --- a/src/main/java/ru/ulstu/students/controller/Navigation.java +++ /dev/null @@ -1,16 +0,0 @@ -package ru.ulstu.students.controller; - -import org.springframework.validation.Errors; - -class Navigation { - public static final String REDIRECT_TO = "redirect:%s"; - public static final String TASKS_PAGE = "/students/tasks"; - public static final String TASK_PAGE = "/students/task"; - - public static String hasErrors(Errors errors, String page) { - if (errors.hasErrors()) { - return page; - } - return null; - } -} diff --git a/src/main/java/ru/ulstu/students/controller/TaskController.java b/src/main/java/ru/ulstu/students/controller/TaskController.java deleted file mode 100644 index 5d0f4e8..0000000 --- a/src/main/java/ru/ulstu/students/controller/TaskController.java +++ /dev/null @@ -1,113 +0,0 @@ -package ru.ulstu.students.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.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.students.model.Task; -import ru.ulstu.students.model.TaskDto; -import ru.ulstu.students.model.TaskFilterDto; -import ru.ulstu.students.service.TaskService; -import ru.ulstu.tags.model.Tag; -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.students.controller.Navigation.REDIRECT_TO; -import static ru.ulstu.students.controller.Navigation.TASKS_PAGE; -import static ru.ulstu.students.controller.Navigation.TASK_PAGE; - -@Controller() -@RequestMapping(value = "/students") -@ApiIgnore -public class TaskController { - - private final TaskService taskService; - - public TaskController(TaskService taskService) { - this.taskService = taskService; - } - - @GetMapping("/dashboard") - public void getDashboard(ModelMap modelMap) { - modelMap.put("tasks", taskService.findAllDto()); - } - - @GetMapping("/tasks") - public void getTask(ModelMap modelMap) { - modelMap.put("filteredTasks", new TaskFilterDto(taskService.findAllDto(), null, null, null)); - } - - @GetMapping("/task") - public void getTask(ModelMap modelMap, @RequestParam(value = "id") Integer id) { - if (id != null && id > 0) { - modelMap.put("taskDto", taskService.findOneDto(id)); - } else { - modelMap.put("taskDto", new TaskDto()); - } - } - - @PostMapping("/tasks") - public void filterTasks(@Valid TaskFilterDto taskFilterDto, ModelMap modelMap) { - modelMap.put("filteredTasks", new TaskFilterDto(taskService.filter(taskFilterDto), - taskFilterDto.getStatus(), - taskFilterDto.getTag(), - taskFilterDto.getOrder())); - } - - @PostMapping(value = "/task", params = "save") - public String save(@Valid TaskDto taskDto, Errors errors) throws IOException { - filterEmptyDeadlines(taskDto); - if (taskDto.getDeadlines().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Не может быть пустым"); - } - if (errors.hasErrors()) { - return TASK_PAGE; - } - taskService.save(taskDto); - return String.format(REDIRECT_TO, TASKS_PAGE); - } - - @PostMapping(value = "/task", params = "addDeadline") - public String addDeadline(@Valid TaskDto taskDto, Errors errors) { - filterEmptyDeadlines(taskDto); - if (errors.hasErrors()) { - return TASK_PAGE; - } - taskDto.getDeadlines().add(new Deadline()); - return TASK_PAGE; - } - - @GetMapping("/delete/{task-id}") - public String delete(@PathVariable("task-id") Integer taskId) throws IOException { - taskService.delete(taskId); - return String.format(REDIRECT_TO, TASKS_PAGE); - } - - - @ModelAttribute("allStatuses") - public List getTaskStatuses() { - return taskService.getTaskStatuses(); - } - - @ModelAttribute("allTags") - public List getTags() { - return taskService.getTags(); - } - - private void filterEmptyDeadlines(TaskDto taskDto) { - taskDto.setDeadlines(taskDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) - .collect(Collectors.toList())); - } -} diff --git a/src/main/java/ru/ulstu/students/repository/SchedulerRepository.java b/src/main/java/ru/ulstu/students/repository/SchedulerRepository.java deleted file mode 100644 index 7481692..0000000 --- a/src/main/java/ru/ulstu/students/repository/SchedulerRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -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 findOneByTask(Task task); - -} diff --git a/src/main/java/ru/ulstu/timeline/controller/EventController.java b/src/main/java/ru/ulstu/timeline/controller/EventController.java deleted file mode 100644 index 2a9245c..0000000 --- a/src/main/java/ru/ulstu/timeline/controller/EventController.java +++ /dev/null @@ -1,54 +0,0 @@ -package ru.ulstu.timeline.controller; - -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import ru.ulstu.configuration.Constants; -import ru.ulstu.core.model.response.Response; -import ru.ulstu.timeline.model.EventDto; -import ru.ulstu.timeline.service.EventService; - -import javax.validation.Valid; -import java.util.List; - -@RestController -@RequestMapping(Constants.API_1_0 + "events") -public class EventController { - - private final EventService eventService; - - public EventController(EventService eventService) { - this.eventService = eventService; - } - - @GetMapping - public Response> getEvents() { - return new Response<>(eventService.findAllDto()); - } - - @GetMapping("/future") - public Response> getFutureEvents() { - return new Response<>(eventService.findAllFutureDto()); - } - - @PostMapping - public Response createEvent(@RequestBody @Valid EventDto timelineDto) { - return new Response<>(eventService.create(timelineDto)); - } - - @PutMapping - public Response updateEvent(@RequestBody @Valid EventDto eventDto) { - return new Response<>(eventService.update(eventDto)); - } - - @DeleteMapping("/{event-id}") - public Response delete(@PathVariable("event-id") Integer eventId) { - eventService.delete(eventId); - return new Response<>(Boolean.TRUE); - } -} diff --git a/src/main/java/ru/ulstu/timeline/model/EventDto.java b/src/main/java/ru/ulstu/timeline/model/EventDto.java deleted file mode 100644 index 7c3a836..0000000 --- a/src/main/java/ru/ulstu/timeline/model/EventDto.java +++ /dev/null @@ -1,170 +0,0 @@ -package ru.ulstu.timeline.model; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import ru.ulstu.conference.model.ConferenceDto; -import ru.ulstu.grant.model.GrantDto; -import ru.ulstu.paper.model.PaperDto; -import ru.ulstu.project.model.ProjectDto; -import ru.ulstu.students.model.TaskDto; -import ru.ulstu.user.model.UserDto; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import java.util.Date; -import java.util.List; - -import static ru.ulstu.core.util.StreamApiUtils.convert; - -public class EventDto { - private final Integer id; - @NotBlank - private final String title; - private final PeriodEvent period; - private final Event.EventStatus status; - @NotNull - private final Date executeDate; - private final Date createDate; - private final Date updateDate; - private final String description; - private final List recipients; - private PaperDto paperDto; - private ConferenceDto conferenceDto; - private GrantDto grantDto; - private ProjectDto projectDto; - private TaskDto taskDto; - - @JsonCreator - public EventDto(@JsonProperty("id") Integer id, - @JsonProperty("title") String title, - @JsonProperty("status") Event.EventStatus status, - @JsonProperty("period") PeriodEvent period, - @JsonProperty("executeDate") Date executeDate, - @JsonProperty("createDate") Date createDate, - @JsonProperty("updateDate") Date updateDate, - @JsonProperty("description") String description, - @JsonProperty("paperDto") PaperDto paperDto, - @JsonProperty("recipients") List recipients, - @JsonProperty("conferenceDto") ConferenceDto conferenceDto, - @JsonProperty("grantDto") GrantDto grantDto, - @JsonProperty("projectDto") ProjectDto projectDto, - @JsonProperty("taskDto") TaskDto taskDto) { - this.id = id; - this.title = title; - this.period = period; - this.status = status; - this.executeDate = executeDate; - this.createDate = createDate; - this.updateDate = updateDate; - this.description = description; - this.recipients = recipients; - this.paperDto = paperDto; - this.conferenceDto = conferenceDto; - this.grantDto = grantDto; - this.projectDto = projectDto; - this.taskDto = taskDto; - } - - public EventDto(Event event) { - this.id = event.getId(); - this.title = event.getTitle(); - this.status = event.getStatus(); - this.period = event.getPeriod(); - this.executeDate = event.getExecuteDate(); - this.createDate = event.getCreateDate(); - this.updateDate = event.getUpdateDate(); - this.description = event.getDescription(); - this.recipients = convert(event.getRecipients(), UserDto::new); - if (paperDto != null) { - this.paperDto = new PaperDto(event.getPaper()); - } - if (conferenceDto != null) { - this.conferenceDto = new ConferenceDto(event.getConference()); - } - if (grantDto != null) { - this.grantDto = new GrantDto(event.getGrant()); - } - if (projectDto != null) { - this.projectDto = new ProjectDto(event.getProject()); - } - if (taskDto != null) { - this.taskDto = new TaskDto(event.getTask()); - } - } - - public Integer getId() { - return id; - } - - public String getTitle() { - return title; - } - - public PeriodEvent getPeriod() { - return period; - } - - public Event.EventStatus getStatus() { - return status; - } - - public Date getCreateDate() { - return createDate; - } - - public Date getUpdateDate() { - return updateDate; - } - - public String getDescription() { - return description; - } - - public List getRecipients() { - return recipients; - } - - public Date getExecuteDate() { - return executeDate; - } - - public PaperDto getPaperDto() { - return paperDto; - } - - public void setPaperDto(PaperDto paperDto) { - this.paperDto = paperDto; - } - - public ConferenceDto getConferenceDto() { - return conferenceDto; - } - - public void setConferenceDto(ConferenceDto conferenceDto) { - this.conferenceDto = conferenceDto; - } - - public GrantDto getGrantDto() { - return grantDto; - } - - public void setGrantDto(GrantDto grantDto) { - this.grantDto = grantDto; - } - - public ProjectDto getProjectDto() { - return projectDto; - } - - public void setProjectDto(ProjectDto projectDto) { - this.projectDto = projectDto; - } - - public TaskDto getTaskDto() { - return taskDto; - } - - public void setTaskDto(TaskDto taskDto) { - this.taskDto = taskDto; - } -} diff --git a/src/main/java/ru/ulstu/timeline/model/PeriodEvent.java b/src/main/java/ru/ulstu/timeline/model/PeriodEvent.java deleted file mode 100644 index 39eaffb..0000000 --- a/src/main/java/ru/ulstu/timeline/model/PeriodEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package ru.ulstu.timeline.model; - -import java.time.Period; - -public enum PeriodEvent { - EVERY_YEAR(Period.ofYears(1), "Каждый год"), - EVERY_MONTH(Period.ofMonths(1), "Каждый месяц"), - EVERY_WEEK(Period.ofWeeks(1), "Каждую неделю"), - EVERY_DAY(Period.ofDays(1), "Каждый день"); - - private final Period period; - private final String message; - - PeriodEvent(Period period, String message) { - this.period = period; - this.message = message; - } - - public Period getPeriod() { - return period; - } - - public String getMessage() { - return message; - } -} diff --git a/src/main/java/ru/ulstu/timeline/model/Timeline.java b/src/main/java/ru/ulstu/timeline/model/Timeline.java deleted file mode 100644 index 06e04bc..0000000 --- a/src/main/java/ru/ulstu/timeline/model/Timeline.java +++ /dev/null @@ -1,26 +0,0 @@ -package ru.ulstu.timeline.model; - -import ru.ulstu.core.model.BaseEntity; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; -import java.util.ArrayList; -import java.util.List; - -@Entity -public class Timeline extends BaseEntity { - - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "timeline_id") - private List events = new ArrayList<>(); - - public List getEvents() { - return events; - } - - public void setEvents(List events) { - this.events = events; - } -} diff --git a/src/main/java/ru/ulstu/timeline/model/TimelineDto.java b/src/main/java/ru/ulstu/timeline/model/TimelineDto.java deleted file mode 100644 index 1c651a7..0000000 --- a/src/main/java/ru/ulstu/timeline/model/TimelineDto.java +++ /dev/null @@ -1,33 +0,0 @@ -package ru.ulstu.timeline.model; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - -import static ru.ulstu.core.util.StreamApiUtils.convert; - -public class TimelineDto { - private final Integer id; - private final List events; - - @JsonCreator - public TimelineDto(@JsonProperty("id") Integer id, - @JsonProperty("events") List events) { - this.id = id; - this.events = events; - } - - public TimelineDto(Timeline timeline) { - this.id = timeline.getId(); - this.events = convert(timeline.getEvents(), EventDto::new); - } - - public Integer getId() { - return id; - } - - public List getEvents() { - return events; - } -} diff --git a/src/main/java/ru/ulstu/timeline/repository/EventRepository.java b/src/main/java/ru/ulstu/timeline/repository/EventRepository.java deleted file mode 100644 index 15e1355..0000000 --- a/src/main/java/ru/ulstu/timeline/repository/EventRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -package ru.ulstu.timeline.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.grant.model.Grant; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.project.model.Project; -import ru.ulstu.students.model.Task; -import ru.ulstu.timeline.model.Event; - -import java.util.List; - -public interface EventRepository extends JpaRepository { - @Query("SELECT e FROM Event e WHERE e.executeDate = CURRENT_DATE") - List findByCurrentDate(); - - @Query("SELECT e FROM Event e WHERE e.executeDate > CURRENT_DATE ORDER BY e.executeDate") - List findAllFuture(); - - List findAllByPaper(Paper paper); - - List findAllByConference(Conference conference); - - List findAllByGrant(Grant grant); - - List findAllByProject(Project project); - - List findAllByTask(Task task); -} diff --git a/src/main/java/ru/ulstu/timeline/repository/TimelineRepository.java b/src/main/java/ru/ulstu/timeline/repository/TimelineRepository.java deleted file mode 100644 index 6b1be39..0000000 --- a/src/main/java/ru/ulstu/timeline/repository/TimelineRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package ru.ulstu.timeline.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import ru.ulstu.timeline.model.Timeline; - -public interface TimelineRepository extends JpaRepository { -} diff --git a/src/main/java/ru/ulstu/timeline/service/EventScheduler.java b/src/main/java/ru/ulstu/timeline/service/EventScheduler.java deleted file mode 100644 index 7899aca..0000000 --- a/src/main/java/ru/ulstu/timeline/service/EventScheduler.java +++ /dev/null @@ -1,77 +0,0 @@ -package ru.ulstu.timeline.service; - -import com.google.common.collect.ImmutableMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import ru.ulstu.core.util.DateUtils; -import ru.ulstu.timeline.model.Event; -import ru.ulstu.timeline.model.PeriodEvent; -import ru.ulstu.user.service.MailService; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -@Service -public class EventScheduler { - - private final Logger log = LoggerFactory.getLogger(EventScheduler.class); - private final EventService eventService; - private final MailService mailService; - - public EventScheduler(EventService eventService, - MailService mailService) { - this.eventService = eventService; - this.mailService = mailService; - } - - @Scheduled(cron = "0 0 8 * * ?") - public void sendNotifications() { - List events = eventService.findByCurrentDate(); - events.forEach(event -> { - Map variables = ImmutableMap.of("description", event.getDescription()); - event.getRecipients() - .forEach(recipient -> mailService.sendEmailFromTemplate(variables, recipient, "eventNotification", event.getTitle())); - if (event.getPeriod() == null) { - event.setStatus(Event.EventStatus.COMPLETED); - eventService.save(event); - } - }); - } - - @Scheduled(cron = "0 0 * * * ?") - public void checkPeriodEvents() { - log.debug("EventScheduler.checkPeriodEvents started"); - //TODO: filter - for (Event event : eventService.findAll()) { - if (halfOfThePeriodHasPassed(event)) { - eventService.createBasedOn(event, DateUtils.addDays(event.getExecuteDate(), getShiftInDays(event.getPeriod()))); - } - } - - log.debug("EventScheduler.checkPeriodEvents finished"); - } - - private int getShiftInDays(PeriodEvent periodEvent) { - switch (periodEvent) { - case EVERY_DAY: - return periodEvent.getPeriod().getDays(); - case EVERY_WEEK: - return periodEvent.getPeriod().getDays(); - case EVERY_MONTH: - return periodEvent.getPeriod().getMonths() * 30; - case EVERY_YEAR: - return periodEvent.getPeriod().getYears() * 365; - default: - throw new RuntimeException("period event not exists"); - } - } - - private boolean halfOfThePeriodHasPassed(Event event) { - return event.getPeriod() != null && event.getChild() == null - && new Date().after( - DateUtils.addDays(event.getExecuteDate(), (int) Math.round((double) getShiftInDays(event.getPeriod()) / 2))); - } -} diff --git a/src/main/java/ru/ulstu/timeline/service/EventService.java b/src/main/java/ru/ulstu/timeline/service/EventService.java deleted file mode 100644 index c7639c2..0000000 --- a/src/main/java/ru/ulstu/timeline/service/EventService.java +++ /dev/null @@ -1,180 +0,0 @@ -package ru.ulstu.timeline.service; - -import org.apache.commons.lang3.time.DateUtils; -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.core.model.EventSource; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.grant.model.Grant; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.project.model.Project; -import ru.ulstu.students.model.Task; -import ru.ulstu.timeline.model.Event; -import ru.ulstu.timeline.model.EventDto; -import ru.ulstu.timeline.model.Timeline; -import ru.ulstu.timeline.repository.EventRepository; -import ru.ulstu.user.model.UserDto; -import ru.ulstu.user.service.UserService; - -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.stream.Collectors; - -import static ru.ulstu.core.util.StreamApiUtils.convert; - -@Service -public class EventService { - - private final EventRepository eventRepository; - private final TimelineService timelineService; - private final UserService userService; - - public EventService(EventRepository eventRepository, - @Lazy TimelineService timelineService, - UserService userService) { - this.eventRepository = eventRepository; - this.timelineService = timelineService; - this.userService = userService; - } - - public List findAllDto() { - return convert(findAll(), EventDto::new); - } - - public List findAll() { - return eventRepository.findAll(); - } - - @Transactional - public Integer create(EventDto eventDto) { - return eventRepository.save(copyFromDto(new Event(), eventDto)).getId(); - } - - private Event copyFromDto(Event event, EventDto eventDto) { - event.setExecuteDate(eventDto.getExecuteDate()); - event.setCreateDate(eventDto.getId() == null ? new Date() : eventDto.getCreateDate()); - event.setDescription(eventDto.getDescription()); - event.setRecipients(userService.findByIds(convert(eventDto.getRecipients(), UserDto::getId))); - event.setTitle(eventDto.getTitle()); - event.setPeriod(eventDto.getPeriod()); - event.setStatus(eventDto.getStatus()); - event.setUpdateDate(new Date()); - return event; - } - - @Transactional - public Integer update(EventDto eventDto) { - Event event = eventRepository.getOne(eventDto.getId()); - return eventRepository.save(copyFromDto(event, eventDto)).getId(); - } - - @Transactional - public Event save(Event event) { - return eventRepository.save(event); - } - - @Transactional - public void delete(Integer eventId) { - Event event = eventRepository.getOne(eventId); - event.setParents(null); - eventRepository.delete(event); - } - - public List findByIds(List ids) { - return eventRepository.findAllById(ids); - } - - public void createBasedOn(Event event, Date executeDate) { - //backup event id - Integer parentEventId = event.getId(); - - event.setId(null); - event.setStatus(Event.EventStatus.POSSIBLE); - event.setExecuteDate(executeDate); - event.setCreateDate(new Date()); - event.setUpdateDate(new Date()); - event = eventRepository.save(event); - - //set child to parent - Event parentEvent = eventRepository.getOne(parentEventId); - parentEvent.setChild(event); - eventRepository.save(parentEvent); - } - - public void createFromPaper(Paper newPaper) { - createFromObject(newPaper, Collections.emptyList(), false, "статьи"); - } - - public void createFromObject(EventSource eventSource, List events, Boolean addCurrentUser, String suffix) { - List timelines = timelineService.findAll(); - Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0); - - timeline.getEvents().removeAll(events); - for (Deadline deadline : eventSource.getDeadlines() - .stream() - .filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date())) - .collect(Collectors.toList())) { - Event newEvent = new Event(); - newEvent.setTitle("Дедлайн " + suffix); - newEvent.setStatus(Event.EventStatus.NEW); - newEvent.setExecuteDate(deadline.getDate()); - newEvent.setCreateDate(new Date()); - newEvent.setUpdateDate(new Date()); - newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' " + suffix + " '" - + eventSource.getTitle() + "'"); - if (addCurrentUser) { - newEvent.getRecipients().add(userService.getCurrentUser()); - } - newEvent.setRecipients(eventSource.getRecipients()); - eventSource.addObjectToEvent(newEvent); - timeline.getEvents().add(eventRepository.save(newEvent)); - } - timelineService.save(timeline); - } - - public void updatePaperDeadlines(Paper paper) { - List foundEvents = eventRepository.findAllByPaper(paper); - eventRepository.deleteAll(foundEvents); - createFromObject(paper, foundEvents, false, "статьи"); - } - - public List findByCurrentDate() { - return eventRepository.findByCurrentDate(); - } - - private List findAllFuture() { - return eventRepository.findAllFuture(); - } - - public List findAllFutureDto() { - return convert(findAllFuture(), EventDto::new); - } - - public void updateConferenceDeadlines(Conference conference) { - eventRepository.deleteAll(eventRepository.findAllByConference(conference)); - createFromObject(conference, Collections.emptyList(), false, "конференции"); - } - - public void updateGrantDeadlines(Grant grant) { - eventRepository.deleteAll(eventRepository.findAllByGrant(grant)); - createFromObject(grant, Collections.emptyList(), false, "гранта"); - } - - public void updateProjectDeadlines(Project project) { - eventRepository.deleteAll(eventRepository.findAllByProject(project)); - createFromObject(project, Collections.emptyList(), false, "проекта"); - } - - public void removeConferencesEvent(Conference conference) { - List eventList = eventRepository.findAllByConference(conference); - eventList.forEach(event -> eventRepository.deleteById(event.getId())); - } - - public void updateTaskDeadlines(Task task) { - eventRepository.deleteAll(eventRepository.findAllByTask(task)); - createFromObject(task, Collections.emptyList(), true, "задачи"); - } -} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/timeline/service/TimelineService.java b/src/main/java/ru/ulstu/timeline/service/TimelineService.java deleted file mode 100644 index dd5c384..0000000 --- a/src/main/java/ru/ulstu/timeline/service/TimelineService.java +++ /dev/null @@ -1,60 +0,0 @@ -package ru.ulstu.timeline.service; - -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import ru.ulstu.timeline.model.EventDto; -import ru.ulstu.timeline.model.Timeline; -import ru.ulstu.timeline.model.TimelineDto; -import ru.ulstu.timeline.repository.TimelineRepository; - -import java.util.List; - -import static ru.ulstu.core.util.StreamApiUtils.convert; - -@Service -public class TimelineService { - - private final TimelineRepository timelineRepository; - private final EventService eventService; - - public TimelineService(TimelineRepository timelineRepository, - EventService eventService) { - this.timelineRepository = timelineRepository; - this.eventService = eventService; - } - - public List findAllDto() { - return convert(timelineRepository.findAll(), TimelineDto::new); - } - - public List findAll() { - return timelineRepository.findAll(); - } - - @Transactional - public int create(TimelineDto timelineDto) { - return timelineRepository.save(copyFromDto(new Timeline(), timelineDto)).getId(); - } - - @Transactional - public Timeline save(Timeline timeline) { - return timelineRepository.save(timeline); - } - - private Timeline copyFromDto(Timeline timeline, TimelineDto timelineDto) { - timeline.setEvents(eventService.findByIds(convert(timelineDto.getEvents(), EventDto::getId))); - return timeline; - } - - @Transactional - public Integer update(TimelineDto timelineDto) { - Timeline timeline = timelineRepository.getOne(timelineDto.getId()); - return timelineRepository.save(copyFromDto(timeline, timelineDto)).getId(); - } - - @Transactional - public void delete(Integer timelineId) { - Timeline timeline = timelineRepository.getOne(timelineId); - timelineRepository.delete(timeline); - } -} diff --git a/src/main/java/ru/ulstu/user/model/UserInfoNow.java b/src/main/java/ru/ulstu/user/model/UserInfoNow.java index 7d69c56..9f55f0f 100644 --- a/src/main/java/ru/ulstu/user/model/UserInfoNow.java +++ b/src/main/java/ru/ulstu/user/model/UserInfoNow.java @@ -1,7 +1,7 @@ package ru.ulstu.user.model; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.utils.timetable.model.Lesson; +import ru.ulstu.activity.boundary.timetable.model.Lesson; +import ru.ulstu.activity.conference.model.Conference; public class UserInfoNow { private Lesson lesson; diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index 0f69c8e..941c4ea 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -15,15 +15,18 @@ 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.activity.boundary.timetable.TimetableService; +import ru.ulstu.activity.boundary.timetable.errors.TimetableClientException; +import ru.ulstu.activity.boundary.timetable.model.Lesson; +import ru.ulstu.activity.common.model.AbstractActivity; +import ru.ulstu.activity.conference.service.ConferenceService; +import ru.ulstu.activity.ping.model.Ping; +import ru.ulstu.activity.ping.service.PingService; 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.UserActivity; import ru.ulstu.core.model.response.PageableItems; -import ru.ulstu.ping.model.Ping; -import ru.ulstu.ping.service.PingService; import ru.ulstu.user.error.UserActivationError; import ru.ulstu.user.error.UserBlockedException; import ru.ulstu.user.error.UserEmailExistsException; @@ -46,9 +49,6 @@ 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.errors.TimetableClientException; -import ru.ulstu.utils.timetable.model.Lesson; import javax.mail.MessagingException; import java.text.ParseException; @@ -411,9 +411,9 @@ public class UserService implements UserDetailsService { Map activitiesPings = new HashMap<>(); for (Ping ping : pingService.getPings(activityName)) { - UserActivity activity = ping.getActivity(); + AbstractActivity activity = ping.getActivity(); - if (user != null && !activity.getActivityUsers().contains(user)) { + if (user != null && !activity.getActivityMembers().contains(user)) { continue; } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 1949a5b..a74a19f 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -27,7 +27,7 @@ spring.datasource.url=jdbc:postgresql://localhost:5432/ng-tracker spring.datasource.username=postgres spring.datasource.password=postgres spring.jpa.hibernate.ddl-auto=validate -spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false +spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false # Liquibase Settings spring.liquibase.change-log=classpath:db/changelog-master.xml spring.liquibase.drop-first=false diff --git a/src/main/resources/mail_templates/grantAuthorsChangeNotification.html b/src/main/resources/mail_templates/grantAuthorsChangeNotification.html index 2bae4fe..15cdf59 100644 --- a/src/main/resources/mail_templates/grantAuthorsChangeNotification.html +++ b/src/main/resources/mail_templates/grantAuthorsChangeNotification.html @@ -13,7 +13,7 @@ Состав рабочей группы гранта "Title" сменился с " oldAuthors" - на " newAuthors". + на " newAuthors".

Regards, diff --git a/src/main/resources/mail_templates/taskCreateNotification.html b/src/main/resources/mail_templates/taskCreateNotification.html new file mode 100644 index 0000000..55ba526 --- /dev/null +++ b/src/main/resources/mail_templates/taskCreateNotification.html @@ -0,0 +1,23 @@ + + + + Уведомление о создании задачи + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Вам нужно поработать над задачей "Title". +

+ +

+ Regards, +
+ NG-tracker. +

+ + diff --git a/src/main/resources/public/js/core.js b/src/main/resources/public/js/core.js index 7f54023..d575d0a 100644 --- a/src/main/resources/public/js/core.js +++ b/src/main/resources/public/js/core.js @@ -191,7 +191,7 @@ function fillSelect(selectElement, values) { $(selectElement).html(""); $.each(values, function (key, value) { $(selectElement).append( - "" + "" ); }); } diff --git a/src/main/resources/public/js/file-loader.js b/src/main/resources/public/js/file-loader.js index 1ba467b..2e1ed9d 100644 --- a/src/main/resources/public/js/file-loader.js +++ b/src/main/resources/public/js/file-loader.js @@ -41,7 +41,7 @@ function FileLoader(args) { .addClass("form-control"); div.append(fileLabel); var fileInput = $("") - .attr("type", "file") + .attr("type", "ru.ulstu.activity.file") .attr("multiple", '') .hide(); fileInput.change(function () { @@ -49,7 +49,7 @@ function FileLoader(args) { if (isEmpty(files)) { return; } - fileLabel.val(files[0].name); + fileLabel.val(ru.ulstu.activity.name); }); div.append(fileInput); @@ -106,7 +106,7 @@ function FileLoader(args) { progressDiv.append(progressBar); function getFileExt(file) { - return file.name.slice((Math.max(0, file.name.lastIndexOf(".")) || Infinity) + 1); + return ru.ulstu.activity.name.slice((Math.max(0, ru.ulstu.activity.name.lastIndexOf(".")) || Infinity) + 1); } function upload(file) { @@ -128,7 +128,7 @@ function FileLoader(args) { }; xhr.open("POST", url, true); var formData = new FormData(); - formData.append("file", file); + formData.append("ru.ulstu.activity.file", file); xhr.send(formData); } } \ No newline at end of file diff --git a/src/main/resources/public/js/tasks.js b/src/main/resources/public/js/tasks.js index ebff7e2..282f462 100644 --- a/src/main/resources/public/js/tasks.js +++ b/src/main/resources/public/js/tasks.js @@ -24,7 +24,7 @@ $(document).ready(function () { if (tagNumber > 0) { tagNumber = $("#tags .tag").last() .children('input') - .attr("name") + .attr("ru.ulstu.activity.name") .split(']')[0] .split('[')[1]; tagNumber++; @@ -48,7 +48,7 @@ $(document).ready(function () { var idInput = $("") .attr("type", "hidden") .attr("id", "tags" + tagNumber + ".id") - .attr("name", "tags[" + tagNumber + "].id") + .attr("ru.ulstu.activity.name", "tags[" + tagNumber + "].id") .attr("value", ''); // контейнер текста var conDiv = $("
") @@ -57,7 +57,7 @@ $(document).ready(function () { var nameInput = $("") .attr("type", "text") .attr("id", "tags" + tagNumber + ".tagName") - .attr("name", "tags[" + tagNumber + "].tagName") + .attr("ru.ulstu.activity.name", "tags[" + tagNumber + "].tagName") .attr("value", tagName) .attr("readonly", "true") .attr("size", tagName.length); diff --git a/src/main/resources/static/core-components/app-index.vue b/src/main/resources/static/core-components/app-index.vue new file mode 100644 index 0000000..eb7e517 --- /dev/null +++ b/src/main/resources/static/core-components/app-index.vue @@ -0,0 +1,154 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/core-components/app-messages-item.vue b/src/main/resources/static/core-components/app-messages-item.vue new file mode 100644 index 0000000..8d7f49c --- /dev/null +++ b/src/main/resources/static/core-components/app-messages-item.vue @@ -0,0 +1,42 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/core-components/app-messages.vue b/src/main/resources/static/core-components/app-messages.vue new file mode 100644 index 0000000..261b464 --- /dev/null +++ b/src/main/resources/static/core-components/app-messages.vue @@ -0,0 +1,26 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/core-components/app.vue b/src/main/resources/static/core-components/app.vue new file mode 100644 index 0000000..5193da1 --- /dev/null +++ b/src/main/resources/static/core-components/app.vue @@ -0,0 +1,90 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/core-components/page-not-found.vue b/src/main/resources/static/core-components/page-not-found.vue new file mode 100644 index 0000000..c298069 --- /dev/null +++ b/src/main/resources/static/core-components/page-not-found.vue @@ -0,0 +1,10 @@ + \ No newline at end of file diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html new file mode 100644 index 0000000..c0223d0 --- /dev/null +++ b/src/main/resources/static/index.html @@ -0,0 +1,38 @@ + + + + + NG-Tracker + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/js/app-axios.js b/src/main/resources/static/js/app-axios.js new file mode 100644 index 0000000..88abb81 --- /dev/null +++ b/src/main/resources/static/js/app-axios.js @@ -0,0 +1,77 @@ +/* global axios */ + +(function umd(root, factory) { + if (typeof module === 'object' && typeof exports === 'object') + module.exports = factory(); + else if (typeof define === 'function' && define.amd) + define([], factory); + else + root.axiosEx = factory(); +})(this, function factory() { + 'use strict'; + + var axiosConfig = { + headers: { + 'Content-Type': 'application/json;charset=UTF-8', + "Access-Control-Allow-Origin": "*" + } + }; + + + function errorHandler(result, callback, errorCallback) { + if (result.data.error) { + if (errorCallback) { + errorCallback(); + } + throw result.data.error; + } + if (callback) { + callback(result.data.data); + } + } + + function axiosGet(url, resolv, reject) { + axios.get(url) + .then(function (result) { + errorHandler(result, resolv, reject); + }) + .catch(function (error) { + setTimeout(function () { + throw Error(error); + } + ); + }); + } + + function axiosPost(url, data, resolv, reject) { + axios.post(url, JSON.stringify(data), axiosConfig) + .then(function (result) { + errorHandler(result, resolv, reject); + }) + .catch(function (error) { + setTimeout(function () { + throw Error(error); + } + ); + }); + } + + function axiosPut(url, data, resolv, reject) { + axios.put(url, JSON.stringify(data), axiosConfig) + .then(function (result) { + errorHandler(result, resolv, reject); + }) + .catch(function (error) { + setTimeout(function () { + throw Error(error); + } + ); + }); + } + + return { + get: axiosGet, + post: axiosPost, + put: axiosPut + }; +}); \ No newline at end of file diff --git a/src/main/resources/static/js/app-config.js b/src/main/resources/static/js/app-config.js new file mode 100644 index 0000000..4bc55cd --- /dev/null +++ b/src/main/resources/static/js/app-config.js @@ -0,0 +1,41 @@ +(function umd(root, factory) { + if (typeof module === 'object' && typeof exports === 'object') + module.exports = factory(); + else if (typeof define === 'function' && define.amd) + define([], factory); + else + root.appConfig = factory(); +})(this, function factory() { + 'use strict'; + + var contextPath = ""; + var apiVersion = "/api/1.0"; + var basePath = contextPath + apiVersion; + + var appVersion = "@@version"; + var resourcesTimestamp = "?v=@@timestamp"; + + var getOwl = basePath + "/get-owl"; + var getTables = basePath + "/get-tables"; + var makeIntegration = basePath + "/make-integration"; + var paperList = basePath + "/papers/list"; + var paperDashboard = basePath + "/papers/dashboard"; + var paper = basePath + "/papers"; + var allPaperAuthors = basePath + "/papers/allAuthors"; + var allPaperTypes = basePath + "/papers/allTypes"; + var allPaperStatuses = basePath + "/papers/allStatuses"; + + return { + version: appVersion, + timestamp: resourcesTimestamp, + owl: getOwl, + tables: getTables, + integration: makeIntegration, + paperList: paperList, + paperDashboard: paperDashboard, + paper: paper, + allPaperAuthors: allPaperAuthors, + allPaperTypes: allPaperTypes, + allPaperStatuses: allPaperStatuses + }; +}); \ No newline at end of file diff --git a/src/main/resources/static/js/app-vue-loader.js b/src/main/resources/static/js/app-vue-loader.js new file mode 100644 index 0000000..fc855e2 --- /dev/null +++ b/src/main/resources/static/js/app-vue-loader.js @@ -0,0 +1,18 @@ +/* global httpVueLoader, appConfig */ + +(function umd(root, factory) { + if (typeof module === 'object' && typeof exports === 'object') + module.exports = factory(); + else if (typeof define === 'function' && define.amd) + define([], factory); + else + root.httpVueLoaderEx = factory(); +})(this, function factory() { + 'use strict'; + + function httpVueLoaderEx(url, name) { + return httpVueLoader(url + appConfig.timestamp, name); + } + + return httpVueLoaderEx; +}); \ No newline at end of file diff --git a/src/main/resources/static/js/app.js b/src/main/resources/static/js/app.js new file mode 100644 index 0000000..c6f9c18 --- /dev/null +++ b/src/main/resources/static/js/app.js @@ -0,0 +1,77 @@ +/* global Vue, VueRouter, Vuex, VeeValidate, httpVueLoaderEx */ + +var router = new VueRouter({ + linkActiveClass: "active", + linkExactActiveClass: "", + mode: "history", + routes: [ + { + path: "/", component: httpVueLoaderEx("/core-components/app-index.vue", "NG-Tracker") + }, + { + path: "/papers/papers", component: httpVueLoaderEx("/papers/paper-list.vue", "PaperList") + }, + { + path: "/papers/paper", component: httpVueLoaderEx("/papers/paper.vue", "PaperEdit") + }, + { + path: "/papers/dashboard", component: httpVueLoaderEx("/papers/paper-dashboard.vue", "PaperDashboard") + }, + { + path: "/other/other", component: httpVueLoaderEx("/other/other.vue", "OtherMain") + }, + { + path: "/*", component: httpVueLoaderEx("/core-components/page-not-found.vue", "PageNotFound") + } + ] +}); + +var store = new Vuex.Store({ + state: { + messages: [] + }, + mutations: { + addMessage: function (state, message) { + state.messages.push({ + id: state.messages.length === 0 ? 0 : state.messages[state.messages.length - 1], + text: message.text, + type: message.type || "info" + }); + }, + removeMessage: function (state, messageId) { + if (messageId < 0 || messageId >= state.messages.length) { + return; + } + state.messages.splice(messageId, 1); + } + }, + actions: { + addInfoMessage: function (context, message) { + context.commit("addMessage", message); + }, + addSuccessMessage: function (context, message) { + context.commit("addMessage", {text: message, type: "success"}); + }, + addWarningMessage: function (context, message) { + context.commit("addMessage", {text: message, type: "warning"}); + }, + addDangerMessage: function (context, message) { + context.commit("addMessage", {text: message, type: "danger"}); + }, + removeMessage: function (context, messageId) { + context.commit("removeMessage", messageId); + } + } +}); + +Vue.use(VeeValidate, { + validity: true +}); +new Vue({ + el: "#ng-tracker-app", + router: router, + store: store, + components: { + "app": httpVueLoaderEx("/core-components/app.vue") + } +}); \ No newline at end of file diff --git a/src/main/resources/static/other/other.vue b/src/main/resources/static/other/other.vue new file mode 100644 index 0000000..f77b921 --- /dev/null +++ b/src/main/resources/static/other/other.vue @@ -0,0 +1,30 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/other/var1.vue b/src/main/resources/static/other/var1.vue new file mode 100644 index 0000000..40ebbdc --- /dev/null +++ b/src/main/resources/static/other/var1.vue @@ -0,0 +1,81 @@ + + + + + \ No newline at end of file diff --git a/src/main/resources/static/other/var2.vue b/src/main/resources/static/other/var2.vue new file mode 100644 index 0000000..e55840c --- /dev/null +++ b/src/main/resources/static/other/var2.vue @@ -0,0 +1,78 @@ + + + + + \ No newline at end of file diff --git a/src/main/resources/static/papers/paper-dashboard-item.vue b/src/main/resources/static/papers/paper-dashboard-item.vue new file mode 100644 index 0000000..6818c3b --- /dev/null +++ b/src/main/resources/static/papers/paper-dashboard-item.vue @@ -0,0 +1,46 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/papers/paper-dashboard.vue b/src/main/resources/static/papers/paper-dashboard.vue new file mode 100644 index 0000000..c520fb6 --- /dev/null +++ b/src/main/resources/static/papers/paper-dashboard.vue @@ -0,0 +1,34 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/papers/paper-item.vue b/src/main/resources/static/papers/paper-item.vue new file mode 100644 index 0000000..1821db5 --- /dev/null +++ b/src/main/resources/static/papers/paper-item.vue @@ -0,0 +1,47 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/papers/paper-list.vue b/src/main/resources/static/papers/paper-list.vue new file mode 100644 index 0000000..aafaf5d --- /dev/null +++ b/src/main/resources/static/papers/paper-list.vue @@ -0,0 +1,37 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/papers/paper-navigation.vue b/src/main/resources/static/papers/paper-navigation.vue new file mode 100644 index 0000000..1d28eb2 --- /dev/null +++ b/src/main/resources/static/papers/paper-navigation.vue @@ -0,0 +1,28 @@ + diff --git a/src/main/resources/static/papers/paper-status.vue b/src/main/resources/static/papers/paper-status.vue new file mode 100644 index 0000000..0386e05 --- /dev/null +++ b/src/main/resources/static/papers/paper-status.vue @@ -0,0 +1,35 @@ + + + \ No newline at end of file diff --git a/src/main/resources/static/papers/paper.vue b/src/main/resources/static/papers/paper.vue new file mode 100644 index 0000000..2e30178 --- /dev/null +++ b/src/main/resources/static/papers/paper.vue @@ -0,0 +1,211 @@ + + + \ No newline at end of file diff --git a/src/main/resources/templates/activate.html b/src/main/resources/templates/activate.html deleted file mode 100644 index d06cdc8..0000000 --- a/src/main/resources/templates/activate.html +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/admin/commits.html b/src/main/resources/templates/admin/commits.html deleted file mode 100644 index 2f3f58f..0000000 --- a/src/main/resources/templates/admin/commits.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - -
-
-
-
- -
-
-
-
- - - - - \ No newline at end of file diff --git a/src/main/resources/templates/admin/userList.html b/src/main/resources/templates/admin/userList.html deleted file mode 100644 index 911601f..0000000 --- a/src/main/resources/templates/admin/userList.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - -
-
- -
-
- - - - - \ No newline at end of file diff --git a/src/main/resources/templates/admin/userSessions.html b/src/main/resources/templates/admin/userSessions.html deleted file mode 100644 index 12d3a61..0000000 --- a/src/main/resources/templates/admin/userSessions.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - -
-
- -
-
- - - - - \ No newline at end of file diff --git a/src/main/resources/templates/conferences/conference.html b/src/main/resources/templates/conferences/conference.html deleted file mode 100644 index 9a0e6b0..0000000 --- a/src/main/resources/templates/conferences/conference.html +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - -
-
-
-
-
-

Редактирование конференции

-
-
-
-
-
-
-
- -
-
- - -
- - -
- -

Incorrect title

-

- -
- - -
- -

Incorrect description

-

- -
- - -
- -

Incorrect description

-

- -
- -
- -
- - - - -
-
-
- -

Incorrect title

-

- - -
- -
-
- -
-
- -
-
-
- -
- -
- -
-
-
-
-

Incorrect date

-

- -
- -
-
- - - - - -
-
-
- -
- - - -
- - -
- - - -
-
- -
-
-
- - - Отмена - -
-
-
-
-
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/conferences/conferences.html b/src/main/resources/templates/conferences/conferences.html deleted file mode 100644 index 3204bf0..0000000 --- a/src/main/resources/templates/conferences/conferences.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - -
-
- -
-
-
-
-

Конференции

-
-
-
-
-
-

-
-
-
- -
- -
-
-
-
Фильтр:
- - -
-
-
-
-
- -
- - -
- - - diff --git a/src/main/resources/templates/conferences/dashboard.html b/src/main/resources/templates/conferences/dashboard.html deleted file mode 100644 index 5e3e97f..0000000 --- a/src/main/resources/templates/conferences/dashboard.html +++ /dev/null @@ -1,149 +0,0 @@ - - - - - - - -
-
-
-
-
-

Актуальные конференции

-
-
-
-
-
- -
- -
-
- - - - - - - - - - - - - - - - - - - - -
-
- -
- - \ No newline at end of file diff --git a/src/main/resources/templates/conferences/fragments/confDashboardFragment.html b/src/main/resources/templates/conferences/fragments/confDashboardFragment.html deleted file mode 100644 index 5aabef2..0000000 --- a/src/main/resources/templates/conferences/fragments/confDashboardFragment.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - -
-
-
-

-

- - title - -
-
-
- - - - \ No newline at end of file diff --git a/src/main/resources/templates/conferences/fragments/confLineFragment.html b/src/main/resources/templates/conferences/fragments/confLineFragment.html deleted file mode 100644 index 21b4191..0000000 --- a/src/main/resources/templates/conferences/fragments/confLineFragment.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - -
-
- - - - - - -
-
- - - - \ No newline at end of file diff --git a/src/main/resources/templates/conferences/fragments/confNavigationFragment.html b/src/main/resources/templates/conferences/fragments/confNavigationFragment.html deleted file mode 100644 index 7bf9d27..0000000 --- a/src/main/resources/templates/conferences/fragments/confNavigationFragment.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html deleted file mode 100644 index daf359a..0000000 --- a/src/main/resources/templates/default.html +++ /dev/null @@ -1,165 +0,0 @@ - - - - - - - - - - NG-Tracker - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
-
- -
-
-
-
- - - - - - - - - - - - - - - diff --git a/src/main/resources/templates/error/403.html b/src/main/resources/templates/error/403.html deleted file mode 100644 index a80b444..0000000 --- a/src/main/resources/templates/error/403.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - -
-
-
-
-
-

Доступ запрещен

-

Вернуться на главную

-
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/error/404.html b/src/main/resources/templates/error/404.html deleted file mode 100644 index 8f1d80b..0000000 --- a/src/main/resources/templates/error/404.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - -
-
-
-
-
-

Страница не найдена

-

Вернуться на главную

-
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/error/500.html b/src/main/resources/templates/error/500.html deleted file mode 100644 index f89b83a..0000000 --- a/src/main/resources/templates/error/500.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - -
-
-
-
-
-

Ошибка сервера

-

Вернуться на главную

-
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/fragments/noRecordsFragment.html b/src/main/resources/templates/fragments/noRecordsFragment.html deleted file mode 100644 index 38970f0..0000000 --- a/src/main/resources/templates/fragments/noRecordsFragment.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -
- - - \ No newline at end of file diff --git a/src/main/resources/templates/grants/dashboard.html b/src/main/resources/templates/grants/dashboard.html deleted file mode 100644 index 4ce7b44..0000000 --- a/src/main/resources/templates/grants/dashboard.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - -
-
-
-
-

Гранты

-
-
-
- -
- -
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/grants/fragments/grantDashboardFragment.html b/src/main/resources/templates/grants/fragments/grantDashboardFragment.html deleted file mode 100644 index 09e7e89..0000000 --- a/src/main/resources/templates/grants/fragments/grantDashboardFragment.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
-
- -
-
- - title - -

status

- - - -
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/grants/fragments/grantLineFragment.html b/src/main/resources/templates/grants/fragments/grantLineFragment.html deleted file mode 100644 index 86ae1cf..0000000 --- a/src/main/resources/templates/grants/fragments/grantLineFragment.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - -
-
- - - - - - - - - - - - - -
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/grants/fragments/grantNavigationFragment.html b/src/main/resources/templates/grants/fragments/grantNavigationFragment.html deleted file mode 100644 index 7545077..0000000 --- a/src/main/resources/templates/grants/fragments/grantNavigationFragment.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/grants/fragments/grantStatusFragment.html b/src/main/resources/templates/grants/fragments/grantStatusFragment.html deleted file mode 100644 index bf866d2..0000000 --- a/src/main/resources/templates/grants/fragments/grantStatusFragment.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - -
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
- - \ No newline at end of file diff --git a/src/main/resources/templates/grants/grant.html b/src/main/resources/templates/grants/grant.html deleted file mode 100644 index ad19553..0000000 --- a/src/main/resources/templates/grants/grant.html +++ /dev/null @@ -1,344 +0,0 @@ - - - - - - - - -
-
-
-
-
-

Редактирование гранта

-
-
-
-
-
-
-
-
-
- -
- - -

Incorrect title

-

-
-
- - -
-
- - -
-
- - -
- -
- -
-
- -
-
- -
-
-

Incorrect title

-
-
- -
-
- -
-
-
-
-
-
-
-
- -
-
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
-
-
- -
-
-
- - -
-
- -
-
-
- - -

Choose leader

-

-
-
- - -
-
- -
-
- -
- - -
-
-
-
-
-
-
-
-
- -
- -
-
-
-
-
- - -
-
-
- -
-
-
-
- - - -
- - diff --git a/src/main/resources/templates/grants/grants.html b/src/main/resources/templates/grants/grants.html deleted file mode 100644 index bc31ccf..0000000 --- a/src/main/resources/templates/grants/grants.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - -
-
- -
-
-
-
-

Гранты

-
-
-
-
-
- -
- -
-
-
-
-
-
-
- -
- - -
- - diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html deleted file mode 100644 index 63dd5b4..0000000 --- a/src/main/resources/templates/index.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - -
- -
-
-
-
- -
-
- -
-
- -
-
-

Статьи

-

-
-
-
- -
-
- -
-
- -
-
-

Гранты

-

-
-
-
- -
-
- -
-
- -
-
-

Проекты

-

-
-
-
- -
-
- -
-
- -
-
-

Конференции

-

-
-
-
- -
-
- -
-
- -
-
-

Команда

-

-
-
-
- -
-
- -
-
- -
-
-

Работа со студентами

-

-
-
-
- -
-
- -
-
- -
-
-

Задачи

-

-
-
-
- -
-
- -
-
- -
-
-

Карьера

-

-
-
-
- -
-
- -
-
- -
-
-

Прочее

-

-
-
-
-
-
-
- - - diff --git a/src/main/resources/templates/load.html b/src/main/resources/templates/load.html deleted file mode 100644 index dbd991a..0000000 --- a/src/main/resources/templates/load.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - -
-
-
-
-
-

Статьи

-
- -
-
-
-
-
- - - - -
- - \ No newline at end of file diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html deleted file mode 100644 index 48e325e..0000000 --- a/src/main/resources/templates/login.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - -
-
-
-
-
-
-
-
- -
-
- -
- - -
-
-
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/papers/dashboard.html b/src/main/resources/templates/papers/dashboard.html deleted file mode 100644 index d02f1be..0000000 --- a/src/main/resources/templates/papers/dashboard.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - -
-
-
-
-

Статьи

-
-
-
- -
- -
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/papers/fragments/paperDashboardFragment.html b/src/main/resources/templates/papers/fragments/paperDashboardFragment.html deleted file mode 100644 index 48b6bae..0000000 --- a/src/main/resources/templates/papers/fragments/paperDashboardFragment.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - -
-
-
- -
-
-

-

- - title - -

authors

-
-
-
- - - - \ No newline at end of file diff --git a/src/main/resources/templates/papers/fragments/paperFilesListFragment.html b/src/main/resources/templates/papers/fragments/paperFilesListFragment.html deleted file mode 100644 index b4de456..0000000 --- a/src/main/resources/templates/papers/fragments/paperFilesListFragment.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - -
- - - - -
- - - - - -
- - - -
-
- - -
-
-
-
-
- - - - - \ No newline at end of file diff --git a/src/main/resources/templates/papers/fragments/paperLineFragment.html b/src/main/resources/templates/papers/fragments/paperLineFragment.html deleted file mode 100644 index 8c843d8..0000000 --- a/src/main/resources/templates/papers/fragments/paperLineFragment.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - -
- -
- - - - \ No newline at end of file diff --git a/src/main/resources/templates/papers/fragments/paperNavigationFragment.html b/src/main/resources/templates/papers/fragments/paperNavigationFragment.html deleted file mode 100644 index 23c8260..0000000 --- a/src/main/resources/templates/papers/fragments/paperNavigationFragment.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/papers/fragments/paperStatusFragment.html b/src/main/resources/templates/papers/fragments/paperStatusFragment.html deleted file mode 100644 index 2505bdf..0000000 --- a/src/main/resources/templates/papers/fragments/paperStatusFragment.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - -
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
- - \ No newline at end of file diff --git a/src/main/resources/templates/papers/paper.html b/src/main/resources/templates/papers/paper.html deleted file mode 100644 index b1f195a..0000000 --- a/src/main/resources/templates/papers/paper.html +++ /dev/null @@ -1,577 +0,0 @@ - - - - - - - - - - - -
- -
-
-
-
-

Редактирование статьи

-
-
-
-
-
-
-
-
-
- - -
-
-
-
-
-
-
Дата создания:
-
-
- - text - -
-
-
-
-
-
-
Дата изменения:
-
-
- - text - -
-
-
-
- -
-
- -
-
-
- - - Отмена - -
- -
-
- -
-
-
-
- - - -
- - - - diff --git a/src/main/resources/templates/papers/papers.html b/src/main/resources/templates/papers/papers.html deleted file mode 100644 index f4eb06b..0000000 --- a/src/main/resources/templates/papers/papers.html +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - -
-
- -
-
-
-
-

Статьи

-
-
-
- -
-
-

-
-
- -
- -
-
-
-
Фильтр:
- - -
-
-
- -
-
- -
- - -
- - - diff --git a/src/main/resources/templates/projects/dashboard.html b/src/main/resources/templates/projects/dashboard.html deleted file mode 100644 index 0eafb4a..0000000 --- a/src/main/resources/templates/projects/dashboard.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - -
-
-
-
-

Проекты

-
-
-
- -
- -
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/projects/fragments/projectDashboardFragment.html b/src/main/resources/templates/projects/fragments/projectDashboardFragment.html deleted file mode 100644 index 027dce7..0000000 --- a/src/main/resources/templates/projects/fragments/projectDashboardFragment.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - -
-
-
- -
-
- title -
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/projects/fragments/projectLineFragment.html b/src/main/resources/templates/projects/fragments/projectLineFragment.html deleted file mode 100644 index 43bdfb9..0000000 --- a/src/main/resources/templates/projects/fragments/projectLineFragment.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - -
-
- - - - - - - - - -
-
- - \ 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 deleted file mode 100644 index 75dfff6..0000000 --- a/src/main/resources/templates/projects/fragments/projectNavigationFragment.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/projects/fragments/projectStatusFragment.html b/src/main/resources/templates/projects/fragments/projectStatusFragment.html deleted file mode 100644 index bf0d3f6..0000000 --- a/src/main/resources/templates/projects/fragments/projectStatusFragment.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - -
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
- - \ No newline at end of file diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html deleted file mode 100644 index b8999a5..0000000 --- a/src/main/resources/templates/projects/project.html +++ /dev/null @@ -1,289 +0,0 @@ - - - - - - - -
- -
-
-
-
-

Редактирование проекта

-
-
-
-
-
-
-
-
- -
- - -

Incorrect title

-

-
- -
- - -
- -
- - -
- -
- -
-
- -
-
-
- -
- - -

Incorrect repository link

-

-
- -
- -
- -
- -
-
- -
-
- - -
-
-
- -
-
- -
-
-

Incorrect title

-
-
- -
- -
- - -
- -
- -
- -
- -
-
-
- -
-
- -
-
-
- - -
-
-
- -
-
-
-
- - -
- - diff --git a/src/main/resources/templates/projects/projects.html b/src/main/resources/templates/projects/projects.html deleted file mode 100644 index de334f8..0000000 --- a/src/main/resources/templates/projects/projects.html +++ /dev/null @@ -1,36 +0,0 @@ - - - - - -
-
- -
-
-
-
-

Проекты

-
-
-
-
-
- -
- -
-
-
-
-
-
-
-
- - -
- - diff --git a/src/main/resources/templates/reset.html b/src/main/resources/templates/reset.html deleted file mode 100644 index c2dd78f..0000000 --- a/src/main/resources/templates/reset.html +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - -
-
-
-
- -
-
- -
- - -
-
- -
- - - - - \ No newline at end of file diff --git a/src/main/resources/templates/resetRequest.html b/src/main/resources/templates/resetRequest.html deleted file mode 100644 index d340151..0000000 --- a/src/main/resources/templates/resetRequest.html +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - -
-
- -
-
-
-
- -
-
- -
-
- -
-
- -
- - - - -
-
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/students/dashboard.html b/src/main/resources/templates/students/dashboard.html deleted file mode 100644 index 1f930cd..0000000 --- a/src/main/resources/templates/students/dashboard.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - -
-
-
-
-

Работа со студентами

-
-
-
-
- -
- - -
-
-
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/students/fragments/taskDashboardFragment.html b/src/main/resources/templates/students/fragments/taskDashboardFragment.html deleted file mode 100644 index 3779ef8..0000000 --- a/src/main/resources/templates/students/fragments/taskDashboardFragment.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - -
-
-
- - -
-
- title -

status

- - -
-
-
- - - - \ No newline at end of file diff --git a/src/main/resources/templates/students/fragments/taskLineFragment.html b/src/main/resources/templates/students/fragments/taskLineFragment.html deleted file mode 100644 index 210863d..0000000 --- a/src/main/resources/templates/students/fragments/taskLineFragment.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/students/fragments/taskNavigationFragment.html b/src/main/resources/templates/students/fragments/taskNavigationFragment.html deleted file mode 100644 index cf32140..0000000 --- a/src/main/resources/templates/students/fragments/taskNavigationFragment.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/templates/students/fragments/taskStatusFragment.html b/src/main/resources/templates/students/fragments/taskStatusFragment.html deleted file mode 100644 index d8ef4f4..0000000 --- a/src/main/resources/templates/students/fragments/taskStatusFragment.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - -
- -
-
- -
-
- -
-
- -
-
- -
- - \ No newline at end of file diff --git a/src/main/resources/templates/students/task.html b/src/main/resources/templates/students/task.html deleted file mode 100644 index 3642221..0000000 --- a/src/main/resources/templates/students/task.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - - - -
- -
- -
-
-
-

Редактирование задачи

-
-
-
-
-
-
-
-
-
- -
- - -

Incorrect title

-

-
- -
- - -
-
- - -
- -
- -
-
- -
- - -
-
- -
-
-
- -
- -
- -
-
- -
-
- - -
-
-

Incorrect title

-
-
- -
-
-
- - - Отмена - -
-
-
-
-
-
-
Дата создания:
-
-
- - text - -
-
-
-
-
-
-
Дата изменения:
-
-
- - text - -
-
-
-
-
- -
-
-
- -
-
- - \ No newline at end of file diff --git a/src/main/resources/templates/students/tasks.html b/src/main/resources/templates/students/tasks.html deleted file mode 100644 index 72c4194..0000000 --- a/src/main/resources/templates/students/tasks.html +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - -
-
- -
-
-
-
-

Работа со студентами

-
-
-
-
-
-
- -
- -
-
-
-
Сортировать:
- -
-
-
Фильтр:
- - -
-
-
-
-
- -
- - -
- - \ No newline at end of file diff --git a/src/main/resources/templates/timeline.html b/src/main/resources/templates/timeline.html deleted file mode 100644 index 0fdaddd..0000000 --- a/src/main/resources/templates/timeline.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - -
-
-
-
-
-

События

-
-
-
-
-
    - -
-
-
-
-
- - - - - -
- - - diff --git a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java deleted file mode 100644 index 56756a3..0000000 --- a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java +++ /dev/null @@ -1,278 +0,0 @@ -package ru.ulstu.conference.service; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.springframework.data.domain.Sort; -import org.springframework.test.context.junit4.SpringRunner; -import ru.ulstu.conference.model.Conference; -import ru.ulstu.conference.model.ConferenceDto; -import ru.ulstu.conference.model.ConferenceFilterDto; -import ru.ulstu.conference.model.ConferenceUser; -import ru.ulstu.conference.repository.ConferenceRepository; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.deadline.service.DeadlineService; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.paper.service.PaperService; -import ru.ulstu.ping.service.PingService; -import ru.ulstu.timeline.service.EventService; -import ru.ulstu.user.model.User; -import ru.ulstu.user.service.UserService; - -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.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -@RunWith(SpringRunner.class) -public class ConferenceServiceTest { - - @Mock - ConferenceRepository conferenceRepository; - - @Mock - DeadlineService deadlineService; - - @Mock - ConferenceUserService conferenceUserService; - - @Mock - PaperService paperService; - - @Mock - UserService userService; - - @Mock - EventService eventService; - - @Mock - ConferenceNotificationService conferenceNotificationService; - - @Mock - PingService pingService; - - @InjectMocks - ConferenceService conferenceService; - - private final static Integer ID = 1; - private final static Integer INDEX = 0; - private final static String NAME = "Name"; - private final static String DESCRIPTION = "Desc"; - private final static boolean TRUE = true; - private final static Integer YEAR = 2019; - private final static Sort SORT = new Sort(Sort.Direction.DESC, "beginDate"); - - private List conferences; - private List deadlines; - private List papers; - private List conferenceUsers; - - private Conference conferenceWithId; - - private Paper paperWithId; - private Paper paperWithoutId; - - private ConferenceDto conferenceDto; - private User user; - private Deadline deadline; - - @Before - public void setUp() throws Exception { - conferences = new ArrayList<>(); - conferenceWithId = new Conference(); - - conferenceWithId.setId(ID); - conferenceWithId.setTitle(NAME); - conferenceWithId.setDescription(DESCRIPTION); - - paperWithId = new Paper(); - paperWithId.setId(1); - paperWithId.setTitle(NAME); - - paperWithoutId = new Paper(); - paperWithoutId.setTitle(NAME); - - papers = new ArrayList<>(); - papers.add(paperWithId); - papers.add(paperWithoutId); - - deadlines = new ArrayList<>(); - deadline = new Deadline(new Date(), DESCRIPTION); - deadline.setId(ID); - deadlines.add(deadline); - - ConferenceUser conferenceUser = new ConferenceUser(); - conferenceUser.setDeposit(ConferenceUser.Deposit.ARTICLE); - conferenceUser.setParticipation(ConferenceUser.Participation.INTRAMURAL); - user = new User(); - user.setFirstName(NAME); - conferenceUser.setUser(user); - - conferenceUsers = new ArrayList<>(); - conferenceUsers.add(conferenceUser); - - conferences.add(conferenceWithId); - conferenceDto = new ConferenceDto(conferenceWithId); - } - - @Test - public void getExistConferenceById() { - when(conferenceRepository.getOne(ID)).thenReturn(conferenceWithId); - when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers); - when(userService.getCurrentUser()).thenReturn(user); - - ConferenceDto newConferenceDto = new ConferenceDto(conferenceWithId); - newConferenceDto.setNotSelectedPapers(papers); - newConferenceDto.setDisabledTakePart(!TRUE); - ConferenceDto result = conferenceService.getExistConferenceById(ID); - - assertEquals(newConferenceDto.getId(), result.getId()); - assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); - assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); - } - - @Test - public void getNewConference() { - when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers); - - ConferenceDto newConferenceDto = new ConferenceDto(); - newConferenceDto.setNotSelectedPapers(papers); - ConferenceDto result = conferenceService.getNewConference(); - - assertEquals(newConferenceDto.getId(), result.getId()); - assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); - assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); - } - - @Test - public void findAll() { - when(conferenceRepository.findAll(SORT)).thenReturn(conferences); - - assertEquals(Collections.singletonList(conferenceWithId), conferenceService.findAll()); - } - - @Test - public void create() throws IOException { - when(paperService.findPaperById(ID)).thenReturn(paperWithId); - when(paperService.create(new Paper())).thenReturn(paperWithoutId); - when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); - when(conferenceUserService.saveOrCreate(new ArrayList<>())).thenReturn(conferenceUsers); - when(conferenceRepository.save(new Conference())).thenReturn(conferenceWithId); - - conferenceDto.setPapers(papers); - conferenceDto.setDeadlines(deadlines); - conferenceDto.setUsers(conferenceUsers); - conferenceDto.getPaperIds().add(ID); - - Conference newConference = new Conference(); - newConference.setId(ID); - newConference.setTitle(NAME); - newConference.setDescription(DESCRIPTION); - newConference.setPapers(papers); - newConference.getPapers().add(paperWithId); - newConference.setDeadlines(deadlines); - newConference.setUsers(conferenceUsers); - - assertEquals(newConference, conferenceService.create(conferenceDto)); - } - - @Test - public void delete() { - when(conferenceRepository.existsById(ID)).thenReturn(true); - when(conferenceRepository.getOne(ID)).thenReturn(conferenceWithId); - assertTrue(conferenceService.delete(ID)); - } - - @Test - public void addDeadline() { - ConferenceDto newConferenceDto = new ConferenceDto(); - newConferenceDto.getDeadlines().add(new Deadline()); - conferenceDto.getDeadlines().clear(); - - assertEquals(newConferenceDto.getDeadlines().get(0), conferenceService.addDeadline(conferenceDto).getDeadlines().get(0)); - } - - @Test - public void removeDeadline() throws IOException { - ConferenceDto newConferenceDto = new ConferenceDto(); - newConferenceDto.getRemovedDeadlineIds().add(ID); - conferenceDto.getDeadlines().add(deadline); - ConferenceDto result = conferenceService.removeDeadline(conferenceDto, INDEX); - - assertEquals(newConferenceDto.getDeadlines(), result.getDeadlines()); - assertEquals(newConferenceDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds()); - } - - @Test - public void addPaper() { - when(userService.getCurrentUser()).thenReturn(user); - - ConferenceDto newConferenceDto = new ConferenceDto(); - newConferenceDto.getPapers().add(paperWithoutId); - conferenceDto.getPapers().clear(); - ConferenceDto result = conferenceService.addPaper(conferenceDto); - result.getPapers().get(INDEX).setTitle(NAME); // приходится вручную назначать название, т.е. название зависит от даты - - assertEquals(newConferenceDto.getPapers(), result.getPapers()); - } - - @Test - public void removePaper() throws IOException { - ConferenceDto newConferenceDto = new ConferenceDto(); - newConferenceDto.getNotSelectedPapers().add(paperWithId); - newConferenceDto.getPapers().add(paperWithoutId); - conferenceDto.getPapers().add(paperWithId); - conferenceDto.getPapers().add(paperWithoutId); - ConferenceDto result = conferenceService.removePaper(conferenceDto, INDEX); - - assertEquals(newConferenceDto.getPapers(), result.getPapers()); - assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); - } - - @Test - public void takePart() throws IOException { - when(userService.getCurrentUser()).thenReturn(user); - - ConferenceDto newConferenceDto = new ConferenceDto(); - newConferenceDto.setUsers(conferenceUsers); - newConferenceDto.setDisabledTakePart(TRUE); - conferenceDto.getPapers().clear(); - ConferenceDto result = conferenceService.takePart(conferenceDto); - - assertEquals(newConferenceDto.getUsers(), result.getUsers()); - assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); - } - - @Test - public void getAllUsers() { - List users = Collections.singletonList(user); - when(userService.findAll()).thenReturn(users); - assertEquals(users, conferenceService.getAllUsers()); - } - - @Test - public void filter() { - when(userService.findById(ID)).thenReturn(user); - when(conferenceRepository.findByUserAndYear(user, YEAR)).thenReturn(conferences); - - ConferenceFilterDto conferenceFilterDto = new ConferenceFilterDto(); - conferenceFilterDto.setFilterUserId(ID); - conferenceFilterDto.setYear(YEAR); - - assertEquals(Collections.singletonList(conferenceDto), conferenceService.filter(conferenceFilterDto)); - } - - @Test - public void isAttachedToConference() { - when(conferenceRepository.isPaperAttached(ID)).thenReturn(TRUE); - - assertTrue(conferenceService.isAttachedToConference(ID)); - } -} \ No newline at end of file diff --git a/src/test/java/ru/ulstu/grant/service/GrantServiceTest.java b/src/test/java/ru/ulstu/grant/service/GrantServiceTest.java deleted file mode 100644 index c8df288..0000000 --- a/src/test/java/ru/ulstu/grant/service/GrantServiceTest.java +++ /dev/null @@ -1,223 +0,0 @@ -package ru.ulstu.grant.service; - -import org.apache.commons.lang3.StringUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringRunner; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.deadline.service.DeadlineService; -import ru.ulstu.grant.model.Grant; -import ru.ulstu.grant.model.GrantDto; -import ru.ulstu.grant.repository.GrantRepository; -import ru.ulstu.paper.model.Paper; -import ru.ulstu.paper.model.PaperDto; -import ru.ulstu.paper.service.PaperService; -import ru.ulstu.timeline.service.EventService; -import ru.ulstu.user.model.User; -import ru.ulstu.user.service.UserService; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -@RunWith(SpringRunner.class) -public class GrantServiceTest { - - @Mock - GrantRepository grantRepository; - - @Mock - DeadlineService deadlineService; - - @Mock - PaperService paperService; - - @Mock - UserService userService; - - @Mock - EventService eventService; - - @Mock - GrantNotificationService grantNotificationService; - - @InjectMocks - GrantService grantService; - - private final static Integer ID = 1; - private final static Integer INDEX = 0; - private final static String TITLE = "Title"; - private final static String COMMENT = "Comment"; - private final static boolean TRUE = true; - private final static Integer YEAR = 2019; - private final static Integer MAX_DISPLAY_SIZE = 50; - - private List grants; - private List deadlines; - private List paperDtos; - private GrantDto grantDto; - private Deadline deadline; - private User leader; - - private Grant grantWithId; - - - @Before - public void setUp() throws Exception { - grants = new ArrayList<>(); - paperDtos = new ArrayList<>(); - grantWithId = new Grant(); - - deadlines = new ArrayList<>(); - deadline = new Deadline(new Date(), COMMENT); - deadline.setId(ID); - deadlines.add(deadline); - - leader = Mockito.mock(User.class); - - List papers = new ArrayList<>(); - Paper paperWithId = new Paper(); - paperWithId.setId(ID); - paperWithId.setTitle(TITLE); - papers.add(paperWithId); - PaperDto paperDto = new PaperDto(paperWithId); - paperDtos.add(paperDto); - - Set authors = new HashSet<>(); - User author = leader; - authors.add(author); - - grantWithId.setId(ID); - grantWithId.setTitle(TITLE); - grantWithId.setComment(COMMENT); - grantWithId.setDeadlines(deadlines); - grantWithId.setLeader(leader); - grantWithId.setPapers(papers); - grantWithId.setAuthors(authors); - - grants.add(grantWithId); - grantDto = new GrantDto(grantWithId); - } - - @Test - public void getExistGrantById() { - when(grantRepository.getOne(ID)).thenReturn(grantWithId); - - GrantDto newGrantDto = new GrantDto(grantWithId); - GrantDto result = grantService.getExistGrantById(ID); - - assertEquals(newGrantDto.getId(), result.getId()); - } - - @Test - public void findAll() { - when(grantRepository.findAll()).thenReturn(grants); - - assertEquals(Collections.singletonList(grantWithId), grantService.findAll()); - } - - @Test - public void create() throws IOException { - when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); - when(userService.getUserByLogin("admin")).thenReturn(leader); - when(grantRepository.save(new Grant())).thenReturn(grantWithId); - - Grant newGrant = new Grant(); - newGrant.setId(ID); - newGrant.setTitle(TITLE); - newGrant.setComment(COMMENT); - newGrant.setDeadlines(deadlines); - newGrant.setLeader(leader); - - assertEquals(newGrant, grantService.create(grantDto)); - } - - @Test - public void getGrantStatuses() { - assertEquals(Arrays.asList(Grant.GrantStatus.values()), grantService.getGrantStatuses()); - } - - @Test - public void getGrantPapers() { - when(paperService.findAllSelect(Collections.singletonList(ID))).thenReturn(paperDtos); - - assertEquals(paperDtos, grantService.getGrantPapers(Collections.singletonList(ID))); - } - - @Test - public void getAllUncompletedPapers() { - when(paperService.findAllNotCompleted()).thenReturn(paperDtos); - paperDtos.stream() - .forEach(paperDto -> { - paperDto.setTitle(StringUtils.abbreviate(paperDto.getTitle(), MAX_DISPLAY_SIZE)); - }); - - assertEquals(paperDtos, grantService.getAllUncompletedPapers()); - } - - @Test - public void delete() throws IOException { - when(grantRepository.getOne(ID)).thenReturn(grantWithId); - assertTrue(grantService.delete(grantWithId.getId())); - } - - @Test - public void removeDeadline() { - GrantDto newGrantDto = new GrantDto(); - newGrantDto.getRemovedDeadlineIds().add(ID); - grantDto.getDeadlines().add(deadline); - GrantDto result = grantService.removeDeadline(grantDto, INDEX); - - assertEquals(newGrantDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds()); - } - - @Test - public void findById() { - when(grantRepository.getOne(ID)).thenReturn(grantWithId); - Grant findGrant = grantService.findById(ID); - - assertEquals(grantWithId.getId(), findGrant.getId()); - } - - @Test - public void attachPaper() { - when(grantRepository.getOne(ID)).thenReturn(grantWithId); - when(paperService.findAllSelect(Collections.singletonList(ID))).thenReturn(paperDtos); - GrantDto newGrantDto = new GrantDto(grantWithId); - - if (!newGrantDto.getPaperIds().isEmpty()) { - newGrantDto.getPapers().clear(); - newGrantDto.setPapers(paperDtos); - } else { - newGrantDto.getPapers().clear(); - } - - assertEquals(newGrantDto.getPapers(), grantService.attachPaper(grantDto)); - } - - @Test - public void filterEmptyDeadlines() { - when(grantRepository.getOne(ID)).thenReturn(grantWithId); - GrantDto newGrantDto = new GrantDto(grantWithId); - - newGrantDto.setDeadlines(newGrantDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !StringUtils.isEmpty(dto.getDescription())) - .collect(Collectors.toList())); - - assertEquals(newGrantDto.getDeadlines(), grantService.filterEmptyDeadlines(grantDto)); - } -} \ No newline at end of file diff --git a/src/test/java/ru/ulstu/project/service/ProjectServiceTest.java b/src/test/java/ru/ulstu/project/service/ProjectServiceTest.java deleted file mode 100644 index f46971c..0000000 --- a/src/test/java/ru/ulstu/project/service/ProjectServiceTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package ru.ulstu.project.service; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.springframework.test.context.junit4.SpringRunner; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.deadline.service.DeadlineService; -import ru.ulstu.file.model.FileData; -import ru.ulstu.file.service.FileService; -import ru.ulstu.grant.model.GrantDto; -import ru.ulstu.grant.service.GrantService; -import ru.ulstu.project.model.Project; -import ru.ulstu.project.model.ProjectDto; -import ru.ulstu.project.repository.ProjectRepository; -import ru.ulstu.timeline.service.EventService; -import ru.ulstu.user.model.User; -import ru.ulstu.user.service.UserService; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -@RunWith(SpringRunner.class) -public class ProjectServiceTest { - - @Mock - ProjectRepository projectRepository; - - @Mock - DeadlineService deadlineService; - - @Mock - EventService eventService; - - @Mock - FileService fileService; - - @Mock - UserService userService; - - @Mock - GrantService grantService; - - @InjectMocks - ProjectService projectService; - - private final static String TITLE = "title"; - private final static String DESCR = "descr"; - private final static Integer ID = 1; - private final static Integer INDEX = 0; - private final static String NAME = "name"; - - private List projects; - private Project project; - private ProjectDto projectDto; - private Deadline deadline; - private List deadlines; - private FileData file; - private List files; - private User user; - - @Before - public void setUp() throws Exception { - projects = new ArrayList<>(); - project = new Project(); - - projects.add(project); - projectDto = new ProjectDto(project); - - deadlines = new ArrayList<>(); - deadline = new Deadline(new Date(), DESCR); - deadline.setId(ID); - deadlines.add(deadline); - - user = new User(); - user.setFirstName(NAME); - - List grants = new ArrayList<>(); - GrantDto grant = new GrantDto(); - grant.setId(ID); - grants.add(grant); - } - - @Test - public void findAll() { - when(projectRepository.findAll()).thenReturn(projects); - assertEquals(projects, projectService.findAll()); - } - - @Test - public void create() throws IOException { - when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); - when(projectRepository.save(new Project())).thenReturn(project); - eventService.createFromObject(new Project(), Collections.emptyList(), false, "проекта"); - - projectDto.setTitle(TITLE); - projectDto.setDeadlines(deadlines); - - project.setId(ID); - project.setTitle(TITLE); - project.setDescription(DESCR); - project.setDeadlines(deadlines); - project.setFiles(files); - - assertEquals(project.getId(), (projectService.create(projectDto)).getId()); - } - - @Test - public void delete() throws IOException { - when(projectRepository.existsById(ID)).thenReturn(true); - when(projectRepository.getOne(ID)).thenReturn(project); - - assertTrue(projectService.delete(ID)); - } - - @Test - public void getProjectExecutors() { - List executors = Collections.singletonList(user); - when(userService.findAll()).thenReturn(executors); - - assertEquals(executors, projectService.getProjectExecutors(projectDto)); - } - - @Test - public void findById() { - when(projectRepository.getOne(ID)).thenReturn(project); - assertEquals(project, projectService.findById(ID)); - } - - @Test - public void removeDeadline() throws IOException { - ProjectDto newProjectDto = new ProjectDto(); - newProjectDto.getRemovedDeadlineIds().add(INDEX); - projectDto.getDeadlines().add(deadline); - ProjectDto result = projectService.removeDeadline(projectDto, INDEX); - - assertEquals(newProjectDto.getDeadlines(), result.getDeadlines()); - assertEquals(newProjectDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds()); - } -} \ No newline at end of file diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java deleted file mode 100644 index 97b9990..0000000 --- a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java +++ /dev/null @@ -1,215 +0,0 @@ -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.springframework.data.domain.Sort; -import org.springframework.test.context.junit4.SpringRunner; -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.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -@RunWith(SpringRunner.class) -public class TaskServiceTest { - - @Mock - TaskRepository taskRepository; - - @Mock - SchedulerRepository schedulerRepository; - - @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 final static Date YEAR = DateUtils.clearTime(DateUtils.addYears(new Date(), 0)); - - private List tasks; - private List tags; - private Task task; - private Task taskForSchedule; - private TaskDto taskDto; - private Tag tag; - private Deadline deadline; - private List deadlines; - private Scheduler scheduler; - - - @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); - - task.setDeadlines(deadlines); - - tags = new ArrayList<>(); - tags.add(tag); - - tasks.add(task); - taskDto = new TaskDto(task); - - taskForSchedule = new Task(); - taskForSchedule.setTitle(TITLE); - taskForSchedule.setDescription(DESCR); - - scheduler = new Scheduler(); - scheduler.setDate(new Date()); - scheduler.setTask(taskForSchedule); - - - } - - @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.createFromObject(new Task(), Collections.emptyList(), true, "задачи"); - - 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 delete() throws IOException { - when(taskRepository.existsById(ID)).thenReturn(true); - when(taskRepository.getOne(ID)).thenReturn(task); - when(schedulerRepository.findOneByTask(task)).thenReturn(null); - - assertTrue(taskService.delete(ID)); - } - - @Test - public void generateYearTasks() { - 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.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); - - assertEquals(Arrays.asList(task), taskService.generateYearTasks()); - } - - @Test - public void checkRepeatingTags() { - when(tagService.getTags()).thenReturn(tags); - tasks.get(0).setTags(tags); - when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks); - - assertEquals(new HashSet(Arrays.asList(tag)), taskService.checkRepeatingTags(false)); - } - - @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