mirror of
https://github.com/headporter81/specialsource-homepage-backend.git
synced 2026-12-06 07:41:09 +09:00
feat : 방문자 카운터·관리자 API, admin 계정 관리자 권한
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 56s
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 56s
- 지금 접속: IP별 마지막 요청 시각을 메모리로 (5분) - 일별 정산: NAS가 꺼진 0시 대신 켜질 때·7시 10분에 빠진 날 몰아서, 날짜는 한국 시간 - 방문 기록: 로그인 사용자도 1시간에 한 번만, IP는 CF-Connecting-IP 우선 - 진단용 UploadErrorAdvice 제거 (400 오류를 500으로 바꾸던 부작용) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
926d78c094
commit
f9aad9ae3a
15 files changed
+181
-63
No files matched your search
@@ -28,5 +28,11 @@ public class DataInitializer implements CommandLineRunner {
|
|||||||
} else {
|
} else {
|
||||||
log.info("이미 관리자 계정이 존재합니다.");
|
log.info("이미 관리자 계정이 존재합니다.");
|
||||||
}
|
}
|
||||||
|
// admin 계정은 관리자 권한 (관리자 화면·접속 기록). 처음에 ROLE_USER로 만들어져 있던 것을 한 번 올려 줌
|
||||||
|
userRepository.findByUsername("admin").filter(u -> !"ROLE_ADMIN".equals(u.getRole())).ifPresent(u -> {
|
||||||
|
u.setRole("ROLE_ADMIN");
|
||||||
|
userRepository.save(u);
|
||||||
|
log.info("admin 계정을 관리자(ROLE_ADMIN)로 바꿨습니다.");
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,6 +40,7 @@ public class SecurityConfig {
|
|||||||
.requestMatchers(HttpMethod.GET, "/api/guestbook").permitAll()
|
.requestMatchers(HttpMethod.GET, "/api/guestbook").permitAll()
|
||||||
.requestMatchers(HttpMethod.POST, "/api/guestbook").permitAll()
|
.requestMatchers(HttpMethod.POST, "/api/guestbook").permitAll()
|
||||||
.requestMatchers("/api/chat").permitAll()
|
.requestMatchers("/api/chat").permitAll()
|
||||||
|
.requestMatchers(HttpMethod.GET, "/api/analytics/counter").permitAll() // 메인 화면 방문자 카운터
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
package company.specialsource.config;
|
|
||||||
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.ErrorResponse;
|
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
// 업로드 500 원인 찾기용: 컨트롤러 진입 전(멀티파트 해석 등)에 난 오류도 원인을 응답에 담아 화면까지 전달
|
|
||||||
// ErrorResponse(400·404 같은 스프링 표준 오류)는 원래대로 두고, 그 밖의 예외만
|
|
||||||
@RestControllerAdvice
|
|
||||||
public class UploadErrorAdvice {
|
|
||||||
|
|
||||||
@ExceptionHandler(Exception.class)
|
|
||||||
public ResponseEntity<?> handle(Exception e) throws Exception {
|
|
||||||
if (e instanceof ErrorResponse) throw e;
|
|
||||||
e.printStackTrace();
|
|
||||||
Throwable root = e;
|
|
||||||
while (root.getCause() != null && root.getCause() != root) root = root.getCause();
|
|
||||||
String msg = root == e ? e.toString() : e + " ← " + root;
|
|
||||||
return ResponseEntity.status(500).body(Map.of("error", "서버 처리 실패: " + msg));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,6 +2,7 @@ package company.specialsource.config;
|
|||||||
|
|
||||||
import company.specialsource.entity.VisitorLog;
|
import company.specialsource.entity.VisitorLog;
|
||||||
import company.specialsource.repository.VisitorLogRepository;
|
import company.specialsource.repository.VisitorLogRepository;
|
||||||
|
import company.specialsource.service.AnalyticsService;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -17,6 +18,7 @@ import java.time.ZonedDateTime;
|
|||||||
public class VisitorInterceptor implements HandlerInterceptor {
|
public class VisitorInterceptor implements HandlerInterceptor {
|
||||||
|
|
||||||
private final VisitorLogRepository visitorLogRepository;
|
private final VisitorLogRepository visitorLogRepository;
|
||||||
|
private final AnalyticsService analyticsService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||||
@@ -24,13 +26,12 @@ public class VisitorInterceptor implements HandlerInterceptor {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. 진짜 클라이언트 IP 추출
|
// 1. 진짜 클라이언트 IP (클라우드플레어가 넣어 주는 값 우선) + "지금 접속 중" 갱신
|
||||||
String ip = request.getHeader("X-Forwarded-For");
|
String ip = ClientGuard.ip(request);
|
||||||
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
|
analyticsService.touch(ip);
|
||||||
ip = request.getRemoteAddr();
|
// 대화실은 2초마다 물어봐서 DB 방문 기록은 남기지 않음 (접속 중 표시만)
|
||||||
}
|
if (request.getRequestURI().startsWith("/api/chat")) {
|
||||||
if (ip != null && ip.contains(",")) {
|
return true;
|
||||||
ip = ip.split(",")[0].trim();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 🟢 [NEW] 현재 요청을 보낸 유저의 식별 정보 추적 (기본값: anonymous)
|
// 2. 🟢 [NEW] 현재 요청을 보낸 유저의 식별 정보 추적 (기본값: anonymous)
|
||||||
@@ -52,10 +53,9 @@ public class VisitorInterceptor implements HandlerInterceptor {
|
|||||||
try {
|
try {
|
||||||
// 중복 카운팅 방지: 동일 IP가 최근 1시간 이내에 접속한 로그가 있는지 확인
|
// 중복 카운팅 방지: 동일 IP가 최근 1시간 이내에 접속한 로그가 있는지 확인
|
||||||
ZonedDateTime oneHourAgo = ZonedDateTime.now().minusHours(1);
|
ZonedDateTime oneHourAgo = ZonedDateTime.now().minusHours(1);
|
||||||
boolean isRecentVisitor = visitorLogRepository.existsByIpAddressAndAccessedAtAfter(ip, oneHourAgo);
|
boolean isRecentVisitor = visitorLogRepository.existsByIpAddressAndUsernameAndAccessedAtAfter(ip, username, oneHourAgo);
|
||||||
|
|
||||||
// 1시간 이내에 왔던 기록이 없거나, 'anonymous'가 아닌 실제 '회원 로그인 ID'인 경우는 무조건 기록 갱신
|
if (!isRecentVisitor) { // 같은 IP·같은 사용자는 1시간에 한 번만 (로그인 사용자도 요청마다 쌓이지 않게)
|
||||||
if (!isRecentVisitor || !"anonymous".equals(username)) {
|
|
||||||
VisitorLog visitorLog = new VisitorLog();
|
VisitorLog visitorLog = new VisitorLog();
|
||||||
visitorLog.setIpAddress(ip);
|
visitorLog.setIpAddress(ip);
|
||||||
visitorLog.setUsername(username); // 🟢 추출한 아이디 또는 anonymous 주입
|
visitorLog.setUsername(username); // 🟢 추출한 아이디 또는 anonymous 주입
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
|||||||
public void addInterceptors(InterceptorRegistry registry) {
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
registry.addInterceptor(visitorInterceptor)
|
registry.addInterceptor(visitorInterceptor)
|
||||||
// .addPathPatterns("/api/**") // 🟢 모든 API 주소로 들어오는 길목을 차단하여 감시
|
// .addPathPatterns("/api/**") // 🟢 모든 API 주소로 들어오는 길목을 차단하여 감시
|
||||||
.excludePathPatterns("/api/analytics/**", "/api/chat", // 대화실은 2초마다 물어봐서 방문 기록에서 뺌
|
.excludePathPatterns("/api/analytics/**", "/api/media-posts/files/**", "/static/**", "/favicon.ico"); // 통계 조회 API 자체는 중복 카운팅 차단
|
||||||
"/api/media-posts/files/**", "/static/**", "/favicon.ico"); // 통계 조회 API 자체는 중복 카운팅 차단
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package company.specialsource.controller;
|
||||||
|
|
||||||
|
import company.specialsource.entity.VisitorLog;
|
||||||
|
import company.specialsource.repository.VisitorLogRepository;
|
||||||
|
import company.specialsource.service.AnalyticsService;
|
||||||
|
import company.specialsource.service.UserService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.security.Principal;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 관리자 화면 (role = ROLE_ADMIN만): 방문 통계, 접속 기록 */
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/admin")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AdminController {
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
private final AnalyticsService analyticsService;
|
||||||
|
private final VisitorLogRepository visitorLogRepository;
|
||||||
|
|
||||||
|
/** 접속 기록 한 줄 (시각은 한국 시간) */
|
||||||
|
public record VisitorRow(long id, LocalDateTime at, String ip, String username, String userAgent) {
|
||||||
|
static VisitorRow of(VisitorLog v) {
|
||||||
|
return new VisitorRow(v.getId(), v.getAccessedAt().withZoneSameInstant(AnalyticsService.ZONE).toLocalDateTime(),
|
||||||
|
v.getIpAddress(), v.getUsername(), v.getUserAgent());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/stats")
|
||||||
|
public ResponseEntity<?> stats(Principal principal) {
|
||||||
|
if (!userService.isAdmin(principal.getName())) return ResponseEntity.status(403).build();
|
||||||
|
return ResponseEntity.ok(analyticsService.adminStats());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 최근 접속 기록 50개씩 (before = 이미 받은 마지막 id → 그보다 오래된 기록). 상세 기록은 30일만 보관
|
||||||
|
@GetMapping("/visitors")
|
||||||
|
public ResponseEntity<?> visitors(@RequestParam(required = false) Long before, Principal principal) {
|
||||||
|
if (!userService.isAdmin(principal.getName())) return ResponseEntity.status(403).build();
|
||||||
|
List<VisitorLog> rows = before == null
|
||||||
|
? visitorLogRepository.findTop50ByOrderByIdDesc()
|
||||||
|
: visitorLogRepository.findTop50ByIdLessThanOrderByIdDesc(before);
|
||||||
|
return ResponseEntity.ok(rows.stream().map(VisitorRow::of).toList());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,4 +24,10 @@ public class AnalyticsController {
|
|||||||
Map<String, Long> liveStats = analyticsService.getRealTimeDashboardStats();
|
Map<String, Long> liveStats = analyticsService.getRealTimeDashboardStats();
|
||||||
return ResponseEntity.ok(liveStats);
|
return ResponseEntity.ok(liveStats);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/** 메인 화면 방문자 카운터 (로그인 없이): 오늘·전체 방문자, 지금 접속 */
|
||||||
|
@GetMapping("/counter")
|
||||||
|
public AnalyticsService.Counter counter() {
|
||||||
|
return analyticsService.counter();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,8 +28,9 @@ public class AuthController {
|
|||||||
String token = jwtTokenProvider.createToken(request.getUsername());
|
String token = jwtTokenProvider.createToken(request.getUsername());
|
||||||
|
|
||||||
// 3. 응답 상자에 토큰을 담아서 리턴
|
// 3. 응답 상자에 토큰을 담아서 리턴
|
||||||
Map<String, String> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
response.put("token", token);
|
response.put("token", token);
|
||||||
|
response.put("admin", userService.isAdmin(request.getUsername())); // true면 화면에 관리자 메뉴 표시
|
||||||
return ResponseEntity.ok(response);
|
return ResponseEntity.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,5 +21,6 @@ public class User {
|
|||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
|
@Setter
|
||||||
private String role; // 예: ROLE_USER, ROLE_ADMIN
|
private String role; // 예: ROLE_USER, ROLE_ADMIN
|
||||||
}
|
}
|
||||||
@@ -4,11 +4,20 @@ import company.specialsource.entity.DailyVisitorStats;
|
|||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface DailyVisitorStatsRepository extends JpaRepository<DailyVisitorStats, LocalDate> {
|
public interface DailyVisitorStatsRepository extends JpaRepository<DailyVisitorStats, LocalDate> {
|
||||||
|
|
||||||
|
// 지금까지 정산된 날들의 방문자 합계 (전체 방문자 카운터)
|
||||||
|
@Query("select coalesce(sum(s.uniqueVisitorCount), 0) from DailyVisitorStats s")
|
||||||
|
long sumVisitors();
|
||||||
|
|
||||||
|
List<DailyVisitorStats> findByVisitDateBetweenOrderByVisitDateDesc(LocalDate start, LocalDate end);
|
||||||
|
|
||||||
// 💡 일일 통계 정산 데이터는 JPA가 기본 제공하는 save() 메서드만으로도
|
// 💡 일일 통계 정산 데이터는 JPA가 기본 제공하는 save() 메서드만으로도
|
||||||
// 새벽마다 적재(Insert/Update)하는 비즈니스 로직을 에러 없이 완벽하게 수행할 수 있습니다.
|
// 새벽마다 적재(Insert/Update)하는 비즈니스 로직을 에러 없이 완벽하게 수행할 수 있습니다.
|
||||||
|
|
||||||
|
|||||||
@@ -9,12 +9,18 @@ import org.springframework.stereotype.Repository;
|
|||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface VisitorLogRepository extends JpaRepository<VisitorLog, Long> {
|
public interface VisitorLogRepository extends JpaRepository<VisitorLog, Long> {
|
||||||
|
|
||||||
// 1시간 중복 방문 여부 확인 메서드
|
// 1시간 중복 방문 여부 확인 (같은 IP·같은 사용자)
|
||||||
boolean existsByIpAddressAndAccessedAtAfter(String ipAddress, ZonedDateTime time);
|
boolean existsByIpAddressAndUsernameAndAccessedAtAfter(String ipAddress, String username, ZonedDateTime time);
|
||||||
|
|
||||||
|
// 관리자 화면: 최근 기록 50개씩 (before = 이미 받은 마지막 id)
|
||||||
|
List<VisitorLog> findTop50ByOrderByIdDesc();
|
||||||
|
|
||||||
|
List<VisitorLog> findTop50ByIdLessThanOrderByIdDesc(long before);
|
||||||
|
|
||||||
// 오늘 기준 실시간 고유 접속자 카운트 (중복 IP 제거)
|
// 오늘 기준 실시간 고유 접속자 카운트 (중복 IP 제거)
|
||||||
@Query("SELECT COUNT(DISTINCT v.ipAddress) FROM VisitorLog v WHERE v.accessedAt >= :startOfDay")
|
@Query("SELECT COUNT(DISTINCT v.ipAddress) FROM VisitorLog v WHERE v.accessedAt >= :startOfDay")
|
||||||
|
|||||||
@@ -3,10 +3,11 @@ package company.specialsource.scheduler;
|
|||||||
import company.specialsource.service.AnalyticsService;
|
import company.specialsource.service.AnalyticsService;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -18,15 +19,16 @@ public class VisitorScheduler {
|
|||||||
/**
|
/**
|
||||||
* 매일 새벽 0시 5분에 정확히 트리거되는 크론 배치 스케줄링 메서드
|
* 매일 새벽 0시 5분에 정확히 트리거되는 크론 배치 스케줄링 메서드
|
||||||
*/
|
*/
|
||||||
@Scheduled(cron = "0 5 0 * * *")
|
// 원래 0시 5분이었지만 NAS가 0~7시에 꺼져 있어 한 번도 못 돌았음 → 켜진 뒤 7시 10분에, 빠진 날을 모두 정산
|
||||||
|
@Scheduled(cron = "0 10 7 * * *", zone = "Asia/Seoul")
|
||||||
|
// 서버가 켜질 때(아침 7시 부팅·배포)도 한 번
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
public void runDailySettlementTask() {
|
public void runDailySettlementTask() {
|
||||||
// 정산 기준은 당연히 어제(하루 전) 날짜임
|
|
||||||
LocalDate yesterday = LocalDate.now().minusDays(1);
|
|
||||||
try {
|
try {
|
||||||
analyticsService.processDailySettlement(yesterday);
|
analyticsService.settleMissingDays();
|
||||||
log.info("🚀 [AUTO SCHEDULER] 일일 통계 무인 정산 작업이 성공적으로 종료되었습니다.");
|
log.info("🚀 [AUTO SCHEDULER] 일일 통계 정산 완료");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("🚨 [CRITICAL SCHEDULER ERROR] 자동 정산 도중 치명적인 시스템 오류 발생: ", e);
|
log.error("🚨 [SCHEDULER ERROR] 일일 통계 정산 실패: ", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,60 +8,117 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class AnalyticsService {
|
public class AnalyticsService {
|
||||||
|
|
||||||
|
/** 날짜 경계는 한국 시간 (서버 컨테이너는 UTC라 기본값을 쓰면 "오늘"이 오전 9시에 시작됨) */
|
||||||
|
public static final ZoneId ZONE = ZoneId.of("Asia/Seoul");
|
||||||
|
private static final long ONLINE_SECONDS = 5 * 60;
|
||||||
|
|
||||||
private final VisitorLogRepository visitorLogRepository;
|
private final VisitorLogRepository visitorLogRepository;
|
||||||
private final DailyVisitorStatsRepository dailyVisitorStatsRepository;
|
private final DailyVisitorStatsRepository dailyVisitorStatsRepository;
|
||||||
|
|
||||||
|
/** 지금 접속 중: IP별 마지막 요청 시각 (DB 기록은 1시간에 한 번이라 메모리로 따로 셈) */
|
||||||
|
private final Map<String, Instant> lastSeen = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
public record Counter(long today, long total, long online) {}
|
||||||
|
|
||||||
|
public record DayStat(LocalDate date, long visitors, long views) {}
|
||||||
|
|
||||||
|
public record AdminStats(long today, long todayViews, long total, long online, List<DayStat> days) {}
|
||||||
|
|
||||||
|
/** 요청마다 호출 (VisitorInterceptor) */
|
||||||
|
public void touch(String ip) {
|
||||||
|
lastSeen.put(ip, Instant.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 최근 5분 안에 요청한 IP 수 (오래된 항목은 이때 정리) */
|
||||||
|
public long online() {
|
||||||
|
Instant cut = Instant.now().minusSeconds(ONLINE_SECONDS);
|
||||||
|
lastSeen.values().removeIf(t -> t.isBefore(cut));
|
||||||
|
return lastSeen.size();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 관제 대시보드용 실시간 통계 카운트 맵 산출
|
* 관제 대시보드용 실시간 통계 카운트 맵 산출
|
||||||
*/
|
*/
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public Map<String, Long> getRealTimeDashboardStats() {
|
public Map<String, Long> getRealTimeDashboardStats() {
|
||||||
ZonedDateTime startOfToday = LocalDate.now().atStartOfDay(ZoneId.systemDefault());
|
|
||||||
ZonedDateTime fiveMinutesAgo = ZonedDateTime.now().minusMinutes(5);
|
|
||||||
|
|
||||||
Map<String, Long> statsMap = new HashMap<>();
|
Map<String, Long> statsMap = new HashMap<>();
|
||||||
statsMap.put("todayUnique", visitorLogRepository.countUniqueVisitorsToday(startOfToday));
|
statsMap.put("todayUnique", visitorLogRepository.countUniqueVisitorsToday(startOf(LocalDate.now(ZONE))));
|
||||||
statsMap.put("activeNow", visitorLogRepository.countActiveUsers(fiveMinutesAgo));
|
statsMap.put("activeNow", online());
|
||||||
|
|
||||||
return statsMap;
|
return statsMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 누구나 보는 방문자 카운터: 오늘 방문자, 전체 방문자(정산된 날들의 합 + 오늘), 지금 접속 */
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Counter counter() {
|
||||||
|
long today = visitorLogRepository.countUniqueVisitorsToday(startOf(LocalDate.now(ZONE)));
|
||||||
|
return new Counter(today, dailyVisitorStatsRepository.sumVisitors() + today, online());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 관리자 화면: 카운터 + 최근 14일 일별 방문자·조회 수 (오늘은 실시간 계산) */
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public AdminStats adminStats() {
|
||||||
|
LocalDate today = LocalDate.now(ZONE);
|
||||||
|
ZonedDateTime start = startOf(today);
|
||||||
|
long todayVisitors = visitorLogRepository.countUniqueVisitorsToday(start);
|
||||||
|
long todayViews = visitorLogRepository.countTotalPageViewsBetween(start, start.plusDays(1));
|
||||||
|
|
||||||
|
List<DayStat> days = new ArrayList<>();
|
||||||
|
days.add(new DayStat(today, todayVisitors, todayViews));
|
||||||
|
dailyVisitorStatsRepository.findByVisitDateBetweenOrderByVisitDateDesc(today.minusDays(13), today.minusDays(1))
|
||||||
|
.forEach(s -> days.add(new DayStat(s.getVisitDate(), s.getUniqueVisitorCount(), s.getPageViewCount())));
|
||||||
|
return new AdminStats(todayVisitors, todayViews, dailyVisitorStatsRepository.sumVisitors() + todayVisitors, online(), days);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 아직 정산 안 된 지난 날(최근 30일)을 모두 정산. 서버가 밤에 꺼져 있어 정해진 시각에 못 돌 수 있으므로
|
||||||
|
* 켜질 때와 아침에 "빠진 날 몰아서" 처리
|
||||||
|
*/
|
||||||
|
public void settleMissingDays() {
|
||||||
|
LocalDate today = LocalDate.now(ZONE);
|
||||||
|
for (LocalDate d = today.minusDays(30); d.isBefore(today); d = d.plusDays(1)) {
|
||||||
|
if (!dailyVisitorStatsRepository.existsById(d)) processDailySettlement(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 스케줄러 호출용 일일 결산 정산 실행 처리 비즈니스 로직
|
* 스케줄러 호출용 일일 결산 정산 실행 처리 비즈니스 로직
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public void processDailySettlement(LocalDate targetDate) {
|
public void processDailySettlement(LocalDate targetDate) {
|
||||||
// 어제 시작 시간(00:00:00) ~ 어제 끝 시간(23:59:59) 확보
|
ZonedDateTime startTimeline = startOf(targetDate);
|
||||||
ZonedDateTime startTimeline = targetDate.atStartOfDay(ZoneId.systemDefault());
|
|
||||||
ZonedDateTime endTimeline = startTimeline.plusDays(1);
|
ZonedDateTime endTimeline = startTimeline.plusDays(1);
|
||||||
|
|
||||||
// 연산 쿼리 수행
|
|
||||||
long uniqueVisitors = visitorLogRepository.countUniqueVisitorsBetween(startTimeline, endTimeline);
|
long uniqueVisitors = visitorLogRepository.countUniqueVisitorsBetween(startTimeline, endTimeline);
|
||||||
long totalPageViews = visitorLogRepository.countTotalPageViewsBetween(startTimeline, endTimeline);
|
long totalPageViews = visitorLogRepository.countTotalPageViewsBetween(startTimeline, endTimeline);
|
||||||
|
|
||||||
// 캐시 데이터베이스 빌드 및 세이브
|
|
||||||
DailyVisitorStats dailyStats = new DailyVisitorStats();
|
DailyVisitorStats dailyStats = new DailyVisitorStats();
|
||||||
dailyStats.setVisitDate(targetDate);
|
dailyStats.setVisitDate(targetDate);
|
||||||
dailyStats.setUniqueVisitorCount((int) uniqueVisitors);
|
dailyStats.setUniqueVisitorCount((int) uniqueVisitors);
|
||||||
dailyStats.setPageViewCount((int) totalPageViews);
|
dailyStats.setPageViewCount((int) totalPageViews);
|
||||||
|
|
||||||
dailyVisitorStatsRepository.save(dailyStats);
|
dailyVisitorStatsRepository.save(dailyStats);
|
||||||
log.info("📊 [ANALYTICS ENGINE] 날짜 [{}] 정산 스냅샷 세이브 완료 -> UV: {}, PV: {}", targetDate, uniqueVisitors, totalPageViews);
|
log.info("📊 [ANALYTICS ENGINE] 날짜 [{}] 정산 -> UV: {}, PV: {}", targetDate, uniqueVisitors, totalPageViews);
|
||||||
|
|
||||||
// 30일이 지나 쓸모없어진 원본 쓰레기 데이터 폐기 청소기 가동
|
// 30일 지난 상세 기록은 삭제 (일별 합계는 남음)
|
||||||
ZonedDateTime expirationThreshold = ZonedDateTime.now().minusDays(30);
|
visitorLogRepository.deleteOldLogsBefore(ZonedDateTime.now(ZONE).minusDays(30));
|
||||||
visitorLogRepository.deleteOldLogsBefore(expirationThreshold);
|
|
||||||
log.info("🗑️ [ANALYTICS ENGINE] 디비 하드디스크 무한 용량 방어를 위해 30일 경과 로그 원격 청소 완료.");
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private static ZonedDateTime startOf(LocalDate date) {
|
||||||
|
return date.atStartOfDay(ZONE);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,11 @@ public class UserService {
|
|||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
/** 관리자 화면을 쓸 수 있는 사용자 (role = ROLE_ADMIN) */
|
||||||
|
public boolean isAdmin(String username) {
|
||||||
|
return username != null && userRepository.findByUsername(username).map(u -> "ROLE_ADMIN".equals(u.getRole())).orElse(false);
|
||||||
|
}
|
||||||
|
|
||||||
public boolean login(String username, String password) {
|
public boolean login(String username, String password) {
|
||||||
Optional<User> userOptional = userRepository.findByUsername(username);
|
Optional<User> userOptional = userRepository.findByUsername(username);
|
||||||
|
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ class MediaPostControllerTest {
|
|||||||
@Autowired JwtTokenProvider jwt;
|
@Autowired JwtTokenProvider jwt;
|
||||||
@MockBean MediaPostRepository repository;
|
@MockBean MediaPostRepository repository;
|
||||||
@MockBean VisitorLogRepository visitorLogRepository;
|
@MockBean VisitorLogRepository visitorLogRepository;
|
||||||
|
@MockBean company.specialsource.service.AnalyticsService analyticsService; // VisitorInterceptor가 씀
|
||||||
|
|
||||||
MediaPost samplePost() {
|
MediaPost samplePost() {
|
||||||
return MediaPost.builder().id(1L).title("https://youtu.be/x").sourceUrl("https://youtu.be/x")
|
return MediaPost.builder().id(1L).title("https://youtu.be/x").sourceUrl("https://youtu.be/x")
|
||||||
|
|||||||
Reference in new issue
Block a user