WIP: Resolve "Статистика по активностям" #232

Draft
arefiev1997 wants to merge 11 commits from 93-activites-analytics into dev
87 changed files with 2576 additions and 327 deletions
Showing only changes of commit 0bb9d5771f - Show all commits

View File

@ -127,5 +127,7 @@ dependencies {
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'
testCompile group: 'org.seleniumhq.selenium', name: 'selenium-support', version: '3.3.1'
testCompile group: 'com.google.guava', name: 'guava', version: '21.0'
}

View File

@ -18,6 +18,6 @@ fi
ssh $USERSERVER "cd /tmp && rm -rf $ARTIFACT_NAME*.jar && echo `date` 'killed' >> log_$ARTIFACT_NAME"
scp build/libs/$ARTIFACT_NAME-0.1.0-SNAPSHOT.jar $USERSERVER:/tmp/$ARTIFACT_NAME-0.1.0-SNAPSHOT.jar
ssh $USERSERVER -f "cd /tmp/ && /opt/jdk1.8.0_192/bin/java -jar $ARTIFACT_NAME-0.1.0-SNAPSHOT.jar -Xms 512m -Xmx 1024m --server.port=8443 --server.http.port=8080 --ng-tracker.base-url=http://193.110.3.124:8080 --ng-tracker.dev-mode=false >> /home/user/logfile_$ARTIFACT_NAME" &
ssh $USERSERVER -f "cd /tmp/ && /opt/jdk1.8.0_192/bin/java -jar $ARTIFACT_NAME-0.1.0-SNAPSHOT.jar -Xms 512m -Xmx 1024m --server.port=8443 --server.http.port=8080 --ng-tracker.base-url=http://193.110.3.124:8080 --ng-tracker.dev-mode=false --ng-tracker.driver-path=/home/user >> /home/user/logfile_$ARTIFACT_NAME" &
sleep 10
echo "is deployed"

View File

