Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

484 diveni stat - draft #489

Merged
merged 35 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
8fa4780
fix: remove autofix of linter on forked PRs
stritti Oct 19, 2023
9bdc4b2
fix: precent comit on backend action
stritti Oct 19, 2023
6da86f2
fix: Actions updated
stritti Oct 25, 2023
a989f1b
Merge branch 'main' into fix/456-build-fail-at-forked-projects
stritti Oct 25, 2023
0be5352
fix: lint issue solved
stritti Oct 25, 2023
68d11e7
fix: lint-staged command corrected
stritti Oct 25, 2023
b7a59e3
fix: remove last month stats
G1t-Happens Oct 27, 2023
9e104c7
fix: remove last month stats
G1t-Happens Oct 27, 2023
cefa01b
fix: remove unused imports
G1t-Happens Oct 27, 2023
756d49c
fix: implement statistic entity
G1t-Happens Oct 27, 2023
db67b52
fix: implement statistic repo
G1t-Happens Oct 27, 2023
a91a31a
fix: remove unused method param
G1t-Happens Oct 27, 2023
8817d0a
fix: implement business logic for stat calculation
G1t-Happens Oct 27, 2023
7d4a092
fix: remove unused last month stats
G1t-Happens Oct 27, 2023
17c6a81
fix: simplify method
G1t-Happens Oct 27, 2023
41cc4e3
fix: let DatabaseService handle everything + introduce logging
G1t-Happens Oct 27, 2023
e4b455f
fix: remove initialization and add lombok constructor
G1t-Happens Oct 27, 2023
5fcf338
fix: only remove a member if the member hasn't used the 'Leave Sessio…
G1t-Happens Oct 27, 2023
11f94bb
fix: implement method to check if member is still in session
G1t-Happens Oct 27, 2023
6c2a9f5
style: same name convention
G1t-Happens Oct 27, 2023
16ce660
fix: remove LastMonth tests
G1t-Happens Oct 27, 2023
1435860
fix: set attendees before the session gets deleted
G1t-Happens Oct 27, 2023
f792d86
fix: remove last month stats
G1t-Happens Oct 27, 2023
ea97ed5
fix: experimentally removing removeMember stream
G1t-Happens Oct 28, 2023
eb2ef9e
fix: no responsestatusexception needed
G1t-Happens Oct 28, 2023
4c9dcae
fix: let the admin register first to avoid 404 - session not found er…
G1t-Happens Oct 28, 2023
dc59f10
fix: ensuring the atomic update of the statistics and the deletion of…
G1t-Happens Oct 28, 2023
e084dcd
fix: useless import
G1t-Happens Oct 28, 2023
a4b3807
Merge remote-tracking branch 'upstream/fix/456-build-fail-at-forked-p…
G1t-Happens Oct 28, 2023
d882c6d
fix: revert some changes + requestMemberUpdate to be executed only on…
G1t-Happens Oct 29, 2023
6094e4b
Merge remote-tracking branch 'origin/main' into 484-diveni-stat
G1t-Happens Oct 30, 2023
e1b78d1
fix: npm run lint:fix + undo deleted comment
G1t-Happens Oct 30, 2023
deecd26
Merge remote-tracking branch 'origin/main' into 484-diveni-stat
G1t-Happens Oct 31, 2023
753f605
Merge remote-tracking branch 'origin/main' into 484-diveni-stat
G1t-Happens Nov 9, 2023
622e4e7
fix: set creation time to track when we started logging the entry
G1t-Happens Nov 10, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package io.diveni.backend.controller;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
Expand All @@ -12,92 +10,36 @@
import org.springframework.web.bind.annotation.GetMapping;

