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

Feature: 부원들 출석 정보 열람 기능 구현 #80

Merged
merged 9 commits into from
Aug 5, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.cotato.csquiz.api.attendance.controller;

import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.cotato.csquiz.api.attendance.dto.AttendanceRecordResponse;
import org.cotato.csquiz.api.attendance.dto.UpdateAttendanceRequest;
import org.cotato.csquiz.domain.attendance.service.AttendanceAdminService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/v2/api/attendance")
Youthhing marked this conversation as resolved.
Show resolved Hide resolved
public class AttendanceController {

private final AttendanceAdminService attendanceAdminService;

@Operation(summary = "출석 정보 변경 API")
@PatchMapping()
public ResponseEntity<Void> updateAttendance(@RequestBody @Valid UpdateAttendanceRequest request) {
attendanceAdminService.updateAttendance(request);
return ResponseEntity.noContent().build();
}

@Operation(summary = "회원 출결사항 조회 API")
@GetMapping("/records")
public ResponseEntity<List<AttendanceRecordResponse>> findAttendanceRecords(
@RequestParam(name = "generationId") Long generationId,
@RequestParam(name = "month", required = false) @Min(1) @Max(12) Integer month
Youthhing marked this conversation as resolved.
Show resolved Hide resolved
) {
return ResponseEntity.ok().body(attendanceAdminService.findAttendanceRecords(generationId, month));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package org.cotato.csquiz.api.attendance.dto;

import org.cotato.csquiz.domain.attendance.entity.AttendanceRecord;
import org.cotato.csquiz.domain.attendance.enums.AttendanceStatus;
import org.cotato.csquiz.domain.attendance.enums.AttendanceType;

public record AttendanceInfoResponse(
Long attendanceId,
Long attendanceRecordId,
AttendanceType attendanceType,
AttendanceStatus attendanceStatus
) {
public static AttendanceInfoResponse from(AttendanceRecord attendanceRecord) {
return new AttendanceInfoResponse(
attendanceRecord.getAttendance().getId(),
attendanceRecord.getId(),
attendanceRecord.getAttendanceType(),
attendanceRecord.getAttendanceStatus()
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package org.cotato.csquiz.api.attendance.dto;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.cotato.csquiz.api.admin.dto.MemberInfoResponse;
import org.cotato.csquiz.domain.attendance.entity.AttendanceRecord;
import org.cotato.csquiz.domain.attendance.enums.AttendanceStatus;
import org.cotato.csquiz.domain.attendance.enums.AttendanceType;


public record AttendanceRecordResponse(
MemberInfoResponse memberInfo,
List<AttendanceInfoResponse> attendanceInfos,
Youthhing marked this conversation as resolved.
Show resolved Hide resolved
AttendanceStatistic statistic
) {
public static AttendanceRecordResponse of(MemberInfoResponse memberInfo, List<AttendanceRecord> attendanceRecords,
Integer totalAttendance) {
return new AttendanceRecordResponse(
memberInfo,
attendanceRecords.stream()
.map(AttendanceInfoResponse::from)
.toList(),
AttendanceStatistic.from(attendanceRecords, totalAttendance)
);
}

public record AttendanceStatistic(
Integer onLine,
Integer offLine,
Integer late,
Integer absent
) {
public static AttendanceStatistic from(List<AttendanceRecord> attendanceRecords, Integer totalAttendance) {
Map<AttendanceStatus, List<AttendanceRecord>> countByStatus = attendanceRecords.stream()
.collect(Collectors.groupingBy(AttendanceRecord::getAttendanceStatus));
List<AttendanceRecord> presentRecords = countByStatus.getOrDefault(AttendanceStatus.PRESENT, List.of());

int onlineCount = (int) presentRecords.stream()
.filter(record -> AttendanceType.ONLINE == record.getAttendanceType())
.count();
int offLineCount = (int) presentRecords.stream()
.filter(record -> AttendanceType.OFFLINE == record.getAttendanceType())
.count();

return new AttendanceStatistic(
onlineCount,
offLineCount,
countByStatus.getOrDefault(AttendanceStatus.LATE, List.of()).size(),
totalAttendance - attendanceRecords.size()
);
}
}
Youthhing marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.cotato.csquiz.api.attendance.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import jakarta.validation.constraints.NotNull;
import java.time.LocalTime;
import org.cotato.csquiz.domain.attendance.embedded.Location;

public record UpdateAttendanceRequest(
Long attendanceId,
Location location,

@NotNull
AttendanceDeadLine attendanceDeadLine
) {
public record AttendanceDeadLine(
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss")
LocalTime startTime,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss")
LocalTime endTime
) {
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package org.cotato.csquiz.api.session.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import org.cotato.csquiz.domain.attendance.embedded.Location;
import org.cotato.csquiz.domain.generation.enums.CSEducation;
import org.cotato.csquiz.domain.generation.enums.DevTalk;
import org.cotato.csquiz.domain.generation.enums.ItIssue;
Expand All @@ -16,9 +20,22 @@ public record AddSessionRequest(
String title,
@NotNull
String description,
Location location,
String placeName,
@NotNull
LocalDate sessionDate,
@NotNull
AttendanceDeadLine attendanceDeadLine,
ItIssue itIssue,
Networking networking,
CSEducation csEducation,
DevTalk devTalk
) {
public record AttendanceDeadLine(
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss")
LocalTime startTime,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss")
LocalTime endTime
){
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.requestMatchers("/v1/api/session/cs-on").hasAnyRole("EDUCATION", "ADMIN")
.requestMatchers(new AntPathRequestMatcher("/v1/api/session", "GET")).authenticated()
.requestMatchers("/v1/api/session/**").hasAnyRole("ADMIN")
.requestMatchers("/v2/api/attendance/records").hasAnyRole("ADMIN")
.requestMatchers("/v2/api/attendance").hasAnyRole("ADMIN")
.requestMatchers(new AntPathRequestMatcher("/v1/api/socket/token", "POST"))
.hasAnyRole("MEMBER", "EDUCATION", "ADMIN")
.requestMatchers("/v1/api/socket/**").hasAnyRole("EDUCATION", "ADMIN")
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/org/cotato/csquiz/common/error/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ public enum ErrorCode {
// 기수 운영 (세션 -> 출석)
INVALID_DATE(HttpStatus.BAD_REQUEST, "G-101", "시작날짜가 끝 날짜보다 뒤입니다"),
GENERATION_NUMBER_DUPLICATED(HttpStatus.CONFLICT, "G-201", "같은 숫자의 기수가 있습니다"),

SESSION_DATE_NOT_FOUND(HttpStatus.NOT_FOUND, "G-202", "세션 날짜가 존재하지 않습니다"),
SESSION_DEADLINE_INVALID(HttpStatus.BAD_REQUEST, "G-102", "시작 시간과 끝 시간을 입력해주세요"),
// 교육 도메인
REGRADE_FAIL(HttpStatus.BAD_REQUEST, "E-201", "재채점 할 기록이 없습니다."),
EDUCATION_DUPLICATED(HttpStatus.CONFLICT, "E-301", "이미 교육이 존재합니다"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.time.LocalDate;
import java.time.LocalDateTime;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.cotato.csquiz.api.attendance.dto.UpdateAttendanceRequest.AttendanceDeadLine;
import org.cotato.csquiz.common.entity.BaseTimeEntity;
import org.cotato.csquiz.domain.attendance.embedded.Location;
import org.cotato.csquiz.domain.generation.entity.Session;

@Entity
@Getter
Expand All @@ -32,4 +36,21 @@ public class Attendance extends BaseTimeEntity {

@Column(name = "session_id", nullable = false, unique = true)
private Long sessionId;

@Builder
public Attendance(LocalDateTime startTime, LocalDateTime endTime, Location location, Session session) {
this.startTime = startTime;
this.endTime = endTime;
this.location = location;
this.sessionId = session.getId();
}

public void updateLocation(Location location) {
this.location = location;
}

public void updateDeadLine(LocalDate sessionDate, AttendanceDeadLine deadLine) {
this.startTime = LocalDateTime.of(sessionDate, deadLine.startTime());
this.endTime = LocalDateTime.of(sessionDate, deadLine.endTime());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.cotato.csquiz.common.entity.BaseTimeEntity;
import org.cotato.csquiz.domain.attendance.enums.AttendanceStatus;
import org.cotato.csquiz.domain.attendance.enums.AttendanceType;

@Table(name = "attendance_record")
Expand All @@ -32,6 +33,10 @@ public class AttendanceRecord extends BaseTimeEntity {
@Enumerated(EnumType.STRING)
private AttendanceType attendanceType;

@Column(name = "attendance_status", nullable = false)
@Enumerated(EnumType.STRING)
private AttendanceStatus attendanceStatus;

@Column(name = "location_accuracy")
private Double locationAccuracy;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.cotato.csquiz.domain.attendance.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public enum AttendanceStatus {
PRESENT("출석"),
LATE("지각"),
;

private final String description;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.cotato.csquiz.domain.attendance.repository;

import java.util.List;
import org.cotato.csquiz.domain.attendance.entity.Attendance;
import org.cotato.csquiz.domain.attendance.entity.AttendanceRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface AttendanceRecordRepository extends JpaRepository<AttendanceRecord, Long> {
@Query("select a from AttendanceRecord a where a.attendance in :attendances")
List<AttendanceRecord> findAllByAttendanceIdsInQuery(@Param("attendances") List<Attendance> attendances);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package org.cotato.csquiz.domain.attendance.repository;

import java.util.List;
import org.cotato.csquiz.domain.attendance.entity.Attendance;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface AttendanceRepository extends JpaRepository<Attendance, Long> {
@Query("select a from Attendance a where a.sessionId in :sessionIds")
List<Attendance> findAllBySessionIdsInQuery(@Param("sessionIds") List<Long> sessionIds);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package org.cotato.csquiz.domain.attendance.service;


import jakarta.persistence.EntityNotFoundException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.cotato.csquiz.api.attendance.dto.AttendanceRecordResponse;
import org.cotato.csquiz.api.attendance.dto.UpdateAttendanceRequest;
import org.cotato.csquiz.api.session.dto.AddSessionRequest.AttendanceDeadLine;
import org.cotato.csquiz.common.error.ErrorCode;
import org.cotato.csquiz.common.error.exception.AppException;
import org.cotato.csquiz.domain.attendance.embedded.Location;
import org.cotato.csquiz.domain.attendance.entity.Attendance;
import org.cotato.csquiz.domain.attendance.repository.AttendanceRepository;
import org.cotato.csquiz.domain.generation.entity.Session;
import org.cotato.csquiz.domain.generation.repository.SessionRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
@Slf4j
public class AttendanceAdminService {

private final AttendanceRepository attendanceRepository;
private final AttendanceRecordService attendanceRecordService;
private final SessionRepository sessionRepository;

@Transactional
public void addAttendance(Session session, LocalDate localDate, Location location,
AttendanceDeadLine attendanceDeadLine) {

if (checkAttendanceTimeValid(attendanceDeadLine.startTime(), attendanceDeadLine.endTime())) {
throw new AppException(ErrorCode.SESSION_DEADLINE_INVALID);
}

Attendance attendance = Attendance.builder()
.session(session)
.location(location)
.startTime(LocalDateTime.of(localDate, attendanceDeadLine.startTime()))
.endTime(LocalDateTime.of(localDate, attendanceDeadLine.endTime()))
.build();

attendanceRepository.save(attendance);
}


@Transactional
public void updateAttendance(UpdateAttendanceRequest request) {
Attendance attendance = attendanceRepository.findById(request.attendanceId())
.orElseThrow(() -> new EntityNotFoundException("해당 출석 정보가 존재하지 않습니다"));
Session attendanceSession = sessionRepository.findById(attendance.getSessionId())
.orElseThrow(() -> new EntityNotFoundException("출석과 연결된 세션을 찾을 수 없습니다"));

if (attendanceSession.getSessionDate() == null) {
throw new AppException(ErrorCode.SESSION_DATE_NOT_FOUND);
}

if (checkAttendanceTimeValid(request.attendanceDeadLine().startTime(), request.attendanceDeadLine().endTime())) {
throw new AppException(ErrorCode.SESSION_DEADLINE_INVALID);
}

attendance.updateDeadLine(attendanceSession.getSessionDate(), request.attendanceDeadLine());
attendance.updateLocation(request.location());
}

public List<AttendanceRecordResponse> findAttendanceRecords(Long generationId, Integer month) {
List<Session> sessions = sessionRepository.findAllByGenerationId(generationId);
if (month != null) {
sessions = sessions.stream()
.filter(session -> session.getSessionDate().getMonthValue() == month)
.toList();
}
List<Long> sessionIds = sessions.stream()
.map(Session::getId)
.toList();

List<Attendance> attendances = attendanceRepository.findAllBySessionIdsInQuery(sessionIds).stream()
.toList();
Youthhing marked this conversation as resolved.
Show resolved Hide resolved

return attendanceRecordService.generateAttendanceResponses(attendances);
}

private boolean checkAttendanceTimeValid(LocalTime startTime, LocalTime endTime) {
return endTime == null || startTime == null;
}
Youthhing marked this conversation as resolved.
Show resolved Hide resolved
}
Loading
Loading