@ -5,11 +5,16 @@ import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.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.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
@ -25,10 +30,13 @@ import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Entity
@Table(name = "conference")
public class Conference extends BaseEntity {
@DiscriminatorValue("CONFERENCE")
public class Conference extends BaseEntity implements UserActivity, EventSource {
@NotBlank
private String title;
@ -67,18 +75,23 @@ public class Conference extends BaseEntity {
@Fetch(FetchMode.SUBSELECT)
private List<ConferenceUser> users = new ArrayList<>();
@Column(name = "create_date")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate = new Date();
@Column(name = "update_date")
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate = new Date();
public String getTitle() {
return title;
}
@Override
public List<User> getRecipients() {
List<User> list = new ArrayList<>();
getUsers().forEach(conferenceUser -> list.add(conferenceUser.getUser()));
return list;
}
@Override
public void addObjectToEvent(Event event) {
event.setConference(this);
}
public void setTitle(String title) {
this.title = title;
}
@ -155,4 +168,9 @@ public class Conference extends BaseEntity {
.filter(d -> d.getDate().after(new Date()))
.findFirst();
}
@Override
public Set<User> getActivityUsers() {
return getUsers().stream().map(ConferenceUser::getUser).collect(Collectors.toSet());
}
}

View File

@ -25,6 +25,7 @@ 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;
@ -116,7 +117,7 @@ public class ConferenceService extends BaseService {
Conference newConference = copyFromDto(new Conference(), conferenceDto);
newConference = conferenceRepository.save(newConference);
conferenceNotificationService.sendCreateNotification(newConference);
eventService.createFromConference(newConference);
eventService.createFromObject(newConference, Collections.emptyList(), false, "конференции");
return newConference;
}
@ -242,10 +243,9 @@ public class ConferenceService extends BaseService {
}
@Transactional
public Ping ping(ConferenceDto conferenceDto) throws IOException {
Ping ping = pingService.addPing(findOne(conferenceDto.getId()));
public void ping(ConferenceDto conferenceDto) throws IOException {
pingService.addPing(findOne(conferenceDto.getId()));
conferenceRepository.updatePingConference(conferenceDto.getId());
return ping;
}
private Conference findOne(Integer conferenceId) {

View File

@ -23,6 +23,8 @@ public class ApplicationProperties {
private String debugEmail;
private String driverPath;
public boolean isUseHttps() {
return useHttps;
}
@ -70,4 +72,12 @@ public class ApplicationProperties {
public void setDebugEmail(String debugEmail) {
this.debugEmail = debugEmail;
}
public String getDriverPath() {
return driverPath;
}
public void setDriverPath(String driverPath) {
this.driverPath = driverPath;
}
}

View File

@ -0,0 +1,17 @@
package ru.ulstu.core.model;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import java.util.List;
public interface EventSource {
List<Deadline> getDeadlines();
String getTitle();
List<User> getRecipients();
void addObjectToEvent(Event event);
}

View File

@ -4,6 +4,7 @@ import ru.ulstu.user.model.User;
import java.util.Set;
public interface UserContainer {
Set<User> getUsers();
public interface UserActivity {
String getTitle();
Set<User> getActivityUsers();
}

View File

@ -9,6 +9,7 @@ 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;
@ -123,4 +124,10 @@ public class GrantController {
public List<PaperDto> getAllPapers() {
return grantService.getAllUncompletedPapers();
}
@ResponseBody
@PostMapping(value = "/ping")
public void ping(@RequestParam("grantId") int grantId) throws IOException {
grantService.ping(grantId);
}
}

View File

@ -0,0 +1,29 @@
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();
}
}

View File

@ -4,7 +4,8 @@ import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.UserContainer;
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;
@ -13,6 +14,7 @@ import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
@ -29,6 +31,7 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
@ -38,7 +41,8 @@ import java.util.Set;
@Entity
@Table(name = "grants")
public class Grant extends BaseEntity implements UserContainer {
@DiscriminatorValue("GRANT")
public class Grant extends BaseEntity implements UserActivity, EventSource {
public enum GrantStatus {
APPLICATION("Заявка"),
ON_COMPETITION("Отправлен на конкурс"),
@ -101,14 +105,6 @@ public class Grant extends BaseEntity implements UserContainer {
@JoinColumn(name = "grant_id")
private List<Event> events = new ArrayList<>();
@Column(name = "create_date")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate = new Date();
@Column(name = "update_date")
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate = new Date();
public GrantStatus getStatus() {
return status;
}
@ -145,6 +141,16 @@ public class Grant extends BaseEntity implements UserContainer {
return title;
}
@Override
public List<User> getRecipients() {
return authors != null ? new ArrayList<>(authors) : Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setGrant(this);
}
public void setTitle(String title) {
this.title = title;
}
@ -166,7 +172,7 @@ public class Grant extends BaseEntity implements UserContainer {
}
@Override
public Set<User> getUsers() {
public Set<User> getActivityUsers() {
return getAuthors();
}

View File

@ -4,10 +4,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.grant.model.Grant;
import ru.ulstu.user.model.User;
import ru.ulstu.name.BaseRepository;
import java.util.Date;
import java.util.List;
public interface GrantRepository extends JpaRepository<Grant, Integer>, BaseRepository {
@ -16,17 +14,12 @@ public interface GrantRepository extends JpaRepository<Grant, Integer>, BaseRepo
Grant findByTitle(String title);
Grant findGrantById(Integer grantId);
@Override
@Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ")
String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
@Query("SELECT g FROM Grant g WHERE (g.status <> 'SKIPPED') AND (g.status <> 'COMPLETED')")
List<Grant> findAllActive();
@Query("SELECT g FROM Grant g WHERE (:user IS NULL OR user MEMBER OF g.authors) AND (:status IS NULL OR :status = p.status) " +
" AND (:dateFrom IS NULL OR :dateFrom < p.updateDate) AND (:dateTo IS NULL OR :dateTo > p.updateDate)")
List<Grant> findByAuthorHasAndStatus(@Param("user") User user,
@Param("status") Grant.GrantStatus status,
@Param("dateFrom") Date dateFrom,
@Param("dateTo") Date dateTo);
}

View File

@ -1,6 +1,5 @@
package ru.ulstu.grant.service;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@ -17,6 +16,7 @@ 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.Project;
import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.project.service.ProjectService;
@ -52,6 +52,7 @@ public class GrantService extends BaseService {
private final EventService eventService;
private final GrantNotificationService grantNotificationService;
private final KiasService kiasService;
private final PingService pingService;
public GrantService(GrantRepository grantRepository,
FileService fileService,
@ -61,7 +62,8 @@ public class GrantService extends BaseService {
PaperService paperService,
EventService eventService,
GrantNotificationService grantNotificationService,
KiasService kiasService) {
KiasService kiasService,
PingService pingService) {
this.grantRepository = grantRepository;
this.kiasService = kiasService;
this.baseRepository = grantRepository;
@ -72,6 +74,7 @@ public class GrantService extends BaseService {
this.paperService = paperService;
this.eventService = eventService;
this.grantNotificationService = grantNotificationService;
this.pingService = pingService;
}
public List<Grant> findAll() {
@ -90,7 +93,7 @@ public class GrantService extends BaseService {
public Integer create(GrantDto grantDto) throws IOException {
Grant newGrant = copyFromDto(new Grant(), grantDto);
newGrant = grantRepository.save(newGrant);
eventService.createFromGrant(newGrant);
eventService.createFromObject(newGrant, Collections.emptyList(), false, "гранта");
grantNotificationService.sendCreateNotification(newGrant);
return newGrant.getId();
}
@ -178,7 +181,7 @@ public class GrantService extends BaseService {
grant.getPapers().add(paper);
grant = grantRepository.save(grant);
eventService.createFromGrant(grant);
eventService.createFromObject(grant, Collections.emptyList(), false, "гранта");
grantNotificationService.sendCreateNotification(grant);
return grant;
@ -335,7 +338,16 @@ public class GrantService extends BaseService {
return grantRepository.findAllActive();
}
public List<Grant> getByUserAndStatusAndInterval(User user, Grant.GrantStatus status, Date dateFrom, Date dateTo) {
return grantRepository.findByAuthorHasAndStatus(user, status, dateFrom, dateTo);
public Grant findById(Integer id) {
return grantRepository.findOne(id);
}
@Transactional
public void ping(int grantId) throws IOException {
pingService.addPing(findById(grantId));
}
public Grant findGrantById(Integer grantId) {
return grantRepository.findOne(grantId);
}
}

View File

@ -5,16 +5,20 @@ import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Service;
import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.page.KiasPage;
import ru.ulstu.user.service.UserService;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import static org.apache.commons.lang3.StringUtils.isEmpty;
@Service
public class KiasService {
private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s";
@ -27,9 +31,12 @@ public class KiasService {
private final static String DRIVER_TYPE = "webdriver.chrome.driver";
private final UserService userService;
private final ApplicationProperties applicationProperties;
public KiasService(UserService userService) {
public KiasService(UserService userService,
ApplicationProperties applicationProperties) {
this.userService = userService;
this.applicationProperties = applicationProperties;
}
public List<GrantDto> getNewGrantsDto() throws ParseException {
@ -78,8 +85,10 @@ public class KiasService {
}
private String getDriverExecutablePath() {
return KiasService.class.getClassLoader().getResource(
String.format(DRIVER_LOCATION, getDriverExecutable(isWindows()))).getFile();
return isEmpty(applicationProperties.getDriverPath())
? KiasService.class.getClassLoader()
.getResource(String.format(DRIVER_LOCATION, getDriverExecutable(isWindows()))).getFile()
: Paths.get(applicationProperties.getDriverPath(), getDriverExecutable(isWindows())).toString();
}
private String getDriverExecutable(boolean isWindows) {

View File

@ -7,6 +7,7 @@ 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;
@ -72,4 +73,9 @@ public class PaperRestController {
public Response<String> 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);
}
}

View File

@ -5,7 +5,8 @@ import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.UserContainer;
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;
@ -14,6 +15,7 @@ import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
@ -34,7 +36,8 @@ import java.util.Optional;
import java.util.Set;
@Entity
public class Paper extends BaseEntity implements UserContainer {
@DiscriminatorValue("PAPER")
public class Paper extends BaseEntity implements UserActivity, EventSource {
public enum PaperStatus {
ATTENTION("Обратить внимание"),
ON_PREPARATION("На подготовке"),
@ -196,6 +199,16 @@ public class Paper extends BaseEntity implements UserContainer {
return title;
}
@Override
public List<User> getRecipients() {
return new ArrayList(authors);
}
@Override
public void addObjectToEvent(Event event) {
event.setPaper(this);
}
public void setTitle(String title) {
this.title = title;
}
@ -249,7 +262,7 @@ public class Paper extends BaseEntity implements UserContainer {
}
@Override
public Set<User> getUsers() {
public Set<User> getActivityUsers() {
return getAuthors();
}

View File

@ -6,7 +6,6 @@ import org.springframework.data.repository.query.Param;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.user.model.User;
import java.util.Date;
import java.util.List;
public interface PaperRepository extends JpaRepository<Paper, Integer> {
@ -25,11 +24,4 @@ public interface PaperRepository extends JpaRepository<Paper, Integer> {
List<Paper> findByConferencesIsNullAndStatusNot(Paper.PaperStatus status);
List<Paper> findByIdNotInAndConferencesIsNullAndStatusNot(List<Integer> paperIds, Paper.PaperStatus status);
@Query("SELECT p FROM Paper g WHERE (:user IS NULL OR user MEMBER OF p.authors) AND (:status IS NULL OR :status = p.status) " +
"AND (:dateFrom IS NULL OR :dateFrom < p.updateDate) AND (:dateTo IS NULL OR :dateTo > p.updateDate)")
List<Paper> findByAuthorHasAndStatus(@Param("user") User user,
@Param("status") Paper.PaperStatus status,
@Param("dateFrom") Date dateFrom,
@Param("dateTo") Date dateTo);
}

View File

@ -42,8 +42,9 @@ public class LatexService {
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
while ((bufferedReader.readLine()) != null) {
//
String line = bufferedReader.readLine();
while (line != null) {
line = bufferedReader.readLine();
}
}

View File

@ -7,7 +7,6 @@ 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.paper.model.AutoCompleteData;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto;
@ -16,6 +15,7 @@ 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;
@ -56,6 +56,7 @@ public class PaperService {
private final FileService fileService;
private final EventService eventService;
private final ReferenceRepository referenceRepository;
private final PingService pingService;
public PaperService(PaperRepository paperRepository,
ReferenceRepository referenceRepository,
@ -63,7 +64,8 @@ public class PaperService {
PaperNotificationService paperNotificationService,
UserService userService,
DeadlineService deadlineService,
EventService eventService) {
EventService eventService,
PingService pingService) {
this.paperRepository = paperRepository;
this.referenceRepository = referenceRepository;
this.fileService = fileService;
@ -71,6 +73,7 @@ public class PaperService {
this.userService = userService;
this.deadlineService = deadlineService;
this.eventService = eventService;
this.pingService = pingService;
}
public List<Paper> findAll() {
@ -201,7 +204,7 @@ public class PaperService {
paperNotificationService.statusChangeNotification(paper, oldStatus);
if (paper.getStatus() == Paper.PaperStatus.ON_PREPARATION) {
userService.createActivityTookToWork(new ArrayList<>(paper.getUsers()));
userService.createActivityTookToWork(new ArrayList<>(paper.getAuthors()));
}
}
@ -393,7 +396,8 @@ public class PaperService {
return autoCompleteData;
}
public List<Paper> getByUserAndStatusAndInterval(User user, Paper.PaperStatus status, Date dateFrom, Date dateTo) {
return paperRepository.findByAuthorHasAndStatus(user, status, dateFrom, dateTo);
@Transactional
public void ping(int paperId) throws IOException {
pingService.addPing(findPaperById(paperId));
}
}

View File

@ -1,12 +1,20 @@
package ru.ulstu.ping.model;
import com.fasterxml.jackson.annotation.JsonProperty;
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.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;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@ -25,9 +33,24 @@ public class Ping extends BaseEntity {
@JoinColumn(name = "users_id")
private User user;
@ManyToOne(optional = false)
@JoinColumn(name = "conference_id")
private Conference conference;
@Column(name = "activity_type", insertable = false, updatable = false)
private String activityType;
@Any(
metaColumn = @Column(name = "activity_type"),
fetch = FetchType.LAZY
)
@AnyMetaDef(
idType = "integer", metaType = "string",
metaValues = {
@MetaValue(targetEntity = Conference.class, value = "CONFERENCE"),
@MetaValue(targetEntity = Paper.class, value = "PAPER"),
@MetaValue(targetEntity = Project.class, value = "PROJECT"),
@MetaValue(targetEntity = Grant.class, value = "GRANT")
}
)
@JoinColumn(name = "activity_id")
private UserActivity activity;
public Ping() {
}
@ -37,16 +60,6 @@ public class Ping extends BaseEntity {
this.user = user;
}
public Ping(@JsonProperty("id") Integer id,
@JsonProperty("date") Date date,
@JsonProperty("user") User user,
@JsonProperty("conference") Conference conference) {
setId(id);
this.date = date;
this.user = user;
this.conference = conference;
}
public Date getDate() {
return date;
}
@ -63,11 +76,11 @@ public class Ping extends BaseEntity {
this.user = user;
}
public Conference getConference() {
return conference;
public UserActivity getActivity() {
return this.activity;
}
public void setConference(Conference conference) {
this.conference = conference;
public void setActivity(UserActivity activity) {
this.activity = activity;
}
}

View File

@ -0,0 +1,35 @@
package ru.ulstu.ping.model;
import ru.ulstu.user.model.User;
import java.util.ArrayList;
import java.util.List;
public class PingInfo {
private User user;
private List<Ping> pings = new ArrayList<>();
public PingInfo(User user) {
this.user = user;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Ping> getPings() {
return pings;
}
public void setPings(List<Ping> pings) {
this.pings = pings;
}
public void addPing(Ping ping) {
this.pings.add(ping);
}
}

View File

@ -6,8 +6,17 @@ import org.springframework.data.repository.query.Param;
import ru.ulstu.conference.model.Conference;
import ru.ulstu.ping.model.Ping;
import java.util.Date;
import java.util.List;
public interface PingRepository extends JpaRepository<Ping, Integer> {
@Query("SELECT count(*) FROM Ping p WHERE (DAY(p.date) = :day) AND (MONTH(p.date) = :month) AND (YEAR(p.date) = :year) AND (p.conference = :conference)")
@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);
@Query("SELECT p FROM Ping p WHERE (:activity = '' OR p.activityType = :activity)")
List<Ping> getPings(@Param("activity") String activity);
@Query("SELECT p FROM Ping p WHERE (:dateFrom < date)")
List<Ping> findByDate(@Param("dateFrom") Date dateFrom);
}

View File

@ -0,0 +1,58 @@
package ru.ulstu.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.user.model.User;
import ru.ulstu.user.service.MailService;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Service
public class PingScheduler {
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;
this.mailService = mailService;
}
@Scheduled(cron = "0 0 * * 1 ?")
public void sendPingsInfo() {
log.debug("Scheduler.sendPingsInfo started");
List<PingInfo> pingInfos = new ArrayList<>();
for (Ping ping : pingRepository.findByDate(java.sql.Date.valueOf(LocalDate.now().minusWeeks(1)))) {
UserActivity pingActivity = ping.getActivity();
Set<User> users = pingActivity.getActivityUsers();
for (User user : users) {
PingInfo userPing = pingInfos.stream().filter(u -> u.getUser() == user).findFirst().orElse(null);
if (userPing == null) {
userPing = new PingInfo(user);
pingInfos.add(userPing);
}
userPing.addPing(ping);
}
}
for (PingInfo pingInfo : pingInfos) {
mailService.sendEmailFromTemplate(ImmutableMap.of("pings", pingInfo.getPings()),
pingInfo.getUser(), "pingsInfoWeekEmail", PING_MAIL_SUBJECT);
}
}
}

View File

@ -3,6 +3,7 @@ package ru.ulstu.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.user.service.UserService;
@ -10,22 +11,26 @@ import ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service
public class PingService {
private final PingRepository pingRepository;
private final UserService userService;
private final PingScheduler pingScheduler;
public PingService(PingRepository pingRepository,
UserService userService) {
UserService userService,
PingScheduler pingScheduler) {
this.pingRepository = pingRepository;
this.userService = userService;
this.pingScheduler = pingScheduler;
}
@Transactional
public Ping addPing(Conference conference) throws IOException {
public Ping addPing(UserActivity activity) throws IOException {
Ping newPing = new Ping(new Date(), userService.getCurrentUser());
newPing.setConference(conference);
newPing.setActivity(activity);
return pingRepository.save(newPing);
}
@ -33,4 +38,8 @@ public class PingService {
return Math.toIntExact(pingRepository.countByConferenceAndDate(conference, calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR)));
}
public List<Ping> getPings(String activity) {
return pingRepository.getPings(activity);
}
}

View File

@ -9,12 +9,12 @@ 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.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.model.User;
import springfox.documentation.annotations.ApiIgnore;
@ -48,6 +48,8 @@ public class ProjectController {
@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());
@ -72,6 +74,12 @@ public class ProjectController {
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);
@ -100,9 +108,20 @@ public class ProjectController {
return projectService.getProjectExecutors(projectDto);
}
@ModelAttribute("allGrants")
public List<GrantDto> 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);
}
}

View File

@ -1,34 +1,38 @@
package ru.ulstu.project.model;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.UserContainer;
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.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Entity
public class Project extends BaseEntity implements UserContainer {
@DiscriminatorValue("PROJECT")
public class Project extends BaseEntity implements UserActivity, EventSource {
public enum ProjectStatus {
TECHNICAL_TASK("Техническое задание"),
@ -69,25 +73,39 @@ public class Project extends BaseEntity implements UserContainer {
@NotNull
private String repository;
@ManyToOne
@JoinColumn(name = "file_id")
private FileData application;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "project_id", unique = true)
@Fetch(FetchMode.SUBSELECT)
private List<FileData> files = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "project_id")
private List<Event> events = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY)
private List<User> executors = new ArrayList<>();
@Column(name = "create_date")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate = new Date();
@Column(name = "update_date")
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate = new Date();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "project_grants",
joinColumns = {@JoinColumn(name = "project_id")},
inverseJoinColumns = {@JoinColumn(name = "grants_id")})
@Fetch(FetchMode.SUBSELECT)
private List<Grant> grants = new ArrayList<>();
public String getTitle() {
return title;
}
@Override
public List<User> getRecipients() {
return executors != null ? new ArrayList<>(executors) : Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setProject(this);
}
public void setTitle(String title) {
this.title = title;
}
@ -132,12 +150,20 @@ public class Project extends BaseEntity implements UserContainer {
this.deadlines = deadlines;
}
public FileData getApplication() {
return application;
public List<FileData> getFiles() {
return files;
}
public void setApplication(FileData application) {
this.application = application;
public void setFiles(List<FileData> files) {
this.files = files;
}
public List<Event> getEvents() {
return events;
}
public void setEvents(List<Event> events) {
this.events = events;
}
public List<User> getExecutors() {
@ -148,9 +174,20 @@ public class Project extends BaseEntity implements UserContainer {
this.executors = executors;
}
@Override
public Set<User> getUsers() {
Set<User> users = new HashSet<User>(getExecutors());
return users;
return new HashSet<>(getExecutors());
}
@Override
public Set<User> getActivityUsers() {
return new HashSet<>();
}
public List<Grant> getGrants() {
return grants;
}
public void setGrants(List<Grant> grants) {
this.grants = grants;
}
}

View File

@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
import org.thymeleaf.util.StringUtils;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto;
@ -27,10 +28,12 @@ public class ProjectDto {
private List<Deadline> deadlines = new ArrayList<>();
private GrantDto grant;
private String repository;
private String applicationFileName;
private List<FileDataDto> files = new ArrayList<>();
private List<Integer> removedDeadlineIds = new ArrayList<>();
private Set<Integer> executorIds;
private List<UserDto> executors;
private List<Integer> grantIds;
private List<GrantDto> grants;
private final static int MAX_EXECUTORS_LENGTH = 40;
@ -48,9 +51,12 @@ public class ProjectDto {
@JsonProperty("description") String description,
@JsonProperty("grant") GrantDto grant,
@JsonProperty("repository") String repository,
@JsonProperty("files") List<FileDataDto> files,
@JsonProperty("deadlines") List<Deadline> deadlines,
@JsonProperty("executorIds") Set<Integer> executorIds,
@JsonProperty("executors") List<UserDto> executors) {
@JsonProperty("executors") List<UserDto> executors,
@JsonProperty("grantIds") List<Integer> grantIds,
@JsonProperty("grants") List<GrantDto> grants) {
this.id = id;
this.title = title;
this.status = status;
@ -58,9 +64,11 @@ public class ProjectDto {
this.grant = grant;
this.repository = repository;
this.deadlines = deadlines;
this.applicationFileName = null;
this.files = files;
this.executorIds = executorIds;
this.executors = executors;
this.grantIds = grantIds;
this.grants = grants;
}
@ -70,12 +78,14 @@ public class ProjectDto {
this.title = project.getTitle();
this.status = project.getStatus();
this.description = project.getDescription();
this.applicationFileName = project.getApplication() == null ? null : project.getApplication().getName();
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.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() {
@ -134,12 +144,12 @@ public class ProjectDto {
this.deadlines = deadlines;
}
public String getApplicationFileName() {
return applicationFileName;
public List<FileDataDto> getFiles() {
return files;
}
public void setApplicationFileName(String applicationFileName) {
this.applicationFileName = applicationFileName;
public void setFiles(List<FileDataDto> files) {
this.files = files;
}
public List<Integer> getRemovedDeadlineIds() {
@ -172,4 +182,20 @@ public class ProjectDto {
.map(executor -> executor.getLastName())
.collect(Collectors.joining(", ")), MAX_EXECUTORS_LENGTH);
}
public List<Integer> getGrantIds() {
return grantIds;
}
public void setGrantIds(List<Integer> grantIds) {
this.grantIds = grantIds;
}
public List<GrantDto> getGrants() {
return grants;
}
public void setGrants(List<GrantDto> grants) {
this.grants = grants;
}
}

View File

@ -1,21 +1,8 @@
package ru.ulstu.project.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.user.model.User;
import java.util.Date;
import java.util.List;
public interface ProjectRepository extends JpaRepository<Project, Integer> {
@Query("SELECT p FROM Project p WHERE (:user IS NULL OR user MEMBER OF p.authors) AND (:status IS NULL OR :status = p.status) " +
"AND (:dateFrom IS NULL OR :dateFrom < p.updateDate) AND (:dateTo IS NULL OR :dateTo > p.updateDate)")
List<Project> findByAuthorHasAndStatus(@Param("user") User user,
@Param("status") Project.ProjectStatus status,
@Param("dateFrom") Date dateFrom,
@Param("dateTo") Date dateTo);
}

View File

@ -4,20 +4,24 @@ 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 ru.ulstu.user.model.User;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
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;
@ -30,18 +34,24 @@ public class ProjectService {
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,
UserService userService) {
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<Project> findAll() {
@ -66,6 +76,7 @@ public class ProjectService {
public Project create(ProjectDto projectDto) throws IOException {
Project newProject = copyFromDto(new Project(), projectDto);
newProject = projectRepository.save(newProject);
eventService.createFromObject(newProject, Collections.emptyList(), false, "проекта");
if (projectDto.getStatus() == Project.ProjectStatus.IN_WORK) {
userService.createActivityTookToWork(newProject.getExecutors());
}
@ -75,10 +86,13 @@ public class ProjectService {
@Transactional
public Project update(ProjectDto projectDto) throws IOException {
Project project = projectRepository.findOne(projectDto.getId());
if (projectDto.getApplicationFileName() != null && project.getApplication() != null) {
fileService.deleteFile(project.getApplication());
}
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());
}
if (projectDto.getStatus() == Project.ProjectStatus.IN_WORK) {
userService.createActivityTookToWork(project.getExecutors());
}
@ -86,12 +100,13 @@ public class ProjectService {
}
@Transactional
public void delete(Integer projectId) throws IOException {
Project project = projectRepository.findOne(projectId);
if (project.getApplication() != null) {
fileService.deleteFile(project.getApplication());
public boolean delete(Integer projectId) throws IOException {
if (projectRepository.exists(projectId)) {
Project project = projectRepository.findOne(projectId);
projectRepository.delete(project);
return true;
}
projectRepository.delete(project);
return false;
}
private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException {
@ -103,8 +118,12 @@ public class ProjectService {
}
project.setRepository(projectDto.getRepository());
project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines()));
if (projectDto.getApplicationFileName() != null) {
project.setApplication(fileService.createFileFromTmp(projectDto.getApplicationFileName()));
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;
}
@ -117,24 +136,44 @@ public class ProjectService {
}
}
public void removeDeadline(ProjectDto projectDto, Integer deadlineId) {
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.findOne(id);
}
public List<Project> getByUserAndStatusAndInterval(User user, Project.ProjectStatus status, Date dateFrom, Date dateTo) {
return projectRepository.findByAuthorHasAndStatus(user, status, dateFrom, dateTo);
}
public List<User> getProjectExecutors(ProjectDto projectDto) {
List<User> users = userService.findAll();
return users;
}
@Transactional
public void ping(int projectId) throws IOException {
pingService.addPing(findById(projectId));
}
public List<GrantDto> getAllGrants() {
List<GrantDto> grants = convert(grantRepository.findAll(), GrantDto::new);
return grants;
}
public List<GrantDto> getProjectGrants(List<Integer> grantIds) {
return convert(grantRepository.findAll(grantIds), GrantDto::new);
}
public void attachGrant(ProjectDto projectDto) {
if (!projectDto.getGrantIds().isEmpty()) {
projectDto.getGrants().clear();
projectDto.setGrants(getProjectGrants(projectDto.getGrantIds()));
} else {
projectDto.getGrants().clear();
}
}
}

View File

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

View File

@ -4,8 +4,12 @@ import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
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.user.model.User;
import ru.ulstu.user.service.UserService;
import javax.persistence.CascadeType;
import javax.persistence.Column;
@ -20,12 +24,14 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@Entity
public class Task extends BaseEntity {
public class Task extends BaseEntity implements EventSource {
public enum TaskStatus {
IN_WORK("В работе"),
@ -49,6 +55,17 @@ public class Task extends BaseEntity {
private String description;
@Transient
private UserService userService;
public Task() {
}
public Task(UserService userService) {
this.userService = userService;
}
@Enumerated(value = EnumType.STRING)
private TaskStatus status = TaskStatus.IN_WORK;
@ -77,6 +94,16 @@ public class Task extends BaseEntity {
return title;
}
@Override
public List<User> getRecipients() {
return Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setTask(this);
}
public void setTitle(String title) {
this.title = title;
}

View File

@ -21,6 +21,7 @@ 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;
@ -83,7 +84,7 @@ public class TaskService {
public Integer create(TaskDto taskDto) throws IOException {
Task newTask = copyFromDto(new Task(), taskDto);
newTask = taskRepository.save(newTask);
eventService.createFromTask(newTask);
eventService.createFromObject(newTask, Collections.emptyList(), true, "задачи");
return newTask.getId();
}

View File

@ -5,6 +5,7 @@ import ru.ulstu.conference.model.Conference;
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;
@ -88,6 +89,10 @@ public class Event extends BaseEntity {
@JoinColumn(name = "grant_id")
private Grant grant;
@ManyToOne
@JoinColumn(name = "project_id")
private Project project;
@ManyToOne
@JoinColumn(name = "task_id")
private Task task;
@ -196,6 +201,14 @@ public class Event extends BaseEntity {
this.grant = grant;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public Task getTask() {
return task;
}

View File

@ -6,6 +6,7 @@ import org.hibernate.validator.constraints.NotBlank;
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;
@ -30,6 +31,7 @@ public class EventDto {
private PaperDto paperDto;
private ConferenceDto conferenceDto;
private GrantDto grantDto;
private ProjectDto projectDto;
private TaskDto taskDto;
@JsonCreator
@ -45,6 +47,7 @@ public class EventDto {
@JsonProperty("recipients") List<UserDto> recipients,
@JsonProperty("conferenceDto") ConferenceDto conferenceDto,
@JsonProperty("grantDto") GrantDto grantDto,
@JsonProperty("projectDto") ProjectDto projectDto,
@JsonProperty("taskDto") TaskDto taskDto) {
this.id = id;
this.title = title;
@ -58,6 +61,7 @@ public class EventDto {
this.paperDto = paperDto;
this.conferenceDto = conferenceDto;
this.grantDto = grantDto;
this.projectDto = projectDto;
this.taskDto = taskDto;
}
@ -80,6 +84,9 @@ public class EventDto {
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());
}
@ -145,6 +152,14 @@ public class EventDto {
this.grantDto = grantDto;
}
public ProjectDto getProjectDto() {
return projectDto;
}
public void setProjectDto(ProjectDto projectDto) {
this.projectDto = projectDto;
}
public TaskDto getTaskDto() {
return taskDto;
}

View File

@ -5,6 +5,7 @@ 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;
@ -23,5 +24,7 @@ public interface EventRepository extends JpaRepository<Event, Integer> {
List<Event> findAllByGrant(Grant grant);
List<Event> findAllByProject(Project project);
List<Event> findAllByTask(Task task);
}

View File

@ -5,9 +5,11 @@ 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;
@ -16,8 +18,6 @@ import ru.ulstu.timeline.repository.EventRepository;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.service.UserService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@ -105,35 +105,39 @@ public class EventService {
}
public void createFromPaper(Paper newPaper) {
createFromPaper(newPaper, Collections.emptyList());
createFromObject(newPaper, Collections.emptyList(), false, "статьи");
}
public void createFromPaper(Paper newPaper, List<Event> events) {
public void createFromObject(EventSource eventSource, List<Event> events, Boolean addCurrentUser, String suffix) {
List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
timeline.getEvents().removeAll(events);
for (Deadline deadline : newPaper.getDeadlines()
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("Дедлайн статьи");
newEvent.setTitle("Дедлайн " + suffix);
newEvent.setStatus(Event.EventStatus.NEW);
newEvent.setExecuteDate(deadline.getDate());
newEvent.setCreateDate(new Date());
newEvent.setUpdateDate(new Date());
newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' cтатьи '" + newPaper.getTitle() + "'");
newEvent.setRecipients(new ArrayList(newPaper.getAuthors()));
newEvent.setPaper(newPaper);
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<Event> foundEvents = eventRepository.findAllByPaper(paper);
eventRepository.delete(foundEvents);
createFromPaper(paper, foundEvents);
createFromObject(paper, foundEvents, false, "статьи");
}
public List<Event> findByCurrentDate() {
@ -148,65 +152,19 @@ public class EventService {
return convert(findAllFuture(), EventDto::new);
}
public void createFromConference(Conference newConference) {
List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newConference.getDeadlines()
.stream()
.filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date()))
.collect(Collectors.toList())) {
Event newEvent = new Event();
newEvent.setTitle("Дедлайн конференции");
newEvent.setStatus(Event.EventStatus.NEW);
newEvent.setExecuteDate(deadline.getDate());
newEvent.setCreateDate(new Date());
newEvent.setUpdateDate(new Date());
newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' конференции '" + newConference.getTitle() + "'");
newConference.getUsers().forEach(conferenceUser -> newEvent.getRecipients().add(conferenceUser.getUser()));
newEvent.setConference(newConference);
save(newEvent);
timeline.getEvents().add(newEvent);
timelineService.save(timeline);
}
}
public void updateConferenceDeadlines(Conference conference) {
eventRepository.delete(eventRepository.findAllByConference(conference));
createFromConference(conference);
}
public void createFromGrant(Grant newGrant) {
List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newGrant.getDeadlines()
.stream()
.filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date()))
.collect(Collectors.toList())) {
Event newEvent = new Event();
newEvent.setTitle("Дедлайн гранта");
newEvent.setStatus(Event.EventStatus.NEW);
newEvent.setExecuteDate(deadline.getDate());
newEvent.setCreateDate(new Date());
newEvent.setUpdateDate(new Date());
newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' гранта '" + newGrant.getTitle() + "'");
if (newGrant.getAuthors() != null) {
newEvent.setRecipients(new ArrayList(newGrant.getAuthors()));
}
newEvent.getRecipients().add(newGrant.getLeader());
newEvent.setGrant(newGrant);
eventRepository.save(newEvent);
timeline.getEvents().add(newEvent);
timelineService.save(timeline);
}
createFromObject(conference, Collections.emptyList(), false, "конференции");
}
public void updateGrantDeadlines(Grant grant) {
eventRepository.delete(eventRepository.findAllByGrant(grant));
createFromGrant(grant);
createFromObject(grant, Collections.emptyList(), false, "гранта");
}
public void updateProjectDeadlines(Project project) {
eventRepository.delete(eventRepository.findAllByProject(project));
createFromObject(project, Collections.emptyList(), false, "проекта");
}
public void removeConferencesEvent(Conference conference) {
@ -214,32 +172,8 @@ public class EventService {
eventList.forEach(event -> eventRepository.delete(event.getId()));
}
public void createFromTask(Task newTask) {
List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newTask.getDeadlines()
.stream()
.filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date()))
.collect(Collectors.toList())) {
Event newEvent = new Event();
newEvent.setTitle("Дедлайн задачи");
newEvent.setStatus(Event.EventStatus.NEW);
newEvent.setExecuteDate(deadline.getDate());
newEvent.setCreateDate(new Date());
newEvent.setUpdateDate(new Date());
newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' задачи '" + newTask.getTitle() + "'");
newEvent.getRecipients().add(userService.getCurrentUser());
newEvent.setTask(newTask);
eventRepository.save(newEvent);
timeline.getEvents().add(newEvent);
timelineService.save(timeline);
}
}
public void updateTaskDeadlines(Task task) {
eventRepository.delete(eventRepository.findAllByTask(task));
createFromTask(task);
createFromObject(task, Collections.emptyList(), true, "задачи");
}
}
}

View File

@ -4,7 +4,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.annotation.Secured;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@ -37,7 +36,6 @@ import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static ru.ulstu.user.controller.UserController.URL;
@ -176,6 +174,12 @@ public class UserController extends OdinController<UserListDto, UserDto> {
userService.inviteUser(email);
}
@GetMapping("/activities/pings")
public Response<Map<String, Integer>> getActivitesStats(@RequestParam(value = "userId", required = false) Integer userId,
@RequestParam(value = "activity", required = false) String activity) {
return new Response<>(userService.getActivitiesPings(userId, activity));
}
@GetMapping("/activities")
public Response<Map<String, ActivityElement>> getActivitiesList(@RequestParam("userId") Integer userId,
@RequestParam("dateFrom") @DateTimeFormat(pattern = "yyyy-MM-dd") Date dateFrom,

View File

@ -1,5 +1,6 @@
package ru.ulstu.user.controller;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
@ -10,8 +11,8 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.configuration.Constants;
import ru.ulstu.odin.controller.OdinController;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.UserListDto;
import ru.ulstu.user.service.UserService;
import ru.ulstu.user.service.UserSessionService;
@ -19,6 +20,7 @@ import ru.ulstu.user.service.UserSessionService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "/users")
@ -61,6 +63,18 @@ public class UserMvcController extends OdinController<UserListDto, UserDto> {
return userService.findAll();
}
@ModelAttribute("allActivities")
public Map<String, String> getAllActivites() {
return ImmutableMap.of("PAPER", "Статьи",
"GRANT", "Гранты",
"PROJECT", "Проекты",
"CONFERENCE", "Конференции");
}
@GetMapping("/pings")
public void getPings() {
}
@GetMapping("/activities")
public void getActivities() {
}

View File

@ -19,13 +19,10 @@ 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.grant.model.Grant;
import ru.ulstu.grant.service.GrantService;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.service.PaperService;
import ru.ulstu.project.model.Project;
import ru.ulstu.project.service.ProjectService;
import ru.ulstu.ping.model.Ping;
import ru.ulstu.ping.service.PingService;
import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserEmailExistsException;
import ru.ulstu.user.error.UserIdExistsException;
@ -86,6 +83,7 @@ public class UserService implements UserDetailsService {
private final ConferenceService conferenceService;
private final UserSessionService userSessionService;
private final ActivityRepository activityRepository;
private final PingService pingService;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
@ -93,6 +91,7 @@ public class UserService implements UserDetailsService {
UserMapper userMapper,
MailService mailService,
ApplicationProperties applicationProperties,
@Lazy PingService pingService,
@Lazy ConferenceService conferenceRepository,
@Lazy UserSessionService userSessionService,
ActivityRepository activityRepository) throws ParseException {
@ -106,6 +105,7 @@ public class UserService implements UserDetailsService {
this.timetableService = new TimetableService();
this.userSessionService = userSessionService;
this.activityRepository = activityRepository;
this.pingService = pingService;
}
private User getUserByEmail(String email) {
@ -405,6 +405,31 @@ public class UserService implements UserDetailsService {
return ImmutableMap.of("users", usersInfoNow, "error", err);
}
public Map<String, Integer> getActivitiesPings(Integer userId,
String activityName) {
User user = null;
if (userId != null) {
user = findById(userId);
}
Map<String, Integer> activitiesPings = new HashMap<>();
for (Ping ping : pingService.getPings(activityName)) {
UserActivity activity = ping.getActivity();
if (user != null && !activity.getActivityUsers().contains(user)) {
continue;
}
if (activitiesPings.containsKey(activity.getTitle())) {
activitiesPings.put(activity.getTitle(), activitiesPings.get(activity.getTitle()) + 1);
} else {
activitiesPings.put(activity.getTitle(), 1);
}
}
return activitiesPings;
}
public void createActivityTookToWork(List<User> users) {
List<Activity> activities = new ArrayList<>();
for (User user : users) {

View File

@ -18,7 +18,7 @@ public class TimetableService {
private static final String TIMETABLE_URL = "http://timetable.athene.tech/api/1.0/timetable?filter=%s";
private SimpleDateFormat lessonTimeFormat = new SimpleDateFormat("hh:mm");
private long[] lessonsStarts = new long[] {
private long[] lessonsStarts = new long[]{
lessonTimeFormat.parse("8:00:00").getTime(),
lessonTimeFormat.parse("9:40:00").getTime(),
lessonTimeFormat.parse("11:30:00").getTime(),
@ -58,8 +58,8 @@ public class TimetableService {
firstJan.set(Calendar.MONTH, 0);
firstJan.set(Calendar.DAY_OF_MONTH, 1);
return (int) Math.round(Math.ceil((((currentDate.getTime() - firstJan.getTime().getTime()) / 86400000)
+ DateUtils.addDays(firstJan.getTime(), 1).getTime() / 7) % 2));
return (int) Math.round(Math.ceil((((currentDate.getTime() - firstJan.getTime().getTime()) / 86400000)
+ DateUtils.addDays(firstJan.getTime(), 1).getTime() / 7) % 2));
}
private TimetableResponse getTimetableForUser(String userFIO) throws RestClientException {
@ -67,7 +67,7 @@ public class TimetableService {
return restTemplate.getForObject(String.format(TIMETABLE_URL, userFIO), TimetableResponse.class);
}
public Lesson getCurrentLesson(String userFio) {
public Lesson getCurrentLesson(String userFio) {
TimetableResponse response;
try {
response = getTimetableForUser(userFio);

View File

@ -4,7 +4,7 @@ import java.util.ArrayList;
import java.util.List;
public class Day {
public class Day {
private Integer day;
private List<List<Lesson>> lessons = new ArrayList<>();

View File

@ -1,6 +1,6 @@
package ru.ulstu.utils.timetable.model;
public class Lesson {
public class Lesson {
private String group;
private String nameOfLesson;
private String teacher;

View File

@ -1,6 +1,6 @@
package ru.ulstu.utils.timetable.model;
public class TimetableResponse {
public class TimetableResponse {
private Response response;
private String error;

View File

@ -37,4 +37,5 @@ ng-tracker.undead-user-login=admin
ng-tracker.dev-mode=false
ng-tracker.debug_email=
ng-tracker.use-https=false
ng-tracker.check-run=false
ng-tracker.check-run=false
ng-tracker.driver-path=

View File

@ -0,0 +1,13 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190507_000002-1">
<addColumn tableName="event">
<column name="project_id" type="integer"/>
</addColumn>
<addForeignKeyConstraint baseTableName="event" baseColumnNames="project_id"
constraintName="fk_event_project_id" referencedTableName="project"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -2,7 +2,7 @@
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190528_000000-3">
<changeSet author="anton" id="20190528_000002-1">
<createTable tableName="deadline_executors">
<column name="deadline_id" type="integer"/>
<column name="executors_id" type="integer"/>

View File

@ -0,0 +1,17 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190528_000000-3">
<createTable tableName="project_grants">
<column name="project_id" type="integer"/>
<column name="grants_id" type="integer"/>
</createTable>
<addForeignKeyConstraint baseTableName="project_grants" baseColumnNames="project_id"
constraintName="fk_project_project_grants" referencedTableName="project"
referencedColumnNames="id"/>
<addForeignKeyConstraint baseTableName="project_grants" baseColumnNames="grants_id"
constraintName="fk_grant_project_grants" referencedTableName="grants"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,13 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190529_000001-1">
<addColumn tableName="file">
<column name="project_id" type="integer"/>
</addColumn>
<addForeignKeyConstraint baseTableName="file" baseColumnNames="project_id"
constraintName="fk_file_project" referencedTableName="project"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -2,9 +2,9 @@
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190428_000000-1">
<changeSet author="anton" id="20190601_000000-1">
<update tableName="project">
<column name="status" value="APPLICATION"/>
<column name="status" value="TECHNICAL_TASK"/>
</update>
</changeSet>
</databaseChangeLog>
</databaseChangeLog>

View File

@ -0,0 +1,11 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="arefyev" id="20190525_000000-1">
<addColumn tableName="ping">
<column name="activity_type" type="varchar(20)"/>
<column name="activity_id" type="integer"/>
</addColumn>
</changeSet>
</databaseChangeLog>

View File

@ -35,7 +35,6 @@
<include file="db/changelog-20190422_000000-schema.xml"/>
<include file="db/changelog-20190424_000000-schema.xml"/>
<include file="db/changelog-20190426_000000-schema.xml"/>
<include file="db/changelog-20190428_000000-schema.xml"/>
<include file="db/changelog-20190430_000000-schema.xml"/>
<include file="db/changelog-20190505_000000-schema.xml"/>
<include file="db/changelog-20190505_000001-schema.xml"/>
@ -43,11 +42,16 @@
<include file="db/changelog-20190506_000001-schema.xml"/>
<include file="db/changelog-20190507_000000-schema.xml"/>
<include file="db/changelog-20190507_000001-schema.xml"/>
<include file="db/changelog-20190507_000002-schema.xml"/>
<include file="db/changelog-20190511_000000-schema.xml"/>
<include file="db/changelog-20190517_000001-schema.xml"/>
<include file="db/changelog-20190520_000000-schema.xml"/>
<include file="db/changelog-20190523_000000-schema.xml"/>
<include file="db/changelog-20190528_000000-schema.xml"/>
<include file="db/changelog-20190528_000002-schema.xml"/>
<include file="db/changelog-20190529_000000-schema.xml"/>
<include file="db/changelog-20190529_000001-schema.xml"/>
<include file="db/changelog-20190601_000001-schema.xml"/>
<include file="db/changelog-20190605_000000-schema.xml"/>
<include file="db/changelog-20190603_000002-schema.xml"/>
</databaseChangeLog>

View File

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Уведомление о создании статьи</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" th:href="@{|${baseUrl}/favicon.ico|}"/>
</head>
<body>
<p>
Уважаемый(ая) <span th:text="${user.firstName + ' ' + user.lastName}">Ivan Ivanov</span>
</p>
<p>
Вы были отмечены в следующих задачах:
</p>
<p th:each="ping : ${pings}" th:text="${ping.getActivity().getTitle() + ' ' + ping.getDate()}">
</p>
<p>
Regards,
<br/>
<em>NG-tracker.</em>
</p>
</body>
</html>

View File

@ -225,3 +225,19 @@ function getUrlVar(key) {
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && decodeURIComponent(result[1]) || "";
}
function sendPing(field, url) {
id = document.getElementById(field).value
$.ajax({
url:url + `?${field}=` + id,
contentType: "application/json; charset=utf-8",
method: "POST",
success: function() {
showFeedbackMessage("Ping был отправлен", MessageTypesEnum.SUCCESS)
},
error: function(errorData) {
showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING)
}
})
}

View File

@ -126,6 +126,38 @@ function isEmailValid(email) {
return re.test(email)
}
function drawChart() {
userId = $('#author :selected').val()
activity = $('#activity :selected').val()
$.ajax({
url:`/api/1.0/users/activities/pings?userId=${userId}&activity=${activity}`,
contentType: "application/json; charset=utf-8",
method: "GET",
success: function(response) {
if (response.data.length == 0) {
return;
}
array = [['Активности', 'Количество']]
Object.keys(response.data).forEach(function(key) {
console.table('Key : ' + key + ', Value : ' + response.data[key])
array.push([key, response.data[key]])
})
var data = google.visualization.arrayToDataTable(array);
var options = {
title: 'Активности',
is3D: true,
pieResidueSliceLabel: 'Остальное'
};
var chart = new google.visualization.PieChart(document.getElementById('air'));
chart.draw(data, options);
},
error: function(errorData) {
showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING)
}
})
}
function drawActivitiesChart() {
userId = $('#author :selected').val()
dateFrom = $('#dateFrom').val()

View File

@ -156,14 +156,16 @@
<a class="paper-name"
th:href="@{'/papers/paper?id=' + *{papers[__${rowStat.index}__].id} + ''}"
th:if="*{papers[__${rowStat.index}__].id !=null}">
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=*{papers[__${rowStat.index}__].status})"/>
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=*{papers[__${rowStat.index}__].status},
title=*{papers[__${rowStat.index}__].title}, small=false)"/>
<span th:text="*{papers[__${rowStat.index}__].title}">
Имя статьи
</span>
</a>
<a class="paper-name"
th:unless="*{papers[__${rowStat.index}__].id !=null}">
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=*{papers[__${rowStat.index}__].status})"/>
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=*{papers[__${rowStat.index}__].status},
title=*{papers[__${rowStat.index}__].title}, small=false)"/>
<span th:text="*{papers[__${rowStat.index}__].title}">
Имя статьи
</span>

View File

@ -8,10 +8,16 @@
<div class="col">
<span th:replace="grants/fragments/grantStatusFragment :: grantStatus(grantStatus=${grant.status})"/>
<a th:href="@{'grant?id='+${grant.id}}">
<span class="h6" th:if="${#strings.length(grant.title) > 50}" th:text="${#strings.substring(grant.title, 0, 50)} + '...'" th:title="${grant.title}"/>
<span class="h6" th:if="${#strings.length(grant.title) le 50}" th:text="${grant.title}" th:title="${grant.title}"/>
<span class="h6" th:if="${#strings.length(grant.title) > 50}"
th:text="${#strings.substring(grant.title, 0, 50)} + '...'" th:title="${grant.title}"/>
<span class="h6" th:if="${#strings.length(grant.title) le 50}" th:text="${grant.title}"
th:title="${grant.title}"/>
<span class="text-muted" th:text="${grant.authorsString}"/>
</a>
<span th:each="paper, rowStat : *{grant.papers}">
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status},
title=${paper.title}, small=true)"/>
</span>
<input class="id-class" type="hidden" th:value="${grant.id}"/>
<a class="remove-paper pull-right d-none" th:href="@{'/grants/delete/'+${grant.id}}"
data-confirm="Удалить грант?">

View File

@ -25,7 +25,7 @@
<i class="fa fa-circle fa-stack-2x text-failed"></i>
</div>
</th:block>
<i class="fa fa-file-text-o fa-stack-1x fa-inverse"></i>
<i class="fa fa-clipboard fa-stack-1x fa-inverse"></i>
</span>
</body>
</html>

View File

@ -23,7 +23,7 @@
th:object="${grantDto}">
<div class="row">
<div class="col-md-6 col-sm-12">
<input type="hidden" name="id" th:field="*{id}"/>
<input type="hidden" id="grantId" name="id" th:field="*{id}"/>
<div class="form-group">
<label for="title">Название:</label>
<input class="form-control" id="title" type="text"
@ -49,7 +49,7 @@
<div class="form-group">
<label>Дедлайны показателей:</label>
<input type="hidden" th:field="*{removedDeadlineIds}"/>
<div class="row" th:each="deadline, rowStat : *{deadlines}">
<div class="row" id="deadlines" th:each="deadline, rowStat : *{deadlines}">
<input type="hidden" th:field="*{deadlines[__${rowStat.index}__].id}"/>
<div class="col-6 div-deadline-date">
<input type="date" class="form-control form-deadline-date" name="deadline"
@ -191,6 +191,7 @@
</div>
</div>
</div>
<!--
<div class="form-group">
<div th:if="*{project} == null">
<input type="submit" name="createProject" class="btn btn-primary"
@ -198,6 +199,13 @@
</div>
<input type = "hidden" th:field="*{project.id}"/>
</div>
-->
<div class="form-group">
<button id="pingButton" class="btn btn-primary text-uppercase"
type="button" onclick="sendPing('grantId', '/grants/ping')">
Ping авторам
</button>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12">

View File

@ -40,7 +40,7 @@
</div>
</div>
<div class="col-md-4 col-sm-6 portfolio-item">
<a class="portfolio-link" href="./projects/dashboard">
<a class="portfolio-link" href="./projects/projects">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-arrow-right fa-3x"></i>

View File

@ -7,10 +7,12 @@
<div th:fragment="paperDashboard (paper)" class="col-12 col-sm-12 col-md-12 col-lg-4 col-xl-3 dashboard-card">
<div class="row">
<div class="col-2">
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status})"/>
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status},
title=${paper.title}, small=false)"/>
</div>
<div class="col col-10 text-right">
<p th:if="${paper.url!=null and paper.url!=''}"><a target="_blank" th:href="${paper.url}"><i
<p th:if="${paper.url!=null and paper.url!=''}"><a target="_blank" class="externalLink"
th:href="${paper.url}"><i
class="fa fa-external-link fa-1x"
aria-hidden="true"></i></a></p>
<p th:unless="${paper.url!=null and paper.url!=''}"><i class="fa fa-fw fa-2x" aria-hidden="true"></i></p>

View File

@ -6,10 +6,12 @@
<body>
<div th:fragment="paperLine (paper)" class="row text-left paper-row" style="background-color: white;">
<div class="col">
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status})"/>
<a th:href="@{'paper?id='+${paper.id}}">
<span class="h6" th:if="${#strings.length(paper.title)} > 50" th:text="${#strings.substring(paper.title, 0, 50) + '...'}" th:title="${paper.title}"/>
<span class="h6" th:if="${#strings.length(paper.title) le 50}" th:text="${paper.title}" th:title="${paper.title}"/>
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status}, title=${paper.title}, small=false)"/>
<a th:href="@{'../papers/paper?id='+${paper.id}}">
<span class="h6" th:if="${#strings.length(paper.title)} > 50"
th:text="${#strings.substring(paper.title, 0, 50) + '...'}" th:title="${paper.title}"/>
<span class="h6" th:if="${#strings.length(paper.title) le 50}" th:text="${paper.title}"
th:title="${paper.title}"/>
<span class="text-muted" th:text="${paper.authorsString}"/>
</a>
<input class="id-class" type="hidden" th:value="${paper.id}"/>

View File

@ -4,34 +4,35 @@
<meta charset="UTF-8"/>
</head>
<body>
<span th:fragment="paperStatus (paperStatus)" class="fa-stack fa-1x">
<span th:fragment="paperStatus (paperStatus, title, small)" class="fa-stack fa-1x">
<th:block th:switch="${paperStatus.name()}">
<div th:case="'ATTENTION'">
<i class="fa fa-circle fa-stack-2x text-warning"></i>
<i class="fa fa-circle text-warning" th:classappend="${small} ? fa-stack-1x : fa-stack-2x"></i>
</div>
<div th:case="'DRAFT'">
<i class="fa fa-circle fa-stack-2x text-draft"></i>
<i class="fa fa-circle fa-stack-2x text-draft" th:classappend="${small} ? fa-stack-1x : fa-stack-2x"></i>
</div>
<div th:case="'ON_PREPARATION'">
<i class="fa fa-circle fa-stack-2x text-primary"></i>
<i class="fa fa-circle fa-stack-2x text-primary" th:classappend="${small} ? fa-stack-1x : fa-stack-2x"></i>
</div>
<div th:case="'ON_REVIEW'">
<i class="fa fa-circle fa-stack-2x text-review"></i>
<i class="fa fa-circle fa-stack-2x text-review" th:classappend="${small} ? fa-stack-1x : fa-stack-2x"></i>
</div>
<div th:case="'COMPLETED'">
<i class="fa fa-circle fa-stack-2x text-success"></i>
<i class="fa fa-circle fa-stack-2x text-success" th:classappend="${small} ? fa-stack-1x : fa-stack-2x"></i>
</div>
<div th:case="'FAILED'">
<i class="fa fa-circle fa-stack-2x text-failed"></i>
<i class="fa fa-circle fa-stack-2x text-failed" th:classappend="${small} ? fa-stack-1x : fa-stack-2x"></i>
</div>
<div th:case="'ACCEPTED'">
<i class="fa fa-circle fa-stack-2x text-accepted"></i>
<i class="fa fa-circle fa-stack-2x text-accepted" th:classappend="${small} ? fa-stack-1x : fa-stack-2x"></i>
</div>
<div th:case="'NOT_ACCEPTED'">
<i class="fa fa-circle fa-stack-2x text-not-accepted"></i>
<i class="fa fa-circle fa-stack-2x text-not-accepted"
th:classappend="${small} ? fa-stack-1x : fa-stack-2x"></i>
</div>
</th:block>
<i class="fa fa-file-text-o fa-stack-1x fa-inverse"></i>
<i class="fa fa-file-text-o fa-stack-1x fa-inverse" th:title="${title}"></i>
</span>
</body>
</html>

View File

@ -43,7 +43,7 @@
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-main" role="tabpanel"
aria-labelledby="nav-main-tab">
<input type="hidden" name="id" th:field="*{id}"/>
<input type="hidden" id="paperId" name="id" th:field="*{id}"/>
<div class="form-group">
<label for="title">Название:</label>
<input class="form-control" id="title" type="text"
@ -87,14 +87,16 @@
<div class="form-group">
<label>Дедлайны:</label>
<div class="row" th:each="deadline, rowStat : *{deadlines}">
<div class="row deadline" th:each="deadline, rowStat : *{deadlines}">
<input type="hidden" th:field="*{deadlines[__${rowStat.index}__].id}"/>
<div class="col-6">
<input type="date" class="form-control" name="deadline"
<input type="date" class="form-control deadline-date"
name="deadline"
th:field="*{deadlines[__${rowStat.index}__].date}"/>
</div>
<div class="col-4">
<input class="form-control" type="text" placeholder="Описание"
<input class="form-control deadline-desc" type="text"
placeholder="Описание"
th:field="*{deadlines[__${rowStat.index}__].description}"/>
</div>
<div class="col-2">
@ -234,7 +236,8 @@
</div>
<div class="form-group col-12">
<label class="col-4">Год издания:</label>
<input type="number" class="form-control col-7 "
<input type="number"
class="form-control col-7 publicationYear"
name="publicationYear"
th:field="*{references[__${rowStat.index}__].publicationYear}"/>
</div>
@ -247,7 +250,8 @@
</div>
<div class="form-group col-12">
<label class="col-4">Страницы:</label>
<input type="text" class="form-control col-7" name="pages"
<input type="text" class="form-control col-7 pages"
name="pages"
th:field="*{references[__${rowStat.index}__].pages}"/>
</div>
<div class="form-group col-12">
@ -326,7 +330,7 @@
</div>
<div class="form-group">
<button id="pingButton" class="btn btn-primary text-uppercase"
type="button">
type="button" onclick="sendPing('paperId', '/api/1.0/papers/ping')">
Ping авторам
</button>
</div>
@ -526,6 +530,7 @@
}
}
</script>
<script th:inline="javascript">
/*<![CDATA[*/

View File

@ -17,6 +17,7 @@
<div th:replace="projects/fragments/projectDashboardFragment :: projectDashboard(project=${project})"/>
</th:block>
</div>
<div th:replace="fragments/noRecordsFragment :: noRecords(entities=${projects}, noRecordsMessage=' одного проекта', url='project')"/>
</div>
</section>
</div>

View File

@ -0,0 +1,40 @@
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
</head>
<body>
<body>
<div th:fragment="filesList">
<th:block th:each="file, rowStat : *{files}">
<div class="row" th:id="|files${rowStat.index}|"
th:style="${file.deleted} ? 'display: none;' :''">
<input type="hidden" th:field="*{files[__${rowStat.index}__].id}"/>
<input type="hidden"
th:field="*{files[__${rowStat.index}__].deleted}"/>
<input type="hidden"
th:field="*{files[__${rowStat.index}__].name}"/>
<input type="hidden"
th:field="*{files[__${rowStat.index}__].tmpFileName}"/>
<div class="col-2">
<a class="btn btn-danger float-right"
th:onclick="|$('#files${rowStat.index}\\.deleted').val('true'); $('#files${rowStat.index}').hide(); |">
<span aria-hidden="true"><i class="fa fa-times"/></span>
</a>
</div>
<div class="col-10">
<a th:onclick="${file.id==null} ? 'downloadFile('+${file.tmpFileName}+',null,\''+${file.name}+'\')':
'downloadFile(null,'+${file.id}+',\''+${file.name}+'\')' "
href="javascript:void(0)"
th:text="*{files[__${rowStat.index}__].name}">
</a>
</div>
</div>
</th:block>
</div>
</body>
</body>
</html>

View File

@ -24,7 +24,7 @@
th:object="${projectDto}">
<div class="row">
<div class="col-md-6 col-sm-12">
<input type="hidden" name="id" th:field="*{id}"/>
<input type="hidden" id="projectId" name="id" th:field="*{id}"/>
<div class="form-group">
<label for="title">Название:</label>
<input class="form-control" id="title" type="text"
@ -51,12 +51,18 @@
</div>
<div class="form-group">
<label for="createGrant">Добавить грант:</label>
<div th:if="*{grant} == null">
<input type="submit" id="createGrant" name="createGrant" class="btn btn-primary"
value="Добавить грант"/>
<label>Добавить грант:</label>
<div class="row">
<div class="col-10">
<select class="selectpicker form-control" data-live-search="true"
title="-- Прикрепить грант --" id="allGrants"
th:field="*{grantIds}" data-size="5">
<option th:each="grant : ${allGrants}" th:value="${grant.id}"
th:text="${grant.title}"> Грант для прикрепления
</option>
</select>
</div>
</div>
<input type="hidden" th:field="*{grant.id}"/>
</div>
<div class="form-group">
@ -92,9 +98,11 @@
</div>
<div class="col-12" style="margin-bottom: 15px;"></div>
<div class="col-10 div-deadline-executor">
<select class="selectpicker form-control" multiple="true" data-live-search="true"
<select class="selectpicker form-control" multiple="true"
data-live-search="true"
title="-- Выберите исполнителя --" id="executors"
th:field="*{deadlines[__${rowStat.index}__].executors}" data-size="5">
th:field="*{deadlines[__${rowStat.index}__].executors}"
data-size="5">
<option th:each="executors : ${allExecutors}" th:value="${executors.id}"
th:text="${executors.lastName}"> Участник
</option>
@ -113,12 +121,25 @@
value="Добавить дедлайн"/>
</div>
<div class="form-group files-list" id="files-list">
<label>Файлы:</label>
<div th:replace="projects/fragments/projectFilesListFragment"/>
</div>
<div class="form-group">
<label for="loader">Загрузить файл:</label>
<div id="loader">
</div>
</div>
<div class="form-group">
<button id="pingButton" class="btn btn-primary text-uppercase"
type="button" onclick="sendPing('projectId', '/projects/ping')">
Ping авторам
</button>
</div>
</div>
<div class="clearfix"></div>
@ -148,17 +169,119 @@
new FileLoader({
div: "loader",
url: urlFileUpload,
maxSize: 2,
extensions: ["doc", "docx", "xls", "jpg", "png", "pdf", "txt"],
maxSize: -1,
extensions: [],
callback: function (response) {
showFeedbackMessage("Файл успешно загружен");
console.debug(response);
addNewFile(response, $("#files-list"));
}
});
$('.selectpicker').selectpicker();
});
/*]]>*/
function sendPing() {
id = document.getElementById("projectId").value
$.ajax({
url:"/projects/ping?projectId=" + id,
contentType: "application/json; charset=utf-8",
method: "POST",
success: function() {
showFeedbackMessage("Ping был отправлен", MessageTypesEnum.SUCCESS)
},
error: function(errorData) {
showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING)
}
})
}
/*]]>*/
function addNewFile(fileDto, listElement) {
var fileNumber = $('.files-list div.row').length;
var newFileRow = $("<div/>")
.attr("id", 'files' + fileNumber)
.addClass("row");
var idInput = $("<input/>")
.attr("type", "hidden")
.attr("id", "files" + fileNumber + ".id")
.attr("value", '')
.attr("name", "files[" + fileNumber + "].id");
newFileRow.append(idInput);
var flagInput = $("<input/>")
.attr("type", "hidden")
.attr("id", "files" + fileNumber + ".deleted")
.attr("value", "false")
.attr("name", "files[" + fileNumber + "].deleted");
newFileRow.append(flagInput);
var nameInput = $("<input/>")
.attr("type", "hidden")
.attr("id", "files" + fileNumber + ".name")
.attr("value", fileDto.fileName)
.attr("name", "files[" + fileNumber + "].name");
newFileRow.append(nameInput);
var tmpFileNameInput = $("<input/>")
.attr("type", "hidden")
.attr("id", "files" + fileNumber + ".tmpFileName")
.attr("value", fileDto.tmpFileName)
.attr("name", "files[" + fileNumber + "].tmpFileName");
newFileRow.append(tmpFileNameInput);
var nextDiv = $("<div/>")
.addClass("col-2");
var nextA = $("<a/>")
.addClass("btn btn-danger float-right")
.attr("onclick", "$('#files" + fileNumber + "\\\\.deleted').val('true'); $('#files" + fileNumber + "').hide();")
.append(($("<span/>").attr("aria-hidden", "true")).append($("<i/>").addClass("fa fa-times")))
;
nextDiv.append(nextA)
newFileRow.append(nextDiv);
var nameDiv = $("<div/>")
.addClass("col-10")
.append($("<a/>").text(fileDto.fileName)
.attr("href", 'javascript:void(0)')
.attr("onclick", "downloadFile('" + fileDto.tmpFileName + "',null,'" + fileDto.fileName + "')"));
newFileRow.append(nameDiv);
listElement.append(newFileRow);
}
function downloadFile(tmpName, fileId, downloadName) {
let xhr = new XMLHttpRequest();
if (fileId != null) xhr.open('GET', urlFileDownload + fileId);
if (tmpName != null) xhr.open('GET', urlFileDownloadTmp + tmpName);
xhr.responseType = 'blob';
var formData = new FormData();
if (fileId != null) formData.append("file-id", fileId);
if (tmpName != null) formData.append("tmp-file-name", tmpName);
xhr.send(formData);
xhr.onload = function () {
if (this.status == 200) {
console.debug(this.response);
var blob = new Blob([this.response], {type: '*'});
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = downloadName;
a.click();
window.URL.revokeObjectURL(url);
} else {
}
}
}
</script>
</div>

View File

@ -24,6 +24,7 @@
</div>
<div class="col-md-3 col-sm-12">
</div>
<div th:replace="fragments/noRecordsFragment :: noRecords(entities=${projects}, noRecordsMessage=' одного проекта', url='project')"/>
</div>
</div>
</section>

View File

@ -1,7 +1,7 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml">
layout:decorator="default">
<head>
<script src="/js/users.js"></script>
<link rel="stylesheet" href="../css/base.css"/>
@ -35,7 +35,8 @@
<input type="text" name="email" id="resetKey" class="form-control"
placeholder="Код подтверждения" style="display:none"/>
</div>
<div id="dvloader" class="loader" style="display:none"><img src="../img/main/ajax-loader.gif" /></div>
<div id="dvloader" class="loader" style="display:none"><img src="../img/main/ajax-loader.gif"/>
</div>
<button id="btnSend" type="button" onclick="requestResetPassword()"
class="btn btn-success btn-block">
Отправить код подтверждения

View File

@ -29,6 +29,7 @@
showFeedbackMessage(error, MessageTypesEnum.WARNING)
});
/*]]>*/
</script>
</div>
</body>

View File

@ -7,9 +7,13 @@
<div th:fragment="userDashboard (user)" class="col-12 col-sm-12 col-md-12 col-lg-4 col-xl-3 dashboard-card">
<div class="row">
<div class="col col-10">
<b><p th:text="${user.user.lastName} + ' ' + ${user.user.firstName} + ' ' + ${user.user.patronymic}"></p></b>
<i><p th:if="${user.conference != null}" th:text="'Сейчас на конференции ' + ${user.conference.title}"></p></i>
<i><p th:if="${user.lesson != null}" th:text="'Сейчас на паре ' + ${user.lesson.nameOfLesson} + ' в аудитории ' + ${user.lesson.room}"></p></i>
<b><p th:text="${user.user.lastName} + ' ' + ${user.user.firstName} + ' ' + ${user.user.patronymic}"></p>
</b>
<i><p th:if="${user.conference != null}" th:text="'Сейчас на конференции ' + ${user.conference.title}"></p>
</i>
<i><p th:if="${user.lesson != null}"
th:text="'Сейчас на паре ' + ${user.lesson.nameOfLesson} + ' в аудитории ' + ${user.lesson.room}"></p>
</i>
<p th:if="${user.isOnline()}">Онлайн</p>
</div>
</div>

View File

@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html">
<head>
<link rel="stylesheet" href="../css/grant.css"/>
<script src="https://www.google.com/jsapi"></script>
<script src="/js/users.js"></script>
<script src="/js/core.js"></script>
<script>
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
</script>
</head>
<body>
<div class="container" layout:fragment="content">
<section id="ewrq">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading text-uppercase">Ping активности</h2>
</div>
<div id="air" style="width: 500px; height: 400px;" class="col-md-9 col-sm-12"></div>
<div class="col-md-3 col-sm-12">
<div class="filter">
<h5>Фильтр:</h5>
<select class="form-control" id="author"
onchange="drawChart();">
<option value="">Все авторы</option>
<option th:each="user: ${allUsers}" th:value="${user.id}"
th:text="${user.lastName}">lastName
</option>
</select>
<br/>
<select class="form-control" id="activity"
onchange="drawChart();">
<option value="">Все активности</option>
<option th:each="activity: ${allActivities}" th:value="${activity.key}"
th:text="${activity.value}">
</option>
</select>
</div>
</div>
</div>
</div>
</section>
</div>
</body>
</html>

View File

@ -0,0 +1,225 @@
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import core.PageObject;
import core.TestTemplate;
import grant.GrantPage;
import grant.GrantsDashboardPage;
import grant.GrantsPage;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import ru.ulstu.NgTrackerApplication;
import ru.ulstu.configuration.ApplicationProperties;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class GrantTest extends TestTemplate {
private final Map<PageObject, List<String>> navigationHolder = ImmutableMap.of(
new GrantsPage(), Arrays.asList("ГРАНТЫ", "/grants/grants"),
new GrantPage(), Arrays.asList("РЕДАКТИРОВАНИЕ ГРАНТА", "/grants/grant?id=0"),
new GrantsDashboardPage(), Arrays.asList("Гранты", "/grants/dashboard")
);
@Autowired
private ApplicationProperties applicationProperties;
@Test
public void aCreateNewGrant() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 1);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantPage grantPage = (GrantPage) getContext().initPage(page.getKey());
GrantsPage grantsPage = (GrantsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey());
String newGrantName = "test grant" + (new Date());
grantPage.setTitle(newGrantName);
String deadlineDate = new Date().toString();
String deadlineDescription = "test deadline description";
grantPage.setDeadline(deadlineDate, 0, deadlineDescription);
grantPage.setLeader();
grantPage.saveGrant();
Assert.assertTrue(grantsPage.findGrantByTitle(newGrantName));
}
@Test
public void bCreateBlankGrant() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 1);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantPage grantPage = (GrantPage) getContext().initPage(page.getKey());
grantPage.saveGrant();
Assert.assertTrue(grantPage.checkBlankFields());
}
@Test
public void cUpdateGrantTitle() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
grantsPage.getFirstGrant();
String newGrantTitle = "test " + (new Date());
grantPage.setTitle(newGrantTitle);
grantPage.saveGrant();
Assert.assertTrue(grantsPage.findGrantByTitle(newGrantTitle));
}
@Test
public void dAttachPaper() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
grantsPage.getFirstGrant();
Integer countPapers = grantPage.getAttachedPapers().size();
Assert.assertEquals(countPapers + 1, grantPage.attachPaper().size());
}
@Test
public void eDeletePaper() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
grantsPage.getFirstGrant();
Integer oldCountPapers = grantPage.getAttachedPapers().size();
if (oldCountPapers == 0) {
oldCountPapers = grantPage.attachPaper().size();
}
Assert.assertEquals(oldCountPapers - 1, grantPage.deletePaper().size());
}
@Test
public void fAddDeadline() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
grantsPage.getFirstGrant();
String grantId = grantPage.getId();
Integer deadlineCount = grantPage.getDeadlineCount();
String description = "deadline test";
String date = "08.08.2019";
String dateValue = "2019-08-08";
grantPage.addDeadline();
grantPage.setDeadline(date, deadlineCount, description);
grantPage.saveGrant();
getContext().goTo(applicationProperties.getBaseUrl() + String.format("/grants/grant?id=%s", grantId));
Assert.assertTrue(grantPage.checkDeadline(description, dateValue));
}
@Test
public void gDeleteDeadline() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
grantsPage.getFirstGrant();
String grantId = grantPage.getId();
Integer deadlineCount = grantPage.getDeadlineCount();
grantPage.deleteDeadline();
grantPage.saveGrant();
getContext().goTo(applicationProperties.getBaseUrl() + String.format("/grants/grant?id=%s", grantId));
Integer newDeadlineCount = grantPage.getDeadlineCount();
Assert.assertEquals(deadlineCount - 1, (int) newDeadlineCount);
}
@Test
public void hAddAuthor() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
WebElement grant = grantsPage.getFirstGrantWithoutClick();
String grantTitle = grantsPage.getGrantTitle(grant);
Integer authorsCount = grantsPage.getAuthorsCount(grant);
grantsPage.getFirstGrant();
grantPage.addAuthor();
grantPage.saveGrant();
grant = grantsPage.getGrantByTitle(grantTitle);
Integer newAuthorsCount = grantsPage.getAuthorsCount(grant);
Assert.assertEquals(authorsCount + 1, (int) newAuthorsCount);
}
@Test
public void iDeleteAuthor() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
WebElement grant = grantsPage.getFirstGrantWithoutClick();
String grantTitle = grantsPage.getGrantTitle(grant);
Integer authorsCount = grantsPage.getAuthorsCount(grant);
grantsPage.getFirstGrant();
grantPage.deleteAuthor();
grantPage.saveGrant();
grant = grantsPage.getGrantByTitle(grantTitle);
Integer newAuthorsCount = grantsPage.getAuthorsCount(grant);
authorsCount = (authorsCount == 0) ? 0 : authorsCount - 1;
Assert.assertEquals((int) authorsCount, (int) newAuthorsCount);
}
@Test
public void jUpdateGrantDescription() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
String description = "newDescriptionForGrant";
grantsPage.getFirstGrant();
String grantId = grantPage.getId();
grantPage.setDescription(description);
grantPage.saveGrant();
getContext().goTo(applicationProperties.getBaseUrl() + String.format("/grants/grant?id=%s", grantId));
Assert.assertTrue(description.equals(grantPage.getDescription()));
}
@Test
public void kDeleteGrant() throws InterruptedException {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey());
Integer size = grantsPage.getGrantsList().size();
grantsPage.deleteFirst();
Assert.assertEquals(size - 1, grantsPage.getGrantsList().size());
}
}

View File

@ -0,0 +1,247 @@
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import core.PageObject;
import core.TestTemplate;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import paper.PaperPage;
import paper.PapersDashboardPage;
import paper.PapersPage;
import ru.ulstu.NgTrackerApplication;
import ru.ulstu.configuration.ApplicationProperties;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class PaperTest extends TestTemplate {
private final Map<PageObject, List<String>> navigationHolder = ImmutableMap.of(
new PapersPage(), Arrays.asList("СТАТЬИ", "/papers/papers"),
new PaperPage(), Arrays.asList("РЕДАКТИРОВАНИЕ СТАТЬИ", "/papers/paper?id=0"),
new PapersDashboardPage(), Arrays.asList("СТАТЬИ", "/papers/dashboard")
);
@Autowired
private ApplicationProperties applicationProperties;
private String getPaperPageUrl() {
return Iterables.get(navigationHolder.entrySet(), 1).getValue().get(1);
}
private PaperPage getPaperPage() {
PaperPage paperPage = (PaperPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
paperPage.initElements();
return paperPage;
}
private String getPapersPageUrl() {
return Iterables.get(navigationHolder.entrySet(), 0).getValue().get(1);
}
private PapersPage getPapersPage() {
PapersPage papersPage = (PapersPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey());
papersPage.initElements();
return papersPage;
}
private String getPapersDashboardPageUrl() {
return Iterables.get(navigationHolder.entrySet(), 2).getValue().get(1);
}
private PapersDashboardPage getPapersDashboardPage() {
PapersDashboardPage papersDashboardPage = (PapersDashboardPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey());
papersDashboardPage.initElements();
return papersDashboardPage;
}
@Test
public void createNewPaperTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
String testTitle = "test " + (String.valueOf(System.currentTimeMillis()));
fillRequiredFields(paperPage, testTitle);
paperPage.clickSaveBtn();
PapersPage papersPage = getPapersPage();
Assert.assertTrue(papersPage.havePaperWithTitle(testTitle));
}
@Test
public void editPaperTest() {
createNewPaper();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl());
PapersPage papersPage = getPapersPage();
papersPage.clickFirstPaper();
PaperPage paperPage = getPaperPage();
String testTitle = "test " + (String.valueOf(System.currentTimeMillis()));
paperPage.setTitle(testTitle);
paperPage.clickSaveBtn();
Assert.assertTrue(papersPage.havePaperWithTitle(testTitle));
}
private void createNewPaper() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
String testTitle = "test " + (String.valueOf(System.currentTimeMillis()));
fillRequiredFields(paperPage, testTitle);
paperPage.clickSaveBtn();
}
@Test
public void addDeadlineTest() {
createNewPaper();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl());
PapersPage papersPage = getPapersPage();
papersPage.clickFirstPaper();
PaperPage paperPage = getPaperPage();
papersPage.clickAddDeadline();
String testDate = "01.01.2019";
String testDateResult = "2019-01-01";
String testDesc = "desc";
Integer deadlineNumber = 2;
paperPage.setDeadlineDate(deadlineNumber, testDate);
paperPage.setDeadlineDescription(deadlineNumber, testDesc);
String paperId = paperPage.getId();
paperPage.clickSaveBtn();
getContext().goTo(applicationProperties.getBaseUrl() + String.format("/papers/paper?id=%s", paperId));
Assert.assertTrue(paperPage.deadlineExist(testDesc, testDateResult));
}
@Test
public void noDeadlinesValidationTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
String testTitle = "test " + (String.valueOf(System.currentTimeMillis()));
paperPage.setTitle(testTitle);
paperPage.clickSaveBtn();
Assert.assertTrue(paperPage.hasAlert("Не может быть пустым"));
}
private void fillRequiredFields(PaperPage paperPage, String title) {
paperPage.setTitle(title);
String testDate = "01.01.2019";
String testDesc = "desc";
Integer deadlineNumber = 1;
paperPage.setDeadlineDate(deadlineNumber, testDate);
paperPage.setDeadlineDescription(deadlineNumber, testDesc);
}
@Test
public void addReferenceTest() {
createNewPaper();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl());
PapersPage papersPage = getPapersPage();
papersPage.clickFirstPaper();
PaperPage paperPage = getPaperPage();
fillRequiredFields(paperPage, "test " + (String.valueOf(System.currentTimeMillis())));
paperPage.clickReferenceTab();
paperPage.clickAddReferenceButton();
paperPage.clickReferenceTab();
paperPage.showFirstReference();
String authors = "testAuthors";
paperPage.setFirstReferenceAuthors(authors);
String paperId = paperPage.getId();
paperPage.clickSaveBtn();
getContext().goTo(applicationProperties.getBaseUrl() + String.format("/papers/paper?id=%s", paperId));
Assert.assertTrue(paperPage.authorsExists(authors));
}
@Test
public void referencesFormatTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
paperPage.setTitle("test");
paperPage.clickReferenceTab();
paperPage.clickAddReferenceButton();
paperPage.clickReferenceTab();
paperPage.showFirstReference();
paperPage.setFirstReferenceAuthors("authors");
paperPage.setFirstReferencePublicationTitle("title");
paperPage.setFirstReferencePublicationYear("2010");
paperPage.setFirstReferencePublisher("publisher");
paperPage.setFirstReferencePages("200");
paperPage.setFirstReferenceJournalOrCollectionTitle("journal");
paperPage.setFormatStandardSpringer();
paperPage.clickFormatButton();
Assert.assertEquals("authors (2010) title. journal, publisher, pp 200", paperPage.getFormatString());
}
@Test
public void dashboardLinkTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
fillRequiredFields(paperPage, "test " + (String.valueOf(System.currentTimeMillis())));
String testLink = "http://test.com/";
paperPage.setUrl(testLink);
paperPage.clickSaveBtn();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersDashboardPageUrl());
PapersDashboardPage papersDashboardPage = getPapersDashboardPage();
Assert.assertTrue(papersDashboardPage.externalLinkExists(testLink));
}
@Test
public void deletePaperTest() {
createNewPaper();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl());
PapersPage papersPage = getPapersPage();
int size = papersPage.getPapersCount();
papersPage.clickRemoveFirstPaperButton();
papersPage.clickConfirmDeleteButton();
Assert.assertEquals(size - 1, papersPage.getPapersCount());
}
@Test
public void latexValidationTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
paperPage.setTitle("test");
paperPage.clickLatexTab();
paperPage.setLatexText("test");
paperPage.clickPdfButton();
Assert.assertTrue(paperPage.dangerMessageExist("Ошибка при создании PDF"));
}
@Test
public void titleValidationTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
paperPage.clickSaveBtn();
Assert.assertTrue(paperPage.hasAlert("не может быть пусто"));
}
}

View File

@ -0,0 +1,174 @@
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import core.PageObject;
import core.TestTemplate;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import project.ProjectDashboard;
import project.ProjectPage;
import project.ProjectsPage;
import ru.ulstu.NgTrackerApplication;
import ru.ulstu.configuration.ApplicationProperties;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ProjectTest extends TestTemplate {
private final Map<PageObject, List<String>> navigationHolder = ImmutableMap.of(
new ProjectPage(), Arrays.asList("ПРОЕКТЫ", "/projects/projects"),
new ProjectsPage(), Arrays.asList("РЕДАКТИРОВАНИЕ ПРОЕКТА", "/projects/project?id=0"),
new ProjectDashboard(), Arrays.asList("ПРОЕКТЫ", "/projects/dashboard")
);
@Autowired
private ApplicationProperties applicationProperties;
@Test
public void testACreateNewProject() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 1);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(page.getKey());
ProjectPage projectPage = (ProjectPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey());
String name = "Project " + (new Date()).getTime();
String date = "01.01.2019";
Integer deadNum = projectPage.getDeadlineCount();
projectPage.setName(name);
projectPage.clickAddDeadline();
projectPage.addDeadlineDate(date, deadNum);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testBChangeNameAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = "Project " + (new Date()).getTime();
projectPage.clearName();
projectPage.setName(name);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testCChangeDeadlineAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
String date = "01.01.2019";
Integer deadNum = projectPage.getDeadlineCount();
projectPage.addDeadlineDate(date, deadNum);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testDSetStatusAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
projectPage.setStatus();
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testEAddDescriptionAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
String description = "Description " + (new Date()).getTime();
projectPage.addDescription(description);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testFAddLinkAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
String link = "Link " + (new Date()).getTime();
projectPage.addLink(link);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testGAddDeadlineDescriptionAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
String deadDesc = "Description " + (new Date()).getTime();
projectPage.addDeadlineDescription(deadDesc);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testHSetDeadlineCompletionAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
projectPage.setDeadlineCompletion();
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testIDeleteDeadline() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
projectPage.clickDeleteDeadline();
Assert.assertTrue(projectPage.getDeadlineCount() == 0);
}
@Test
public void testJDeleteProject() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
projectPage.clickSave();
projectsPage.deleteFirst();
projectsPage.clickConfirm();
Assert.assertFalse(projectsPage.checkNameInList(name));
}
}

View File

@ -6,8 +6,6 @@ import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
//import org.openqa.selenium.support.PageFactory;
public abstract class Context {
private final static String DRIVER_LOCATION = "drivers/%s";

View File

@ -2,16 +2,24 @@ package core;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public abstract class PageObject {
protected WebDriver driver;
protected JavascriptExecutor js;
protected WebDriverWait waiter;
public abstract String getSubTitle();
public PageObject setDriver(WebDriver driver) {
this.driver = driver;
js = (JavascriptExecutor) driver;
waiter = new WebDriverWait(driver, 10);
return this;
}
public void initElements() {
PageFactory.initElements(driver, this);
}
}

View File

@ -0,0 +1,149 @@
package grant;
import core.PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
public class GrantPage extends PageObject {
@Override
public String getSubTitle() {
return driver.findElement(By.tagName("h2")).getText();
}
public String getId() {
return driver.findElement(By.id("id")).getAttribute("value");
}
public void setTitle(String name) {
driver.findElement(By.id("title")).clear();
driver.findElement(By.id("title")).sendKeys(name);
}
public String getTitle() {
return driver.findElement(By.id("title")).getAttribute("value");
}
public void setDeadline(String date, Integer i, String description) {
driver.findElement(By.id(String.format("deadlines%d.date", i))).sendKeys(date);
driver.findElement(By.id(String.format("deadlines%d.description", i))).sendKeys(description);
}
public void setLeader() {
WebElement webElement = driver.findElement(By.id("leaderId"));
Select selectLeader = new Select(webElement);
selectLeader.selectByVisibleText("Романов");
}
public void saveGrant() {
driver.findElement(By.id("sendMessageButton")).click();
}
public boolean checkBlankFields() {
return driver.findElements(By.className("alert-danger")).size() > 0;
}
public List<WebElement> getAttachedPapers() {
try {
return driver.findElement(By.className("div-selected-papers")).findElements(By.tagName("div"));
} catch (Exception ex) {
return null;
}
}
public List<WebElement> attachPaper() {
WebElement selectPapers = driver.findElement(By.id("allPapers"));
Select select = new Select(selectPapers);
List<WebElement> selectedOptions = select.getAllSelectedOptions();
List<WebElement> allOptions = select.getOptions();
if (selectedOptions.size() >= allOptions.size()) {
for (int i = 0; i < allOptions.size(); i++) {
if (!allOptions.get(i).equals(selectedOptions.get(i))) {
select.selectByVisibleText(allOptions.get(i).getText());
selectedOptions.add(allOptions.get(i));
return selectedOptions;
}
}
} else {
select.selectByVisibleText(allOptions.get(0).getText());
selectedOptions.add(allOptions.get(0));
return selectedOptions;
}
return null;
}
public List<WebElement> deletePaper() {
WebElement selectPapers = driver.findElement(By.id("allPapers"));
Select select = new Select(selectPapers);
select.deselectByVisibleText(select.getFirstSelectedOption().getText());
return select.getAllSelectedOptions();
}
public List<WebElement> getDeadlineList() {
return driver.findElements(By.id("deadlines"));
}
public Integer getDeadlineCount() {
return getDeadlineList().size();
}
public void addDeadline() {
driver.findElement(By.id("addDeadline")).click();
}
public boolean checkDeadline(String description, String dateValue) {
return getDeadlineList()
.stream()
.anyMatch(webElement -> {
return webElement.findElement(By.className("div-deadline-description")).findElement(
By.tagName("input")).getAttribute("value").equals(description)
&& webElement.findElement(By.className("form-deadline-date")).getAttribute("value").equals(dateValue);
});
}
public void deleteDeadline() {
driver.findElements(By.className("btn-delete-deadline")).get(0).click();
}
public List<WebElement> addAuthor() {
WebElement selectAuthors = driver.findElement(By.id("authors"));
Select select = new Select(selectAuthors);
List<WebElement> selectedOptions = select.getAllSelectedOptions();
List<WebElement> allOptions = select.getOptions();
int i = 0;
while (i < selectedOptions.size()) {
if (!allOptions.get(i).equals(selectedOptions.get(i))) {
select.selectByVisibleText(allOptions.get(i).getText());
selectedOptions.add(allOptions.get(i));
return selectedOptions;
} else {
i++;
}
}
if (selectedOptions.size() != allOptions.size()) {
select.selectByVisibleText(allOptions.get(i).getText());
selectedOptions.add(allOptions.get(i));
}
return selectedOptions;
}
public void deleteAuthor() {
WebElement selectAuthors = driver.findElement(By.id("authors"));
Select select = new Select(selectAuthors);
List<WebElement> selectedOptions = select.getAllSelectedOptions();
if (selectedOptions.size() != 0) {
select.deselectByVisibleText(selectedOptions.get(0).getText());
}
}
public void setDescription(String description) {
driver.findElement(By.id("comment")).clear();
driver.findElement(By.id("comment")).sendKeys(description);
}
public String getDescription() {
return driver.findElement(By.id("comment")).getText();
}
}

View File

@ -0,0 +1,11 @@
package grant;
import core.PageObject;
import org.openqa.selenium.By;
public class GrantsDashboardPage extends PageObject {
@Override
public String getSubTitle() {
return driver.findElement(By.tagName("h2")).getText();
}
}

View File

@ -0,0 +1,66 @@
package grant;
import core.PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.List;
public class GrantsPage extends PageObject {
@Override
public String getSubTitle() {
return driver.findElement(By.tagName("h2")).getText();
}
public List<WebElement> getGrantsList() {
return driver.findElements(By.className("grant-row"));
}
public boolean findGrantByTitle(String grantTitle) {
return getGrantsList()
.stream()
.map(el -> el.findElement(By.cssSelector("span.h6")))
.anyMatch(webElement -> webElement.getText().equals(grantTitle));
}
public void deleteFirst() throws InterruptedException {
WebElement findDeleteButton = driver.findElement(By.xpath("//*[@id=\"grants\"]/div/div[2]/div[1]/div[1]/div"));
findDeleteButton.click();
Thread.sleep(3000);
WebElement grant = driver.findElement(By.xpath("//*[@id=\"grants\"]/div/div[2]/div[1]/div[1]/div/a[2]"));
grant.click();
WebElement ok = driver.findElement(By.id("dataConfirmOK"));
ok.click();
}
public void getFirstGrant() {
driver.findElement(By.xpath("//*[@id=\"grants\"]/div/div[2]/div[1]/div[1]/div/a[1]")).click();
}
public WebElement getFirstGrantWithoutClick() {
return driver.findElement(By.xpath("//*[@id=\"grants\"]/div/div[2]/div[1]/div[1]"));
}
public String getGrantTitle(WebElement webElement) {
return webElement.findElement(By.cssSelector("span.h6")).getText();
}
public WebElement getGrantByTitle(String title) {
List<WebElement> list = getGrantsList();
for (int i = 0; i < list.size(); i++) {
if (getGrantTitle(list.get(i)).equals(title)) {
return list.get(i);
}
}
return null;
}
public Integer getAuthorsCount(WebElement webElement) {
String authors = webElement.findElement(By.className("text-muted")).getText();
if (!authors.equals("")) {
String[] mas = authors.split(",");
return mas.length;
}
return 0;
}
}

View File

@ -2,10 +2,216 @@ package paper;
import core.PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
public class PaperPage extends PageObject {
@FindBy(id = "title")
private WebElement titleInput;
@FindBy(id = "sendMessageButton")
private WebElement sendMessageButton;
@FindBy(id = "id")
private WebElement idInput;
@FindBy(css = "#messages .alert-danger span")
private WebElement dangerMessage;
@FindBy(className = "deadline")
private List<WebElement> deadlines;
@FindBy(className = "deadline-date")
private List<WebElement> deadlineDates;
@FindBy(className = "deadline-desc")
private List<WebElement> deadlineDescs;
@FindBy(css = ".alert.alert-danger")
private List<WebElement> dangerAlerts;
@FindBy(className = "collapse-heading")
private WebElement firstCollapsedLink;
@FindBy(id = "nav-references-tab")
private WebElement referenceTab;
@FindBy(id = "nav-latex-tab")
private WebElement latexTab;
@FindBy(id = "latex-text")
private WebElement latexTextarea;
@FindBy(id = "addReference")
private WebElement addReferenceButton;
@FindBy(css = "input.author ")
private WebElement firstAuthorInput;
@FindBy(css = "input.publicationTitle")
private WebElement firstPublicationTitleInput;
@FindBy(css = "input.publicationYear")
private WebElement firstPublicationYearInput;
@FindBy(css = "input.publisher")
private WebElement firstPublisherInput;
@FindBy(css = "input.pages")
private WebElement firstPagesInput;
@FindBy(css = "input.journalOrCollectionTitle")
private WebElement firstJournalOrCollectionTitleInput;
@FindBy(id = "formatBtn")
private WebElement formatButton;
@FindBy(id = "formattedReferencesArea")
private WebElement formatArea;
@FindBy(id = "url")
private WebElement urlInput;
@FindBy(id = "pdfBtn")
private WebElement pdfButton;
@FindBy(css = "input.author ")
private List<WebElement> authorInputs;
public String getSubTitle() {
return driver.findElement(By.tagName("h2")).getText();
}
public void clickReferenceTab() {
js.executeScript("document.getElementById('nav-references-tab').scrollIntoView(false);");
referenceTab.click();
}
public void clickLatexTab() {
latexTab.click();
}
public void showFirstReference() {
waiter.until(ExpectedConditions.elementToBeClickable(firstCollapsedLink));
firstCollapsedLink.click();
}
public void clickAddReferenceButton() {
js.executeScript("arguments[0].click()", addReferenceButton);
}
public void clickFormatButton() {
formatButton.click();
}
public void clickPdfButton() {
pdfButton.click();
}
public void setTitle(String title) {
titleInput.clear();
titleInput.sendKeys(title);
}
public void setLatexText(String text) {
waiter.until(ExpectedConditions.visibilityOf(latexTextarea));
latexTextarea.clear();
latexTextarea.sendKeys(text);
}
public void setFirstReferenceAuthors(String authors) {
waiter.until(ExpectedConditions.visibilityOf(firstAuthorInput));
firstAuthorInput.clear();
firstAuthorInput.sendKeys(authors);
}
public void setFirstReferencePublicationTitle(String title) {
firstPublicationTitleInput.clear();
firstPublicationTitleInput.sendKeys(title);
}
public void setFirstReferencePublicationYear(String year) {
firstPublicationYearInput.clear();
firstPublicationYearInput.sendKeys(year);
}
public void setFirstReferencePublisher(String publisher) {
firstPublisherInput.clear();
firstPublisherInput.sendKeys(publisher);
}
public void setFirstReferencePages(String pages) {
firstPagesInput.clear();
firstPagesInput.sendKeys(pages);
}
public void setFirstReferenceJournalOrCollectionTitle(String journal) {
firstJournalOrCollectionTitleInput.clear();
firstJournalOrCollectionTitleInput.sendKeys(journal);
}
public void setUrl(String url) {
urlInput.clear();
urlInput.sendKeys(url);
}
public void setFormatStandardSpringer() {
Select standards = new Select(driver.findElement(By.id("formatStandard")));
standards.selectByValue("SPRINGER");
}
public void setDeadlineDate(Integer deadlineNumber, String date) {
deadlineDates.get(deadlineNumber - 1).sendKeys(date);
}
public void setDeadlineDescription(Integer deadlineNumber, String desc) {
deadlineDescs.get(deadlineNumber - 1).clear();
deadlineDescs.get(deadlineNumber - 1).sendKeys(desc);
}
public boolean hasAlert(String alertMessage) {
return dangerAlerts
.stream()
.anyMatch(
webElement -> webElement.getText().contains(alertMessage));
}
public void clickSaveBtn() {
sendMessageButton.click();
}
public String getId() {
return idInput.getAttribute("value");
}
public String getFormatString() {
waiter.until(ExpectedConditions.attributeToBeNotEmpty(formatArea, "value"));
return formatArea.getAttribute("value");
}
public boolean deadlineExist(String desc, String date) {
return deadlines
.stream()
.anyMatch(
webElement -> webElement.findElement(By.className("deadline-desc")).getAttribute("value").equals(desc)
&& webElement.findElement(By.className("deadline-date")).getAttribute("value").equals(date));
}
public boolean authorsExists(String authors) {
return authorInputs
.stream()
.anyMatch(
webElement -> webElement.getAttribute("value").equals(authors));
}
public boolean dangerMessageExist(String message) {
waiter.until(ExpectedConditions.visibilityOf(dangerMessage));
return dangerMessage.getText().equals(message);
}
}

View File

@ -2,10 +2,23 @@ package paper;
import core.PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import java.util.List;
public class PapersDashboardPage extends PageObject {
@FindBy(className = "externalLink")
private List<WebElement> externalLinks;
public String getSubTitle() {
return driver.findElement(By.tagName("h2")).getText();
}
public boolean externalLinkExists(String link) {
return externalLinks
.stream()
.anyMatch(
webElement -> webElement.getAttribute("href").equals(link));
}
}

View File

@ -2,10 +2,60 @@ package paper;
import core.PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.util.List;
public class PapersPage extends PageObject {
@FindBy(css = ".paper-row .h6")
private List<WebElement> paperTitles;
@FindBy(className = "paper-row")
private List<WebElement> paperItems;
@FindBy(className = "remove-paper")
private WebElement removeFirstPaperButton;
@FindBy(id = "dataConfirmOK")
private WebElement confirmDeleteButton;
@FindBy(id = "addDeadline")
private WebElement addDeadlineButton;
@FindBy(css = ".paper-row a:nth-child(2)")
private WebElement firstPaper;
public String getSubTitle() {
return driver.findElement(By.tagName("h2")).getText();
}
public void clickFirstPaper() {
firstPaper.click();
}
public void clickAddDeadline() {
addDeadlineButton.click();
}
public void clickRemoveFirstPaperButton() {
js.executeScript("arguments[0].click()", removeFirstPaperButton);
}
public void clickConfirmDeleteButton() {
waiter.until(ExpectedConditions.visibilityOf(confirmDeleteButton));
confirmDeleteButton.click();
}
public boolean havePaperWithTitle(String title) {
return paperTitles
.stream()
.anyMatch(webElement -> webElement.getText().equals(title));
}
public int getPapersCount() {
return paperItems.size();
}
}

View File

@ -0,0 +1,11 @@
package project;
import core.PageObject;
import org.openqa.selenium.By;
public class ProjectDashboard extends PageObject {
public String getSubTitle() {
return driver.findElement(By.tagName("h2")).getText();
}
}

View File

@ -0,0 +1,141 @@
package project;
import core.PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.List;
public class ProjectPage extends PageObject {
public String getSubTitle() {
return driver.findElement(By.tagName("h3")).getText();
}
public String getId() {
return driver.findElement(By.id("id")).getAttribute("value");
}
public void setName(String name) {
driver.findElement(By.id("title")).sendKeys(name);
}
public String getName() {
return driver.findElement(By.id("title")).getAttribute("value");
}
public void clearName() {
driver.findElement(By.id("title")).clear();
}
public void clickSave() {
driver.findElement(By.id("sendMessageButton")).click();
}
public void clickAddDeadline() {
driver.findElement(By.id("addDeadline")).click();
}
public void addDeadlineDate(String deadDate, Integer deadNum) {
driver.findElement(By.id(String.format("deadlines%d.date", deadNum))).sendKeys(deadDate);
}
public void addDeadlineDescription(String description) {
driver.findElement(By.id("deadlines0.description")).sendKeys(description);
}
public void setDeadlineCompletion() {
driver.findElement(By.id("deadlines0.done1")).click();
}
public void setStatus() {
driver.findElement(By.id("status")).click();
getFirstStatus();
}
public void getFirstStatus() {
driver.findElement(By.xpath("//*[@id=\"status\"]/option[1]")).click();
}
public void addDescription(String description) {
driver.findElement(By.id("description")).sendKeys(description);
}
public void addLink(String link) {
driver.findElement(By.id("repository")).sendKeys(link);
}
public List<WebElement> getDeadlineList() {
return driver.findElements(By.className("deadline"));
}
public Integer getDeadlineCount() {
return driver.findElements(By.className("deadline")).size();
}
public void setExecutors() {
driver.findElement(By.id("status")).click();
getFirstExecutor();
}
public void getFirstExecutor() {
driver.findElement(By.xpath("//*[@id=\"status\"]/option[1]")).click();
}
public void setDeadlineDescription(String description, Integer i) {
driver.findElement(By.id(String.format("deadlines%d.description", i))).sendKeys(description);
}
public void setDeadlineDate(String date, Integer i) {
driver.findElement(By.id(String.format("deadlines%d.date", i))).sendKeys(date);
}
public Boolean isTakePartButDisabledValueTrue() {
return driver.findElement(By.id("take-part")).getAttribute("disabled").equals("true");
}
public Integer getMemberCount() {
return driver.findElements(By.className("member")).size();
}
public void clickDeleteDeadline() {
driver.findElement(By.className("btn-danger")).click();
}
public void showAllowToAttachArticles() {
driver.findElement(By.cssSelector("button[data-id=\"paperIds\"]")).click();
}
public void clickAddPaperBut() {
driver.findElement(By.id("add-paper")).click();
}
public List<WebElement> getArticles() {
return driver.findElements(By.className("paper"));
}
public Integer getArticlesCount() {
return driver.findElements(By.className("paper")).size();
}
public WebElement selectArticle() {
WebElement webElement = driver.findElement(By.xpath("//*[@id=\"project-form\"]/div/div[2]/div[5]/div/div/div[2]/ul/li[1]/a"));
webElement.click();
return webElement;
}
public void clickUndockArticleBut() {
driver.findElement(By.name("removePaper")).click();
}
public boolean checkDeadline(String description, String dateValue) {
return getDeadlineList()
.stream()
.anyMatch(webElement -> {
return webElement.findElement(By.className("deadline-text")).getAttribute("value").equals(description)
&& webElement.findElement(By.cssSelector("input[type=\"date\"]")).getAttribute("value").equals(dateValue);
});
}
}

View File

@ -0,0 +1,41 @@
package project;
import core.PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.List;
public class ProjectsPage extends PageObject {
public String getSubTitle() {
return driver.findElement(By.tagName("h2")).getText();
}
public List<WebElement> getProjectsList() {
return driver.findElements(By.cssSelector("span.h6"));
}
public void getFirstProject() {
driver.findElement(By.xpath("//*[@id=\"projects\"]/div/div[2]/div[1]/div[1]/div/a")).click();
}
public void selectMember() {
driver.findElements(By.className("bootstrap-select")).get(0).findElement(By.className("btn")).click();
driver.findElements(By.className("bootstrap-select")).get(0).findElements(By.className("dropdown-item")).get(1).click();
}
public void deleteFirst() {
js.executeScript("$('a[data-confirm]').click();");
}
public void clickConfirm() {
driver.findElement(By.id("dataConfirmOK")).click();
}
public boolean checkNameInList(String newProjectName) {
return getProjectsList()
.stream()
.anyMatch(webElement -> webElement.getText().equals(newProjectName));
}
}

View File

@ -276,14 +276,4 @@ public class ConferenceServiceTest {
assertTrue(conferenceService.isAttachedToConference(ID));
}
@Test
public void ping() throws IOException {
Ping ping = new Ping();
when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId);
when(pingService.addPing(conferenceWithId)).thenReturn(ping);
when(conferenceRepository.updatePingConference(ID)).thenReturn(INDEX);
assertEquals(ping, conferenceService.ping(conferenceDto));
}
}

View File

@ -0,0 +1,151 @@
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.mockito.runners.MockitoJUnitRunner;
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(MockitoJUnitRunner.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<Project> projects;
private Project project;
private ProjectDto projectDto;
private Deadline deadline;
private List<Deadline> deadlines;
private FileData file;
private List<FileData> files;
private User user;
private GrantDto grant;
private List<GrantDto> grants;
@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);
grants = new ArrayList<>();
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.exists(ID)).thenReturn(true);
when(projectRepository.findOne(ID)).thenReturn(project);
assertTrue(projectService.delete(ID));
}
@Test
public void getProjectExecutors() {
List<User> executors = Collections.singletonList(user);
when(userService.findAll()).thenReturn(executors);
assertEquals(executors, projectService.getProjectExecutors(projectDto));
}
@Test
public void findById() {
when(projectRepository.findOne(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());
}
}

View File

@ -136,7 +136,7 @@ public class TaskServiceTest {
when(tagService.saveOrCreate(new ArrayList<>())).thenReturn(tags);
when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines);
when(taskRepository.save(new Task())).thenReturn(task);
eventService.createFromTask(new Task());
eventService.createFromObject(new Task(), Collections.emptyList(), true, "задачи");
taskDto.setTags(tags);
taskDto.setDeadlines(deadlines);