import io.diveni.backend.model.AnalyticsData;
import io.diveni.backend.model.Session;
import io.diveni.backend.service.DatabaseService;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AnalyticsController {

private static final Logger LOGGER = LoggerFactory.getLogger(RoutesController.class);
private static final Logger LOGGER = LoggerFactory.getLogger(AnalyticsController.class);

@Autowired DatabaseService databaseService;

@GetMapping(value = "/analytics/All")
public ResponseEntity<AnalyticsData> getAllData() {
LOGGER.debug("--> getAllData()");

int amountOfAllSessions =
databaseService.getSessions().size() + databaseService.getDeletedSessions().size();
databaseService.getSessions().size() + databaseService.getDeletedSessions();
int amountOfAllAttendees =
databaseService.getSessions().stream()
.collect(Collectors.summingInt(s -> s.getMembers().size())); // existing Sessions
amountOfAllAttendees +=
databaseService.getDeletedSessions().stream()
.collect(Collectors.summingInt(deletedSess -> deletedSess.getMembers().size()));

amountOfAllAttendees +=
databaseService.getDeletedSessions().stream()
.filter(
ds ->
databaseService.getRemovedMember().stream()
.anyMatch(rm -> rm.getSessionID().equals(ds.getSessionID())))
.count();

int lastMonth = LocalDate.now().getMonthValue();
int counter;
int year;
if (lastMonth == 1) {
counter = 11;
year = LocalDate.now().getYear() - 1;
} else {
counter = -1;
year = LocalDate.now().getYear();
}
int finalLastMonth = lastMonth + counter;
List<Session> sessionFromLastMonth =
databaseService.getSessions().stream()
.filter(
s ->
s.getCreationTime().getMonthValue() == finalLastMonth
&& s.getCreationTime().getYear() == year)
.collect(Collectors.toList());

List<Session> deletedsessionFromLastMonth =
databaseService.getDeletedSessions().stream()
.filter(
s ->
s.getCreationTime().getMonthValue() == finalLastMonth
&& s.getCreationTime().getYear() == year)
.collect(Collectors.toList());

int amountOfSessionsLastMonth =
sessionFromLastMonth.size() + deletedsessionFromLastMonth.size();
int amountOfAttendeesLastMonth =
sessionFromLastMonth.stream().collect(Collectors.summingInt(s -> s.getMembers().size()));

amountOfAttendeesLastMonth +=
deletedsessionFromLastMonth.stream()
.collect(Collectors.summingInt(s -> s.getMembers().size()));

amountOfAttendeesLastMonth +=
deletedsessionFromLastMonth.stream()
.filter(
ds ->
databaseService.getRemovedMember().stream()
.anyMatch(rm -> rm.getSessionID().equals(ds.getSessionID())))
.count();
amountOfAllAttendees += databaseService.getRemovedMember();

int currentAmountOfSessions = databaseService.getSessions().size();
int currentAmountOfAttendees =
databaseService.getSessions().stream()
.collect(Collectors.summingInt(s -> s.getMembers().size())); // existing Sessions
LOGGER.debug("<-- getAllData()");
return new ResponseEntity<AnalyticsData>(
return new ResponseEntity<>(
new AnalyticsData(
amountOfAllAttendees,
amountOfAllSessions,
amountOfAttendeesLastMonth,
amountOfSessionsLastMonth,
currentAmountOfAttendees,
currentAmountOfSessions),
HttpStatus.OK);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,6 @@ public void closeSession(AdminPrincipal principal) {
ControllerUtils.getSessionOrThrowResponse(databaseService, principal.getSessionID());
webSocketService.sendSessionStateToMembers(
session.updateSessionState(SessionState.SESSION_CLOSED));
webSocketService.getSessionPrincipals(session.getSessionID()).memberPrincipals().stream()
.forEach(memberP -> removeMember(memberP));
webSocketService.removeSession(session);
databaseService.deleteSession(session);
LOGGER.debug("<-- closeSession()");
Expand Down Expand Up @@ -295,4 +293,14 @@ public synchronized ResponseEntity<Long> getTimeValue(String memberID) throws Pa
LOGGER.debug("<-- get-timer-value() + " + timeDifference);
return new ResponseEntity<>(timeDifference, HttpStatus.OK);
}

public boolean isMemberInSession(Principal principal) {
LOGGER.debug("--> isMemberInSession()");
if (principal instanceof MemberPrincipal) {
LOGGER.debug("<-- isMemberInSession()");
return databaseService.getSessionByMemberID(((MemberPrincipal) principal).getMemberID()).isPresent();
}
LOGGER.debug("<-- isMemberInSession(). principal is NOT instanceof MemberPrincipal");
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ public void onApplicationEvent(SessionDisconnectEvent event) {
LOGGER.debug("--> onApplicationEvent()");
var principal = event.getUser();
if (principal instanceof MemberPrincipal) {
controller.removeMember(principal);
if (controller.isMemberInSession(principal)) {
controller.removeMember(principal);
}
}
LOGGER.debug("<-- onApplicationEvent()");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ public class AnalyticsData {

private final int amountOfSessions;

private final int amountofAttendeesLastMonth;

private final int amountOfSessionsLastMonth;

private final int amountOfAttendeesCurrently;

private final int amountOfSessionsCurrently;
Expand Down
39 changes: 39 additions & 0 deletions backend/src/main/java/io/diveni/backend/model/Statistic.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package io.diveni.backend.model;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.time.LocalDate;

@Getter
@AllArgsConstructor
@EqualsAndHashCode
@Document("statistics")
public class Statistic {

@Id private String id;

private Integer overallSessions;

private Integer overallAttendees;

private final LocalDate creationTime;

public Statistic incrementOverallSessions() {
overallSessions++;
return this;
}

public Statistic incrementOverallAttendees() {
overallAttendees++;
return this;
}

public Statistic addOverallAttendees(int overallAttendees) {
this.overallAttendees += overallAttendees;
return this;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package io.diveni.backend.repository;

import io.diveni.backend.model.Statistic;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface StatisticRepository extends MongoRepository<Statistic, String> {

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,63 +5,99 @@
*/
package io.diveni.backend.service;

import java.util.ArrayList;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import io.diveni.backend.model.Session;
import io.diveni.backend.principals.MemberPrincipal;
import io.diveni.backend.model.Statistic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.diveni.backend.repository.SessionRepository;
import io.diveni.backend.repository.StatisticRepository;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DatabaseService {

private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseService.class);

//Sets the database entry identifier in our 'statistics' table.
//Only modify if you want to create a new database entry!!!
//Variable can be further extracted
private final String statEntryIdentifier = "STAT_V1";

@Autowired SessionRepository sessionRepo;

private List<Session> deletedSessions = new ArrayList<>();
@Autowired StatisticRepository statisticRepo;

private List<MemberPrincipal> removedMembers = new ArrayList<>();

public Optional<Session> getSessionByID(String sessionID) {
LOGGER.debug("getSessionByID()");
return Optional.ofNullable(sessionRepo.findBySessionID(sessionID));
}

public Optional<Session> getSessionByAdminCookie(UUID adminCookie) {
LOGGER.debug("getSessionByAdminCookie()");
return Optional.ofNullable(sessionRepo.findByAdminCookie(adminCookie));
}

public Optional<Session> getSessionByMemberID(String memberID) {
LOGGER.debug("getSessionByMemberID()");
return sessionRepo.findByMemberID(memberID);
}

public List<Session> getSessions() {
LOGGER.debug("getSessions()");
return sessionRepo.findAll();
}

public Session saveSession(Session session) {
LOGGER.debug("saveSession()");
return sessionRepo.save(session.setLastModified(new Date()));
}

@Transactional
public void deleteSession(Session session) {
deletedSessions.add(session);
LOGGER.debug("--> deleteSession()");
Statistic statistic = getOrCreateStatistic();
statistic.incrementOverallSessions().addOverallAttendees(session.getMembers().size());
statisticRepo.save(statistic);
sessionRepo.delete(session);
LOGGER.debug("<-- deleteSession()");
}

public void addRemovedMember() {
LOGGER.debug("--> addRemovedMember()");
Statistic statistic = getOrCreateStatistic();
statistic.incrementOverallAttendees();
statisticRepo.save(statistic);
LOGGER.debug("<-- addRemovedMember()");
}

public void addRemovedMember(MemberPrincipal removedMember) {
this.removedMembers.add(removedMember);
public Integer getRemovedMember() {
LOGGER.debug("getRemovedMember()");
return statisticRepo.findById(statEntryIdentifier)
.map(Statistic::getOverallAttendees)
.orElse(0);
}

public List<MemberPrincipal> getRemovedMember() {
return this.removedMembers;
public Integer getDeletedSessions() {
LOGGER.debug("getDeletedSessions()");
return statisticRepo.findById(statEntryIdentifier)
.map(Statistic::getOverallSessions)
.orElse(0);
}

public List<Session> getDeletedSessions() {
return this.deletedSessions;
private Statistic getOrCreateStatistic() {
LOGGER.debug("getOrCreateStatistic()");
return statisticRepo.findById(statEntryIdentifier)
.orElseGet(() -> statisticRepo.save(new Statistic(statEntryIdentifier, 0, 0, LocalDate.now())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public synchronized void removeMember(MemberPrincipal member) {
else return p;
})
.collect(Collectors.toList());
databaseService.addRemovedMember(member);
databaseService.addRemovedMember();
LOGGER.debug("<-- removeMember()");
}

Expand Down
Loading
Loading