From 31d89228a3f8aa410b506fdeb2a7d407747e271a Mon Sep 17 00:00:00 2001 From: GUARDiA Date: Sat, 20 Jun 2026 21:07:37 +0900 Subject: [PATCH] =?UTF-8?q?feat(uiws):=20UIWS=20=EC=97=85=EB=AC=B4?= =?UTF-8?q?=EB=AA=A8=EB=93=88(=EC=97=85=EB=AC=B4=EC=9D=BC=EC=A7=80=C2=B7?= =?UTF-8?q?=EC=9D=BC=EC=A0=95=C2=B7=EC=AA=BD=EC=A7=80=C2=B7=ED=86=B5?= =?UTF-8?q?=EA=B3=84)+2FA=20=EC=9D=B4=EC=8B=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 --- .gitignore | 5 + .../java/com/zioinfo/mes/ai/OllamaClient.java | 4 +- .../com/zioinfo/mes/auth/AuthController.java | 19 +- .../com/zioinfo/mes/auth/AuthService.java | 49 +- .../java/com/zioinfo/mes/auth/JwtFilter.java | 5 +- .../java/com/zioinfo/mes/auth/JwtUtil.java | 40 ++ .../java/com/zioinfo/mes/auth/MesUser.java | 14 + .../zioinfo/mes/auth/mapper/UserMapper.java | 38 ++ .../mes/uiws/auth/LoginVerifyMapper.java | 26 + .../mes/uiws/auth/TwoFactorService.java | 161 ++++++ .../mes/uiws/auth/UiwsLoginVerify.java | 19 + .../mes/uiws/common/UiwsApiException.java | 24 + .../mes/uiws/common/UiwsCurrentUser.java | 48 ++ .../mes/uiws/common/UiwsDataScope.java | 29 + .../mes/uiws/common/UiwsErrorCode.java | 48 ++ .../mes/uiws/common/mail/LogMailSender.java | 23 + .../mes/uiws/common/mail/MailSender.java | 10 + .../mes/uiws/config/UiwsProperties.java | 41 ++ .../message/controller/MessageController.java | 86 +++ .../mes/uiws/message/dto/MessageDtos.java | 100 ++++ .../uiws/message/mapper/MessageMapper.java | 78 +++ .../mes/uiws/message/model/UiwsMessage.java | 24 + .../uiws/message/model/UiwsMessageRcv.java | 22 + .../uiws/message/service/MessageService.java | 271 ++++++++++ .../controller/AttachmentController.java | 74 +++ .../schedule/controller/DiaryController.java | 60 +++ .../controller/ScheduleController.java | 78 +++ .../mes/uiws/schedule/dto/ScheduleDtos.java | 109 ++++ .../uiws/schedule/mapper/ScheduleMapper.java | 93 ++++ .../mes/uiws/schedule/model/UiwsAttach.java | 19 + .../mes/uiws/schedule/model/UiwsDiary.java | 20 + .../mes/uiws/schedule/model/UiwsSchedule.java | 24 + .../schedule/service/AttachmentService.java | 121 +++++ .../uiws/schedule/service/DiaryService.java | 133 +++++ .../schedule/service/FileStorageService.java | 93 ++++ .../schedule/service/ScheduleService.java | 216 ++++++++ .../stats/controller/StatsController.java | 48 ++ .../zioinfo/mes/uiws/stats/dto/StatsDtos.java | 25 + .../mes/uiws/stats/mapper/StatsMapper.java | 36 ++ .../mes/uiws/stats/service/StatsService.java | 165 ++++++ .../worklog/controller/WorklogController.java | 108 ++++ .../mes/uiws/worklog/dto/WorklogDtos.java | 118 ++++ .../uiws/worklog/mapper/WorklogMapper.java | 96 ++++ .../mes/uiws/worklog/model/UiwsWorklog.java | 23 + .../uiws/worklog/model/UiwsWorklogCmt.java | 19 + .../uiws/worklog/model/UiwsWorklogDtl.java | 22 + .../uiws/worklog/service/WorklogNotifier.java | 31 ++ .../uiws/worklog/service/WorklogService.java | 438 +++++++++++++++ backend/src/main/resources/application.yml | 20 +- .../src/main/resources/db/91_uiws_port.sql | 251 +++++++++ .../src/main/resources/mapper/UserMapper.xml | 10 +- .../mapper/uiws/LoginVerifyMapper.xml | 16 + .../resources/mapper/uiws/MessageMapper.xml | 137 +++++ .../resources/mapper/uiws/ScheduleMapper.xml | 168 ++++++ .../resources/mapper/uiws/StatsMapper.xml | 48 ++ .../resources/mapper/uiws/WorklogMapper.xml | 181 +++++++ .../resources/static/assets/index-BLHiicbF.js | 480 ----------------- .../static/assets/index-BwkEm3xg.css | 1 - .../resources/static/assets/index-DOZiCYTH.js | 510 ++++++++++++++++++ .../static/assets/index-i_K9xe48.css | 1 + backend/src/main/resources/static/index.html | 4 +- frontend/src/App.tsx | 10 + frontend/src/api/client.ts | 2 +- frontend/src/api/uiws.ts | 66 +++ frontend/src/components/Sidebar.tsx | 16 +- frontend/src/components/uiws/ThemeToggle.tsx | 16 + frontend/src/components/uiws/ui.tsx | 171 ++++++ frontend/src/main.tsx | 6 +- frontend/src/pages/Login.tsx | 99 +++- frontend/src/pages/uiws/MessageBox.tsx | 118 ++++ frontend/src/pages/uiws/ScheduleCalendar.tsx | 121 +++++ frontend/src/pages/uiws/StatsPivot.tsx | 74 +++ frontend/src/pages/uiws/WorklogList.tsx | 153 ++++++ frontend/src/theme/ThemeContext.tsx | 38 ++ frontend/src/theme/theme.css | 52 ++ 75 files changed, 5606 insertions(+), 516 deletions(-) create mode 100644 .gitignore create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/auth/LoginVerifyMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/auth/TwoFactorService.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/auth/UiwsLoginVerify.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsApiException.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsCurrentUser.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsDataScope.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsErrorCode.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/common/mail/LogMailSender.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/common/mail/MailSender.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/config/UiwsProperties.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/message/controller/MessageController.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/message/dto/MessageDtos.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/message/mapper/MessageMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/message/model/UiwsMessage.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/message/model/UiwsMessageRcv.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/message/service/MessageService.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/AttachmentController.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/DiaryController.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/ScheduleController.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/dto/ScheduleDtos.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/mapper/ScheduleMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsAttach.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsDiary.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsSchedule.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/AttachmentService.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/DiaryService.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/FileStorageService.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/ScheduleService.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/stats/controller/StatsController.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/stats/dto/StatsDtos.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/stats/mapper/StatsMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/stats/service/StatsService.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/worklog/controller/WorklogController.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/worklog/dto/WorklogDtos.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/worklog/mapper/WorklogMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklog.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklogCmt.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklogDtl.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/worklog/service/WorklogNotifier.java create mode 100644 backend/src/main/java/com/zioinfo/mes/uiws/worklog/service/WorklogService.java create mode 100644 backend/src/main/resources/db/91_uiws_port.sql create mode 100644 backend/src/main/resources/mapper/uiws/LoginVerifyMapper.xml create mode 100644 backend/src/main/resources/mapper/uiws/MessageMapper.xml create mode 100644 backend/src/main/resources/mapper/uiws/ScheduleMapper.xml create mode 100644 backend/src/main/resources/mapper/uiws/StatsMapper.xml create mode 100644 backend/src/main/resources/mapper/uiws/WorklogMapper.xml delete mode 100644 backend/src/main/resources/static/assets/index-BLHiicbF.js delete mode 100644 backend/src/main/resources/static/assets/index-BwkEm3xg.css create mode 100644 backend/src/main/resources/static/assets/index-DOZiCYTH.js create mode 100644 backend/src/main/resources/static/assets/index-i_K9xe48.css create mode 100644 frontend/src/api/uiws.ts create mode 100644 frontend/src/components/uiws/ThemeToggle.tsx create mode 100644 frontend/src/components/uiws/ui.tsx create mode 100644 frontend/src/pages/uiws/MessageBox.tsx create mode 100644 frontend/src/pages/uiws/ScheduleCalendar.tsx create mode 100644 frontend/src/pages/uiws/StatsPivot.tsx create mode 100644 frontend/src/pages/uiws/WorklogList.tsx create mode 100644 frontend/src/theme/ThemeContext.tsx create mode 100644 frontend/src/theme/theme.css diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4a7af35 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ + +target/ +backend/target/ +node_modules/ +frontend/dist/ diff --git a/backend/src/main/java/com/zioinfo/mes/ai/OllamaClient.java b/backend/src/main/java/com/zioinfo/mes/ai/OllamaClient.java index e3844b1..2677f22 100644 --- a/backend/src/main/java/com/zioinfo/mes/ai/OllamaClient.java +++ b/backend/src/main/java/com/zioinfo/mes/ai/OllamaClient.java @@ -44,7 +44,7 @@ public class OllamaClient { .bodyValue(body) .retrieve() .bodyToMono(Map.class) - .timeout(Duration.ofSeconds(30)) + .timeout(Duration.ofSeconds(120)) .map(m -> (Map) m) .block(); if (res == null) return ""; @@ -70,7 +70,7 @@ public class OllamaClient { .bodyValue(body) .retrieve() .bodyToMono(Map.class) - .timeout(Duration.ofSeconds(45)) + .timeout(Duration.ofSeconds(120)) .map(m -> (Map) m) .block(); if (res == null) return ""; diff --git a/backend/src/main/java/com/zioinfo/mes/auth/AuthController.java b/backend/src/main/java/com/zioinfo/mes/auth/AuthController.java index cb500bf..47eb448 100644 --- a/backend/src/main/java/com/zioinfo/mes/auth/AuthController.java +++ b/backend/src/main/java/com/zioinfo/mes/auth/AuthController.java @@ -1,22 +1,35 @@ package com.zioinfo.mes.auth; import com.zioinfo.mes.common.ApiResponse; +import com.zioinfo.mes.uiws.auth.TwoFactorService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import java.util.Map; +/** + * MES 인증 컨트롤러. + * - /login: 2FA off 면 { token, type, twofa:"false" }, 2FA on 이면 { twofa:"true", verifyToken, step, maskedEmail }. + * - /verify: (UIWS 2FA 이식) verify-token + 인증코드 → access/refresh 발급. + * 기존 클라이언트(2FA off)는 응답 형태 token 보존 → 회귀 0. + */ @RestController @RequestMapping("/api/mes/auth") @RequiredArgsConstructor public class AuthController { private final AuthService authService; + private final TwoFactorService twoFactorService; @PostMapping("/login") public ApiResponse> login(@RequestBody LoginRequest req) { - String token = authService.login(req.username(), req.password()); - return ApiResponse.ok(Map.of("token", token, "type", "Bearer")); + return ApiResponse.ok(authService.login(req.username(), req.password())); + } + + /** UIWS 2FA 이식: 2차 인증 코드 검증 → access/refresh 발급. */ + @PostMapping("/verify") + public ApiResponse> verify(@RequestBody VerifyRequest req) { + return ApiResponse.ok(twoFactorService.verify(req.verifyToken(), req.code())); } @GetMapping("/me") @@ -26,4 +39,6 @@ public class AuthController { } record LoginRequest(String username, String password) {} + + record VerifyRequest(String verifyToken, String code) {} } diff --git a/backend/src/main/java/com/zioinfo/mes/auth/AuthService.java b/backend/src/main/java/com/zioinfo/mes/auth/AuthService.java index da7156b..380469a 100644 --- a/backend/src/main/java/com/zioinfo/mes/auth/AuthService.java +++ b/backend/src/main/java/com/zioinfo/mes/auth/AuthService.java @@ -1,6 +1,9 @@ package com.zioinfo.mes.auth; import com.zioinfo.mes.auth.mapper.UserMapper; +import com.zioinfo.mes.uiws.auth.TwoFactorService; +import com.zioinfo.mes.uiws.common.UiwsApiException; +import com.zioinfo.mes.uiws.common.UiwsErrorCode; import lombok.RequiredArgsConstructor; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @@ -8,6 +11,12 @@ import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; +/** + * MES 인증 서비스. + * - 기존 단일 JWT 로그인 보존(2FA off 또는 미설정 시 회귀 0). + * - UIWS 2FA 레이어(이메일 코드) 추가: 2FA on 이면 1차 통과 후 verify-token + 이메일코드 발급. + * 실패 누적 max-login-fail 회 시 계정 잠금. + */ @Service @RequiredArgsConstructor public class AuthService { @@ -15,16 +24,52 @@ public class AuthService { private final UserMapper userMapper; private final PasswordEncoder passwordEncoder; private final JwtUtil jwtUtil; + private final TwoFactorService twoFactorService; - public String login(String username, String password) { + /** + * 1차 로그인. 2FA 활성 시 verify-token + 이메일코드 흐름으로 분기, + * 비활성 시 기존처럼 access 토큰 즉시 발급. + * + * @return 2FA off: { token, type, twofa:"false" } + * 2FA on : { verifyToken, step:"EMAIL", maskedEmail, twofa:"true" } + */ + public Map login(String username, String password) { MesUser user = userMapper.findByUsername(username); + + // 잠금 우선 차단(존재하는 계정에 한해 잠금 메시지 — 존재 여부 누설 최소화) + if (user != null && twoFactorService.isLocked(user)) { + throw new UiwsApiException(UiwsErrorCode.ACCOUNT_LOCKED); + } if (user == null || !user.isActive()) { throw new RuntimeException("ERR-AUTH-001: 존재하지 않거나 비활성 계정"); } if (!passwordEncoder.matches(password, user.getPasswordHash())) { + // 2FA 활성 시 실패 누적/잠금. 비활성 시 기존 동작(메시지만) 유지. + if (twoFactorService.isEnabled()) { + twoFactorService.recordLoginFailure(username); + MesUser after = userMapper.findByUsername(username); + if (after != null && Boolean.TRUE.equals(after.getLocked())) { + throw new UiwsApiException(UiwsErrorCode.ACCOUNT_LOCKED); + } + } throw new RuntimeException("ERR-AUTH-002: 비밀번호 불일치"); } - return jwtUtil.generate(username, user.getRole()); + + // 비밀번호 검증 통과 + if (twoFactorService.isEnabled()) { + Map step1 = twoFactorService.beginTwoFactor(user); + // verifyToken/step/maskedEmail + twofa 플래그 + return Map.of( + "twofa", "true", + "verifyToken", step1.get("verifyToken"), + "step", step1.get("step"), + "maskedEmail", step1.getOrDefault("maskedEmail", "")); + } + + // 2FA 비활성 — 기존 단일 로그인 흐름(회귀 0) + userMapper.resetLoginFail(username); + String token = jwtUtil.generate(username, user.getRole()); + return Map.of("twofa", "false", "token", token, "type", "Bearer"); } public Map me(String token) { diff --git a/backend/src/main/java/com/zioinfo/mes/auth/JwtFilter.java b/backend/src/main/java/com/zioinfo/mes/auth/JwtFilter.java index b1897e3..b660f8d 100644 --- a/backend/src/main/java/com/zioinfo/mes/auth/JwtFilter.java +++ b/backend/src/main/java/com/zioinfo/mes/auth/JwtFilter.java @@ -26,7 +26,10 @@ public class JwtFilter extends OncePerRequestFilter { String header = req.getHeader("Authorization"); if (header != null && header.startsWith("Bearer ")) { String token = header.substring(7); - if (jwtUtil.isValid(token)) { + // 보안(UIWS 2FA): purpose=2fa verify-token 은 access 토큰이 아니다. + // 동일 서명키라 isValid()는 통과하므로 별도 차단하지 않으면 2차 인증 전 API 접근(2FA 우회)이 가능. + // → verify-token 은 인증 컨텍스트를 세우지 않고 무시한다(/api/mes/auth/verify 에서만 사용). + if (jwtUtil.isValid(token) && !jwtUtil.isVerifyToken(token)) { String username = jwtUtil.getUsername(token); String role = jwtUtil.getRole(token); var auth = new UsernamePasswordAuthenticationToken( diff --git a/backend/src/main/java/com/zioinfo/mes/auth/JwtUtil.java b/backend/src/main/java/com/zioinfo/mes/auth/JwtUtil.java index 70cc21e..29eb3de 100644 --- a/backend/src/main/java/com/zioinfo/mes/auth/JwtUtil.java +++ b/backend/src/main/java/com/zioinfo/mes/auth/JwtUtil.java @@ -34,6 +34,46 @@ public class JwtUtil { .compact(); } + /** + * UIWS 2FA 이식: 1차 로그인 통과 후 발급하는 단기 verify-token. + * purpose=2fa 클레임으로 access 토큰과 구분(verify-token 으로는 API 접근 불가). + */ + public String generateVerifyToken(String username, long validitySeconds) { + return Jwts.builder() + .subject(username) + .claim("purpose", "2fa") + .issuedAt(new Date()) + .expiration(new Date(System.currentTimeMillis() + validitySeconds * 1000L)) + .signWith(key()) + .compact(); + } + + /** verify-token 검증 후 username 반환. 유효하지 않거나 purpose!=2fa 면 null. */ + public String parseVerifyTokenUsername(String token) { + try { + Claims c = parse(token); + if (!"2fa".equals(c.get("purpose", String.class))) { + return null; + } + return c.getSubject(); + } catch (JwtException | IllegalArgumentException e) { + log.debug("verify-token 검증 실패: {}", e.getMessage()); + return null; + } + } + + /** + * 보안: 토큰이 2FA verify-token(purpose=2fa)인지 판별. + * JwtFilter 가 access 토큰만 인증 컨텍스트로 인정하도록 verify-token 을 걸러내는 데 사용. + */ + public boolean isVerifyToken(String token) { + try { + return "2fa".equals(parse(token).get("purpose", String.class)); + } catch (JwtException | IllegalArgumentException e) { + return false; + } + } + public Claims parse(String token) { return Jwts.parser().verifyWith(key()).build() .parseSignedClaims(token).getPayload(); diff --git a/backend/src/main/java/com/zioinfo/mes/auth/MesUser.java b/backend/src/main/java/com/zioinfo/mes/auth/MesUser.java index c4f97c0..58282b4 100644 --- a/backend/src/main/java/com/zioinfo/mes/auth/MesUser.java +++ b/backend/src/main/java/com/zioinfo/mes/auth/MesUser.java @@ -17,4 +17,18 @@ public class MesUser { private String role; private boolean active; private LocalDateTime createdAt; + + // ── UIWS 2FA 이식 (mes_user ALTER, db/91_uiws_port.sql) ───────────────────── + /** 2FA 발송 대상 이메일. mes_user 원본 미보유 → 91_uiws_port.sql ALTER 로 추가. */ + private String email; + /** 이메일 인증코드(6자리). 발급 후 verify 단계에서 검증. API 응답에는 절대 미포함. */ + private String emailVerifyCode; + /** 인증코드 만료시각. */ + private LocalDateTime emailVerifyExpire; + /** 로그인 실패 누적 횟수(기본 0). max-login-fail 도달 시 locked. */ + private Integer loginFailCount; + /** 계정 잠금 여부(기본 false). */ + private Boolean locked; + /** TOTP 시크릿(UIWS OTP 경로 대비, 현재 이메일 흐름에서는 미사용). */ + private String otpSecret; } diff --git a/backend/src/main/java/com/zioinfo/mes/auth/mapper/UserMapper.java b/backend/src/main/java/com/zioinfo/mes/auth/mapper/UserMapper.java index a095b8b..3c1af9e 100644 --- a/backend/src/main/java/com/zioinfo/mes/auth/mapper/UserMapper.java +++ b/backend/src/main/java/com/zioinfo/mes/auth/mapper/UserMapper.java @@ -3,11 +3,49 @@ package com.zioinfo.mes.auth.mapper; import com.zioinfo.mes.auth.MesUser; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDateTime; @Mapper public interface UserMapper { + // findByUsername / insert 는 mapper/UserMapper.xml 에 정의(2FA 컬럼 포함 resultMap). + // 어노테이션 중복 정의 시 "statement already contains value" 크래시 → XML 유지. MesUser findByUsername(@Param("username") String username); int insert(MesUser user); + + // ── UIWS 2FA 이식: 실패 카운트/잠금/인증코드 갱신 (멱등 UPDATE) ─────────────── + + /** 로그인 성공 시 실패 카운트 초기화. */ + @Update("UPDATE mes_user SET login_fail_count = 0 WHERE username = #{username}") + int resetLoginFail(@Param("username") String username); + + /** 로그인 실패 누적(+1) 및 임계 도달 시 잠금. */ + @Update(""" + UPDATE mes_user + SET login_fail_count = COALESCE(login_fail_count, 0) + 1, + locked = (COALESCE(login_fail_count, 0) + 1 >= #{maxFail}) + WHERE username = #{username} + """) + int incrementLoginFail(@Param("username") String username, @Param("maxFail") int maxFail); + + /** 1차 통과 시 이메일 인증코드/만료 저장(verify 단계에서 검증). */ + @Update(""" + UPDATE mes_user + SET email_verify_code = #{code}, email_verify_expire = #{expire}, login_fail_count = 0 + WHERE username = #{username} + """) + int saveEmailCode(@Param("username") String username, + @Param("code") String code, + @Param("expire") LocalDateTime expire); + + /** 2차 검증 성공 시 코드 폐기. */ + @Update("UPDATE mes_user SET email_verify_code = NULL, email_verify_expire = NULL WHERE username = #{username}") + int clearEmailCode(@Param("username") String username); + + /** 관리자 잠금 해제(실패 카운트/잠금 초기화). */ + @Update("UPDATE mes_user SET locked = false, login_fail_count = 0 WHERE username = #{username}") + int unlock(@Param("username") String username); } diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/auth/LoginVerifyMapper.java b/backend/src/main/java/com/zioinfo/mes/uiws/auth/LoginVerifyMapper.java new file mode 100644 index 0000000..22e716f --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/auth/LoginVerifyMapper.java @@ -0,0 +1,26 @@ +package com.zioinfo.mes.uiws.auth; + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Update; + +/** + * 2FA 로그인 검증 이력 매퍼 (tb_uiws_login_verify). 발급/검증 감사 기록. + * verify_code 는 감사 이력에만 남고 API 응답에는 절대 노출하지 않는다. + */ +@Mapper +public interface LoginVerifyMapper { + + int insert(UiwsLoginVerify v); + + /** 동일 user 의 미검증 EMAIL 이력 중 최신 1건을 검증완료(Y) 처리. */ + @Update(""" + UPDATE tb_uiws_login_verify + SET verified_yn = 'Y', updated_by = #{userId}, updated_at = now() + WHERE verify_id = ( + SELECT verify_id FROM tb_uiws_login_verify + WHERE user_id = #{userId} AND verify_method = 'EMAIL' AND verified_yn = 'N' + ORDER BY verify_id DESC LIMIT 1 + ) + """) + int markLatestVerified(String userId); +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/auth/TwoFactorService.java b/backend/src/main/java/com/zioinfo/mes/uiws/auth/TwoFactorService.java new file mode 100644 index 0000000..4ccbdf6 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/auth/TwoFactorService.java @@ -0,0 +1,161 @@ +package com.zioinfo.mes.uiws.auth; + +import com.zioinfo.mes.auth.JwtUtil; +import com.zioinfo.mes.auth.mapper.UserMapper; +import com.zioinfo.mes.auth.MesUser; +import com.zioinfo.mes.uiws.common.UiwsApiException; +import com.zioinfo.mes.uiws.common.UiwsErrorCode; +import com.zioinfo.mes.uiws.common.mail.MailSender; +import com.zioinfo.mes.uiws.config.UiwsProperties; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.security.SecureRandom; +import java.time.LocalDateTime; +import java.util.Map; + +/** + * UIWS 2FA(이메일 코드) 레이어. ERP 기존 단일 로그인을 보존하면서 2단계 인증을 추가한다. + * + * 흐름: + * 1) 1차 로그인 성공 → {@link #beginTwoFactor}: verify-token 발급 + 이메일 인증코드 발송(LogMailSender 폴백) + 감사 기록. + * 2) {@code POST /api/auth/verify}(verifyToken + code) → {@link #verify}: 코드 검증 후 access/refresh 발급. + * 3) 로그인 실패 누적 max-login-fail 회 → 계정 잠금({@link #recordLoginFailure}). + * + * 보안: + * - 인증코드는 메일/감사 채널로만 전달. API 응답·로그 메시지에 코드/비밀번호/자격증명 절대 미노출(불변규칙). + * - 외부 API 호출 없음(MailSender 폴백은 로그). Ollama 외 외부 통신 금지 준수. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class TwoFactorService { + + private static final SecureRandom RANDOM = new SecureRandom(); + private static final String SYSTEM = "SYSTEM"; + + private final UserMapper userMapper; + private final LoginVerifyMapper loginVerifyMapper; + private final JwtUtil jwtUtil; + private final MailSender mailSender; + private final UiwsProperties properties; + + public boolean isEnabled() { + return properties.getAuth().isTwofaEnabled(); + } + + /** 잠금 여부(1차 로그인 전 차단용). */ + public boolean isLocked(MesUser user) { + return Boolean.TRUE.equals(user.getLocked()); + } + + /** + * 1차 로그인 성공 후 2차 인증 시작: verify-token 발급 + 이메일코드 발송 + 감사 기록 + 실패카운트 초기화. + * @return { verifyToken, step:"EMAIL", maskedEmail } + */ + @Transactional + public Map beginTwoFactor(MesUser user) { + long codeValidity = properties.getAuth().getEmailCodeValiditySeconds(); + long tokenValidity = properties.getAuth().getVerifyTokenValiditySeconds(); + + String code = String.format("%06d", RANDOM.nextInt(1_000_000)); + LocalDateTime expire = LocalDateTime.now().plusSeconds(codeValidity); + + // user 테이블에 코드/만료 저장(실패카운트 초기화) + 감사 이력 기록 + userMapper.saveEmailCode(user.getUsername(), code, expire); + recordVerifyAttempt(user.getUsername(), code, expire); + + // 이메일 발송(미설정 환경은 LogMailSender 폴백). 코드는 메일 본문에만. + String subject = "[GUARDiA MES] 로그인 2차 인증 코드"; + String body = String.format( + "안녕하세요 %s 님,\n로그인 2차 인증 코드는 [%s] 입니다.\n유효시간: %d초", + user.getDisplayName() != null ? user.getDisplayName() : user.getUsername(), code, codeValidity); + if (user.getEmail() != null && !user.getEmail().isBlank()) { + mailSender.send(user.getEmail(), subject, body); + } else { + log.warn("[2FA] no email for user={} — code logged only", user.getUsername()); + } + + String verifyToken = jwtUtil.generateVerifyToken(user.getUsername(), tokenValidity); + // 응답에는 코드 미포함 — verifyToken/step/maskedEmail 만. + return Map.of( + "verifyToken", verifyToken, + "step", "EMAIL", + "maskedEmail", maskEmail(user.getEmail())); + } + + /** + * 2차 검증: verify-token + code 검증 → access/refresh 발급. 코드 폐기 + 감사 이력 검증완료. + * @return { token, refreshToken, username, role } + */ + @Transactional + public Map verify(String verifyToken, String code) { + String username = jwtUtil.parseVerifyTokenUsername(verifyToken); + if (username == null) { + throw new UiwsApiException(UiwsErrorCode.VERIFY_TOKEN_INVALID); + } + MesUser user = userMapper.findByUsername(username); + if (user == null) { + throw new UiwsApiException(UiwsErrorCode.VERIFY_TOKEN_INVALID); + } + if (Boolean.TRUE.equals(user.getLocked())) { + throw new UiwsApiException(UiwsErrorCode.ACCOUNT_LOCKED); + } + + boolean codeOk = user.getEmailVerifyCode() != null + && user.getEmailVerifyCode().equals(code) + && user.getEmailVerifyExpire() != null + && user.getEmailVerifyExpire().isAfter(LocalDateTime.now()); + if (!codeOk) { + throw new UiwsApiException(UiwsErrorCode.VERIFY_CODE_INVALID); + } + + // 코드 폐기 + 감사 검증완료 + userMapper.clearEmailCode(username); + loginVerifyMapper.markLatestVerified(username); + + String access = jwtUtil.generate(user.getUsername(), user.getRole()); + // refresh 토큰: ERP 기존 access 토큰 정책 재사용(별도 refresh 정책 부재 → 동일 발급). + String refresh = jwtUtil.generate(user.getUsername(), user.getRole()); + return Map.of( + "token", access, + "refreshToken", refresh, + "type", "Bearer", + "username", user.getUsername(), + "role", user.getRole() == null ? "" : user.getRole()); + } + + /** 로그인 비밀번호 실패 시 누적/잠금 처리. */ + @Transactional + public void recordLoginFailure(String username) { + userMapper.incrementLoginFail(username, properties.getAuth().getMaxLoginFail()); + } + + private void recordVerifyAttempt(String username, String code, LocalDateTime expire) { + UiwsLoginVerify v = new UiwsLoginVerify(); + v.setUserId(username); + v.setVerifyMethod("EMAIL"); + v.setVerifyCode(code); + v.setExpireAt(expire); + v.setVerifiedYn("N"); + v.setCreatedBy(SYSTEM); + v.setCreatedAt(LocalDateTime.now()); + loginVerifyMapper.insert(v); + } + + /** 이메일 마스킹(자격증명 보호): ab****@domain. */ + private static String maskEmail(String email) { + if (email == null || email.isBlank() || !email.contains("@")) { + return ""; + } + int at = email.indexOf('@'); + String local = email.substring(0, at); + String domain = email.substring(at); + if (local.length() <= 2) { + return local.charAt(0) + "*" + domain; + } + return local.substring(0, 2) + "*".repeat(Math.max(1, local.length() - 2)) + domain; + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/auth/UiwsLoginVerify.java b/backend/src/main/java/com/zioinfo/mes/uiws/auth/UiwsLoginVerify.java new file mode 100644 index 0000000..c9e8314 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/auth/UiwsLoginVerify.java @@ -0,0 +1,19 @@ +package com.zioinfo.mes.uiws.auth; + +import lombok.Data; +import java.time.LocalDateTime; + +/** 2FA 로그인 검증 이력 (tb_uiws_login_verify). 원본 com.urp.uiws.domain.LoginVerify 이식. */ +@Data +public class UiwsLoginVerify { + private Long verifyId; + private String userId; // ERP username 논리참조 + private String verifyMethod; // EMAIL | OTP + private String verifyCode; + private LocalDateTime expireAt; + private String verifiedYn; // Y | N + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsApiException.java b/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsApiException.java new file mode 100644 index 0000000..31a49b2 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsApiException.java @@ -0,0 +1,24 @@ +package com.zioinfo.mes.uiws.common; + +import lombok.Getter; + +/** + * UIWS 이식 모듈 업무 예외. RuntimeException 을 상속하여 ERP 기존 GlobalExceptionHandler + * (RuntimeException → 400 + message, 스택트레이스 미노출)에 그대로 포착된다. + * 추가 인프라/빈 없이 ERP 공통 에러 처리와 정합한다. + */ +@Getter +public class UiwsApiException extends RuntimeException { + + private final UiwsErrorCode errorCode; + + public UiwsApiException(UiwsErrorCode errorCode) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + } + + public UiwsApiException(UiwsErrorCode errorCode, String detail) { + super(detail); + this.errorCode = errorCode; + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsCurrentUser.java b/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsCurrentUser.java new file mode 100644 index 0000000..fcdb060 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsCurrentUser.java @@ -0,0 +1,48 @@ +package com.zioinfo.mes.uiws.common; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * 현재 인증 사용자 식별자(=ERP username) 추출 헬퍼. 감사 컬럼(created_by/updated_by) 및 + * 소유자(writer_id/owner_id/sender_id) 기록에 사용한다. + * + * ERP JwtFilter 는 인증 principal 로 username(String)을 세팅하므로 그 값을 그대로 사용한다. + * (UIWS 원본의 CurrentUser/UserPrincipal 패턴을 ERP 인증 모델에 맞게 단순화 이식.) + */ +public final class UiwsCurrentUser { + + private static final String SYSTEM = "SYSTEM"; + + private UiwsCurrentUser() { + } + + /** 현재 사용자 ID(username). 미인증/시스템 컨텍스트는 "SYSTEM". */ + public static String id() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof String username + && !"anonymousUser".equals(username)) { + return username; + } + return SYSTEM; + } + + /** ADMIN 권한 보유 여부(데이터 가시범위 판정용 — ADMIN=전체). */ + public static boolean isAdmin() { + return hasRole("ADMIN"); + } + + /** MANAGER 이상(MANAGER/ADMIN) 여부 — 업무일지 댓글 권한 등에 사용. */ + public static boolean isManagerOrAbove() { + return hasRole("ADMIN") || hasRole("MANAGER") || hasRole("CFO"); + } + + private static boolean hasRole(String role) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null) { + return false; + } + return auth.getAuthorities().stream() + .anyMatch(a -> ("ROLE_" + role).equals(a.getAuthority())); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsDataScope.java b/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsDataScope.java new file mode 100644 index 0000000..0cc4b5f --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsDataScope.java @@ -0,0 +1,29 @@ +package com.zioinfo.mes.uiws.common; + +import java.util.List; + +/** + * 데이터 가시범위(스코프) — UIWS DataScopeService 의 silo 단순화 이식. + * 원본은 부서계층(TB_DEPT) 기반 팀 스코프를 산출하나, ERP 이식본은 코어 dept 테이블을 이식하지 않으므로 + * 역할만으로 판정한다: + * - ADMIN → 전체(all=true) + * - 그 외 → 본인 데이터만(ownerIds = [본인]) + * (부서계층 스코프가 필요해지면 ERP tb_department 연계로 확장 — 후속 트랙.) + */ +public final class UiwsDataScope { + + private UiwsDataScope() { + } + + /** all=true 면 전체 조회(ownerIds 무시). ownerIds 는 항상 본인 포함(빈 IN 회피). */ + public record Scope(boolean all, List ownerIds) { + } + + public static Scope current() { + String me = UiwsCurrentUser.id(); + if (UiwsCurrentUser.isAdmin()) { + return new Scope(true, List.of(me)); + } + return new Scope(false, List.of(me)); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsErrorCode.java b/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsErrorCode.java new file mode 100644 index 0000000..96eb780 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/common/UiwsErrorCode.java @@ -0,0 +1,48 @@ +package com.zioinfo.mes.uiws.common; + +import lombok.Getter; + +/** + * UIWS 이식 모듈 도메인 오류 코드. + * 원본 com.urp.uiws.common.exception.ErrorCode 의 worklog/schedule/message/auth(2FA) 영역 발췌·이식. + * 메시지는 사용자 노출용 — 스택트레이스/SQL 등 민감정보는 절대 포함하지 않는다(보안 불변규칙). + */ +@Getter +public enum UiwsErrorCode { + + // 공통 + INVALID_REQUEST("ERR-UIWS-400", "요청이 올바르지 않습니다."), + FORBIDDEN("ERR-UIWS-403", "접근 권한이 없습니다."), + NOT_FOUND("ERR-UIWS-404", "대상을 찾을 수 없습니다."), + + // worklog + WORKLOG_NOT_FOUND("ERR-UIWS-WL-404", "업무일지를 찾을 수 없습니다."), + WORKLOG_TIME_OVERLAP("ERR-UIWS-WL-409", "동일 일지 내 시간대가 중복됩니다."), + WORKLOG_TIME_INVALID("ERR-UIWS-WL-422", "근무 시작/종료 시간이 올바르지 않습니다."), + + // schedule + SCHEDULE_NOT_FOUND("ERR-UIWS-SC-404", "일정을 찾을 수 없습니다."), + SCHEDULE_DT_INVALID("ERR-UIWS-SC-422", "일정 시작/종료 일시가 올바르지 않습니다."), + DIARY_NOT_FOUND("ERR-UIWS-DI-404", "일지를 찾을 수 없습니다."), + ATTACH_NOT_FOUND("ERR-UIWS-AT-404", "첨부파일을 찾을 수 없습니다."), + ATTACH_REF_TYPE_INVALID("ERR-UIWS-AT-422", "첨부 대상 유형은 SCHEDULE 또는 DIARY 여야 합니다."), + FILE_EMPTY("ERR-UIWS-FILE-400", "업로드할 파일이 비어 있습니다."), + FILE_STORAGE_ERROR("ERR-UIWS-FILE-500", "파일 저장 중 오류가 발생했습니다."), + + // message + MESSAGE_NOT_FOUND("ERR-UIWS-MSG-404", "쪽지를 찾을 수 없습니다."), + MESSAGE_RCV_TYPE_INVALID("ERR-UIWS-MSG-422", "수신구분은 RECV(수신) 또는 REF(참조) 여야 합니다."), + + // auth (2FA) + VERIFY_TOKEN_INVALID("ERR-UIWS-2FA-401", "2차 검증 토큰이 유효하지 않거나 만료되었습니다."), + VERIFY_CODE_INVALID("ERR-UIWS-2FA-401C", "인증 코드가 올바르지 않거나 만료되었습니다."), + ACCOUNT_LOCKED("ERR-UIWS-2FA-LOCK", "로그인 실패 횟수 초과로 계정이 잠겼습니다. 관리자에게 문의하세요."); + + private final String code; + private final String message; + + UiwsErrorCode(String code, String message) { + this.code = code; + this.message = message; + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/common/mail/LogMailSender.java b/backend/src/main/java/com/zioinfo/mes/uiws/common/mail/LogMailSender.java new file mode 100644 index 0000000..b6dd96f --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/common/mail/LogMailSender.java @@ -0,0 +1,23 @@ +package com.zioinfo.mes.uiws.common.mail; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** + * 로컬/개발/미설정용 메일 발송 폴백. 실제 전송 없이 로그로만 기록한다(외부 호출 0). + * mes.uiws.mail.mode=log (기본) 일 때 활성. SMTP 운영 시 mode=smtp 로 별도 구현 빈 활성화. + * + * 보안: 본문에 인증코드/임시비밀번호가 포함되므로 로그 레벨은 운영에서 조정. + * (인증코드는 API 응답으로는 절대 반환하지 않는다 — 메일/로그 채널로만 전달.) + */ +@Slf4j +@Component +@ConditionalOnProperty(name = "mes.uiws.mail.mode", havingValue = "log", matchIfMissing = true) +public class LogMailSender implements MailSender { + + @Override + public void send(String to, String subject, String body) { + log.info("[UIWS-MAIL:LOG] to={} subject={}\n{}", to, subject, body); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/common/mail/MailSender.java b/backend/src/main/java/com/zioinfo/mes/uiws/common/mail/MailSender.java new file mode 100644 index 0000000..ec3a4a6 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/common/mail/MailSender.java @@ -0,0 +1,10 @@ +package com.zioinfo.mes.uiws.common.mail; + +/** + * 메일 발송 추상화(UIWS 이식). 로컬/미설정 환경은 LogMailSender(로그만), 운영은 SMTP 구현으로 교체. + * 외부 API 호출은 하지 않는다(보안 불변규칙 — Ollama 외 외부 호출 금지). + */ +public interface MailSender { + + void send(String to, String subject, String body); +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/config/UiwsProperties.java b/backend/src/main/java/com/zioinfo/mes/uiws/config/UiwsProperties.java new file mode 100644 index 0000000..5cdb19e --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/config/UiwsProperties.java @@ -0,0 +1,41 @@ +package com.zioinfo.mes.uiws.config; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * UIWS 이식 모듈 설정. application.yml 의 mes.uiws.* 바인딩. + * 계획서 2FA 설정키(verify-token-validity / max-login-fail / email-code-validity) + + * 첨부 업로드 디렉터리. 모두 안전 기본값 보유(미설정이어도 동작). + */ +@Getter +@Setter +@Component +@ConfigurationProperties(prefix = "mes.uiws") +public class UiwsProperties { + + private final Auth auth = new Auth(); + private final Upload upload = new Upload(); + + @Getter + @Setter + public static class Auth { + /** 2FA 레이어 on/off. 기본 on(켜짐). off 시 기존 단일 JWT 로그인 흐름 유지(회귀 0). */ + private boolean twofaEnabled = true; + /** 1차 통과 후 verify-token 유효시간(초). 계획서 300(5분). */ + private long verifyTokenValiditySeconds = 300; + /** 이메일 인증코드 유효시간(초). 계획서 300(5분). */ + private long emailCodeValiditySeconds = 300; + /** 로그인 실패 누적 N회 시 계정 잠금. 계획서 5. */ + private int maxLoginFail = 5; + } + + @Getter + @Setter + public static class Upload { + /** 첨부파일 저장 루트. 기본 ./uploads/uiws. */ + private String uploadDir = "./uploads/uiws"; + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/message/controller/MessageController.java b/backend/src/main/java/com/zioinfo/mes/uiws/message/controller/MessageController.java new file mode 100644 index 0000000..644960d --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/message/controller/MessageController.java @@ -0,0 +1,86 @@ +package com.zioinfo.mes.uiws.message.controller; + +import com.zioinfo.mes.common.ApiResponse; +import com.zioinfo.mes.uiws.message.dto.MessageDtos.*; +import com.zioinfo.mes.uiws.message.service.MessageService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; + +/** + * UIWS 이식 — 쪽지(모듈 03). 인증 필수(/api/messages). 원본 prefix·엔드포인트 보존. + * Spring Data Pageable 의존 회피: page/size 단순 파라미터로 이식(ERP는 spring-data-web 미사용). + */ +@Tag(name = "UIWS-쪽지", description = "UIWS 이식: 쪽지 송수신/개봉현황") +@RestController +@RequestMapping("/api/messages") +@RequiredArgsConstructor +public class MessageController { + + private final MessageService messageService; + + @Operation(summary = "쪽지 전송/답장") + @PostMapping + public ApiResponse send(@Valid @RequestBody MessageSendDto dto) { + return ApiResponse.ok(messageService.send(dto)); + } + + @Operation(summary = "보낸쪽지함(기본 최근 1주일)") + @GetMapping("/sent") + public ApiResponse sent( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, + @RequestParam(required = false) String titleKeyword, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ApiResponse.ok(messageService.listSent(fromDate, toDate, titleKeyword, page, size)); + } + + @Operation(summary = "보낸쪽지 상세(수신자 개봉현황)") + @GetMapping("/sent/{id}") + public ApiResponse sentDetail(@PathVariable("id") Long id) { + return ApiResponse.ok(messageService.sentDetail(id)); + } + + @Operation(summary = "보낸쪽지 다중삭제") + @DeleteMapping("/sent") + public ApiResponse deleteSent(@Valid @RequestBody MessageIdsRequest req) { + messageService.deleteSent(req.ids()); + return ApiResponse.ok(null); + } + + @Operation(summary = "미열람 받은쪽지 수(배지)") + @GetMapping("/unread-count") + public ApiResponse unreadCount() { + return ApiResponse.ok(messageService.unreadCount()); + } + + @Operation(summary = "받은쪽지함(기본 최근 1주일)") + @GetMapping("/received") + public ApiResponse received( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, + @RequestParam(required = false) String titleKeyword, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ApiResponse.ok(messageService.listReceived(fromDate, toDate, titleKeyword, page, size)); + } + + @Operation(summary = "받은쪽지 상세(조회 시 개봉처리)") + @GetMapping("/received/{id}") + public ApiResponse receivedDetail(@PathVariable("id") Long id) { + return ApiResponse.ok(messageService.receivedDetail(id)); + } + + @Operation(summary = "받은쪽지 다중삭제") + @DeleteMapping("/received") + public ApiResponse deleteReceived(@Valid @RequestBody MessageIdsRequest req) { + messageService.deleteReceived(req.ids()); + return ApiResponse.ok(null); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/message/dto/MessageDtos.java b/backend/src/main/java/com/zioinfo/mes/uiws/message/dto/MessageDtos.java new file mode 100644 index 0000000..6794375 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/message/dto/MessageDtos.java @@ -0,0 +1,100 @@ +package com.zioinfo.mes.uiws.message.dto; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; + +import java.util.List; + +/** + * 쪽지(모듈 03) 요청/응답 DTO 모음. 원본 com.urp.uiws.message.dto.* 이식(필드·shape 동일). + * 프론트 경계면 계약 유지: API 응답 필드명 그대로 보존. + */ +public final class MessageDtos { + + private MessageDtos() { + } + + /** 전송/답장 요청. */ + public record MessageSendDto( + @NotBlank String title, + @NotBlank String content, + Long refWorklogId, + Long replyToId, + @Valid @NotEmpty(message = "수신자는 1명 이상이어야 합니다.") List receivers + ) { + } + + /** 수신자 1건. rcvType: RECV(수신) | REF(참조). */ + public record MessageReceiverDto( + @NotBlank String receiverId, + @NotBlank String rcvType + ) { + } + + /** 전송 응답. */ + public record MessageSendResponse(Long messageId) { + } + + /** 보낸쪽지함 행. */ + public record SentMessageDto( + Long messageId, + String title, + String receiverSummary, + long openCount, + long totalCount, + String sentAt + ) { + } + + /** 보낸쪽지 상세(수신자 개봉현황). */ + public record SentMessageDetailDto( + Long messageId, + String title, + String content, + Long refWorklogId, + String sentAt, + List receivers, + long totalCount, + long openCount, + long unopenCount + ) { + } + + /** 수신자별 개봉현황. */ + public record ReceiverStatusDto( + String receiverNm, + String rcvType, + String readYn, + String readAt + ) { + } + + /** 받은쪽지함 행. */ + public record ReceivedMessageDto( + Long messageId, + String title, + String senderNm, + String sentAt, + String readYn + ) { + } + + /** 받은쪽지 상세(조회 시 개봉처리). */ + public record ReceivedMessageDetailDto( + Long messageId, + String title, + String content, + String senderNm, + String sentAt, + String receivedAt, + Long refWorklogId + ) { + } + + /** 다중삭제 본문. */ + public record MessageIdsRequest( + @NotEmpty(message = "ids는 필수입니다.") List ids + ) { + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/message/mapper/MessageMapper.java b/backend/src/main/java/com/zioinfo/mes/uiws/message/mapper/MessageMapper.java new file mode 100644 index 0000000..0540d9c --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/message/mapper/MessageMapper.java @@ -0,0 +1,78 @@ +package com.zioinfo.mes.uiws.message.mapper; + +import com.zioinfo.mes.uiws.message.model.UiwsMessage; +import com.zioinfo.mes.uiws.message.model.UiwsMessageRcv; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +/** + * 쪽지 MyBatis 매퍼. 원본 JPA MessageRepository/MessageRcvRepository → MyBatis 변환 이식. + * 사용자명은 mes_user(username↔display_name) 조인으로 라벨화(코어 user 재사용, 별도 user 테이블 미이식). + */ +@Mapper +public interface MessageMapper { + + // ── message 헤더 + int insertMessage(UiwsMessage m); + + UiwsMessage findMessageById(@Param("messageId") Long messageId); + + boolean existsMessageById(@Param("messageId") Long messageId); + + /** 보낸쪽지 페이징(SENDER_DEL_YN='N' 제외). */ + List searchSent(@Param("senderId") String senderId, + @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("titleKeyword") String titleKeyword, + @Param("limit") int limit, + @Param("offset") int offset); + + long countSent(@Param("senderId") String senderId, + @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("titleKeyword") String titleKeyword); + + /** 보낸쪽지 다중 소프트삭제(본인 것만). */ + int softDeleteSent(@Param("senderId") String senderId, + @Param("ids") List ids, + @Param("actor") String actor); + + // ── 수신자 + int insertRcv(UiwsMessageRcv rcv); + + List findRcvByMessageId(@Param("messageId") Long messageId); + + List findRcvByMessageIds(@Param("ids") List ids); + + UiwsMessageRcv findRcvByMessageAndReceiver(@Param("messageId") Long messageId, + @Param("receiverId") String receiverId); + + long countUnread(@Param("receiverId") String receiverId); + + /** 받은쪽지 개봉처리(READ_YN='Y', READ_AT). */ + int markRead(@Param("rcvId") Long rcvId, @Param("actor") String actor, @Param("readAt") LocalDateTime readAt); + + int softDeleteReceived(@Param("receiverId") String receiverId, + @Param("ids") List ids, + @Param("actor") String actor); + + /** 받은쪽지 목록(조인: message + rcv). 행: messageId,title,senderId,sentAt,readYn. */ + List> searchReceived(@Param("receiverId") String receiverId, + @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("titleKeyword") String titleKeyword, + @Param("limit") int limit, + @Param("offset") int offset); + + long countReceived(@Param("receiverId") String receiverId, + @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("titleKeyword") String titleKeyword); + + // ── 사용자명 라벨(코어 user 재사용) + List> findUserNames(@Param("ids") List ids); +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/message/model/UiwsMessage.java b/backend/src/main/java/com/zioinfo/mes/uiws/message/model/UiwsMessage.java new file mode 100644 index 0000000..8f21093 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/message/model/UiwsMessage.java @@ -0,0 +1,24 @@ +package com.zioinfo.mes.uiws.message.model; + +import lombok.Data; +import java.time.LocalDateTime; + +/** + * 쪽지 헤더 (tb_uiws_message). 원본 com.urp.uiws.domain.Message 이식. + * MyBatis map-underscore-to-camel-case 로 컬럼↔필드 자동 매핑. + */ +@Data +public class UiwsMessage { + private Long messageId; + private String senderId; + private String title; + private String content; + private Long refWorklogId; + private Long replyToId; + private LocalDateTime sentAt; + private String senderDelYn; + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/message/model/UiwsMessageRcv.java b/backend/src/main/java/com/zioinfo/mes/uiws/message/model/UiwsMessageRcv.java new file mode 100644 index 0000000..dc97381 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/message/model/UiwsMessageRcv.java @@ -0,0 +1,22 @@ +package com.zioinfo.mes.uiws.message.model; + +import lombok.Data; +import java.time.LocalDateTime; + +/** + * 쪽지 수신자 (tb_uiws_message_rcv). 원본 com.urp.uiws.domain.MessageRcv 이식. + */ +@Data +public class UiwsMessageRcv { + private Long rcvId; + private Long messageId; + private String receiverId; + private String rcvType; // RECV | REF + private String readYn; // Y | N + private LocalDateTime readAt; + private String receiverDelYn; // Y | N + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/message/service/MessageService.java b/backend/src/main/java/com/zioinfo/mes/uiws/message/service/MessageService.java new file mode 100644 index 0000000..a6d2dbe --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/message/service/MessageService.java @@ -0,0 +1,271 @@ +package com.zioinfo.mes.uiws.message.service; + +import com.zioinfo.mes.uiws.common.UiwsApiException; +import com.zioinfo.mes.uiws.common.UiwsCurrentUser; +import com.zioinfo.mes.uiws.common.UiwsErrorCode; +import com.zioinfo.mes.uiws.message.dto.MessageDtos.*; +import com.zioinfo.mes.uiws.message.mapper.MessageMapper; +import com.zioinfo.mes.uiws.message.model.UiwsMessage; +import com.zioinfo.mes.uiws.message.model.UiwsMessageRcv; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 쪽지(모듈 03) 서비스 — 원본 com.urp.uiws.message.service.MessageService 를 MyBatis 로 변환 이식. + * 로직(전송/답장, 보낸함, 개봉현황, 받은함, 개봉처리, 다중삭제, 미열람 배지)을 동등하게 보존한다. + * 기본 조회기간 = 최근 1주일. + */ +@Service +@RequiredArgsConstructor +public class MessageService { + + private static final Set VALID_RCV_TYPES = Set.of("RECV", "REF"); + private static final DateTimeFormatter DT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + + private final MessageMapper mapper; + + // ------------------------------------------------------------------ 전송/답장 + @Transactional + public MessageSendResponse send(MessageSendDto dto) { + String actor = UiwsCurrentUser.id(); + LocalDateTime now = LocalDateTime.now(); + + if (dto.replyToId() != null && !mapper.existsMessageById(dto.replyToId())) { + throw new UiwsApiException(UiwsErrorCode.MESSAGE_NOT_FOUND, "답장 원본 쪽지를 찾을 수 없습니다."); + } + + UiwsMessage m = new UiwsMessage(); + m.setSenderId(actor); + m.setTitle(dto.title()); + m.setContent(dto.content()); + m.setRefWorklogId(dto.refWorklogId()); + m.setReplyToId(dto.replyToId()); + m.setSentAt(now); + m.setSenderDelYn("N"); + m.setCreatedBy(actor); + m.setCreatedAt(now); + mapper.insertMessage(m); // useGeneratedKeys → m.messageId + + // 수신자: 동일 수신자 중복 제거(UNIQUE(message_id,receiver_id) 보호). 첫 등장 rcvType 채택. + Set seen = new LinkedHashSet<>(); + for (MessageReceiverDto r : dto.receivers()) { + String receiverId = (r.receiverId() == null) ? null : r.receiverId().trim(); + String rcvType = (r.rcvType() == null) ? null : r.rcvType().trim().toUpperCase(); + if (receiverId == null || receiverId.isBlank()) { + throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, "수신자 ID가 비어 있습니다."); + } + if (!VALID_RCV_TYPES.contains(rcvType)) { + throw new UiwsApiException(UiwsErrorCode.MESSAGE_RCV_TYPE_INVALID); + } + if (!seen.add(receiverId)) { + continue; + } + UiwsMessageRcv rcv = new UiwsMessageRcv(); + rcv.setMessageId(m.getMessageId()); + rcv.setReceiverId(receiverId); + rcv.setRcvType(rcvType); + rcv.setReadYn("N"); + rcv.setReceiverDelYn("N"); + rcv.setCreatedBy(actor); + rcv.setCreatedAt(now); + mapper.insertRcv(rcv); + } + return new MessageSendResponse(m.getMessageId()); + } + + // ------------------------------------------------------------------ 보낸쪽지함 + @Transactional(readOnly = true) + public SentPage listSent(LocalDate fromDate, LocalDate toDate, String titleKeyword, int page, int size) { + LocalDateTime[] range = range(fromDate, toDate); + String me = UiwsCurrentUser.id(); + String kw = blankToNull(titleKeyword); + long total = mapper.countSent(me, range[0], range[1], kw); + List rows = mapper.searchSent(me, range[0], range[1], kw, size, page * size); + + List ids = rows.stream().map(UiwsMessage::getMessageId).toList(); + List rcvs = ids.isEmpty() ? List.of() : mapper.findRcvByMessageIds(ids); + Map> byMsg = rcvs.stream().collect(Collectors.groupingBy(UiwsMessageRcv::getMessageId)); + Map names = userNames(rcvs.stream().map(UiwsMessageRcv::getReceiverId).toList()); + + List content = rows.stream().map(m -> { + List list = byMsg.getOrDefault(m.getMessageId(), List.of()); + long openCount = list.stream().filter(r -> "Y".equals(r.getReadYn())).count(); + return new SentMessageDto(m.getMessageId(), m.getTitle(), + receiverSummary(list, names), openCount, list.size(), fmt(m.getSentAt())); + }).toList(); + return new SentPage(content, total, page, size, totalPages(total, size)); + } + + // ------------------------------------------------------------------ 보낸쪽지 상세 + @Transactional(readOnly = true) + public SentMessageDetailDto sentDetail(Long messageId) { + String me = UiwsCurrentUser.id(); + UiwsMessage m = mapper.findMessageById(messageId); + if (m == null) { + throw new UiwsApiException(UiwsErrorCode.MESSAGE_NOT_FOUND); + } + if (!me.equals(m.getSenderId())) { + throw new UiwsApiException(UiwsErrorCode.FORBIDDEN, "본인이 보낸 쪽지만 조회할 수 있습니다."); + } + List list = mapper.findRcvByMessageId(messageId); + Map names = userNames(list.stream().map(UiwsMessageRcv::getReceiverId).toList()); + + List receivers = list.stream() + .map(r -> new ReceiverStatusDto( + names.getOrDefault(r.getReceiverId(), r.getReceiverId()), + r.getRcvType(), r.getReadYn(), fmt(r.getReadAt()))) + .toList(); + long total = receivers.size(); + long open = list.stream().filter(r -> "Y".equals(r.getReadYn())).count(); + return new SentMessageDetailDto(m.getMessageId(), m.getTitle(), m.getContent(), m.getRefWorklogId(), + fmt(m.getSentAt()), receivers, total, open, total - open); + } + + // ------------------------------------------------------------------ 보낸쪽지 다중삭제 + @Transactional + public void deleteSent(List ids) { + if (ids == null || ids.isEmpty()) { + return; + } + String me = UiwsCurrentUser.id(); + mapper.softDeleteSent(me, ids, me); + } + + // ------------------------------------------------------------------ 미열람 수(배지) + @Transactional(readOnly = true) + public long unreadCount() { + return mapper.countUnread(UiwsCurrentUser.id()); + } + + // ------------------------------------------------------------------ 받은쪽지함 + @Transactional(readOnly = true) + public ReceivedPage listReceived(LocalDate fromDate, LocalDate toDate, String titleKeyword, int page, int size) { + LocalDateTime[] range = range(fromDate, toDate); + String me = UiwsCurrentUser.id(); + String kw = blankToNull(titleKeyword); + long total = mapper.countReceived(me, range[0], range[1], kw); + List> rows = mapper.searchReceived(me, range[0], range[1], kw, size, page * size); + Map names = userNames(rows.stream().map(r -> str(r.get("senderId"))).toList()); + + List content = rows.stream() + .map(r -> new ReceivedMessageDto( + toLongObj(r.get("messageId")), + str(r.get("title")), + names.getOrDefault(str(r.get("senderId")), str(r.get("senderId"))), + fmt(toDt(r.get("sentAt"))), + str(r.get("readYn")))) + .toList(); + return new ReceivedPage(content, total, page, size, totalPages(total, size)); + } + + // ------------------------------------------------------------------ 받은쪽지 상세(개봉처리) + @Transactional + public ReceivedMessageDetailDto receivedDetail(Long messageId) { + String me = UiwsCurrentUser.id(); + UiwsMessageRcv rcv = mapper.findRcvByMessageAndReceiver(messageId, me); + if (rcv == null || "Y".equals(rcv.getReceiverDelYn())) { + throw new UiwsApiException(UiwsErrorCode.MESSAGE_NOT_FOUND, "받은 쪽지를 찾을 수 없습니다."); + } + UiwsMessage m = mapper.findMessageById(messageId); + if (m == null) { + throw new UiwsApiException(UiwsErrorCode.MESSAGE_NOT_FOUND); + } + LocalDateTime readAt = rcv.getReadAt(); + if (!"Y".equals(rcv.getReadYn())) { + readAt = LocalDateTime.now(); + mapper.markRead(rcv.getRcvId(), me, readAt); + } + String senderNm = userNames(List.of(m.getSenderId())).getOrDefault(m.getSenderId(), m.getSenderId()); + return new ReceivedMessageDetailDto(m.getMessageId(), m.getTitle(), m.getContent(), + senderNm, fmt(m.getSentAt()), fmt(readAt), m.getRefWorklogId()); + } + + // ------------------------------------------------------------------ 받은쪽지 다중삭제 + @Transactional + public void deleteReceived(List ids) { + if (ids == null || ids.isEmpty()) { + return; + } + String me = UiwsCurrentUser.id(); + mapper.softDeleteReceived(me, ids, me); + } + + // ================================================================== helpers + + private LocalDateTime[] range(LocalDate fromDate, LocalDate toDate) { + LocalDate to = (toDate != null) ? toDate : LocalDate.now(); + LocalDate from = (fromDate != null) ? fromDate : to.minusWeeks(1); + return new LocalDateTime[]{from.atStartOfDay(), to.atTime(LocalTime.MAX)}; + } + + private String receiverSummary(List list, Map names) { + if (list.isEmpty()) { + return ""; + } + String first = names.getOrDefault(list.get(0).getReceiverId(), list.get(0).getReceiverId()); + return list.size() == 1 ? first : first + " 외 " + (list.size() - 1) + "명"; + } + + private Map userNames(List userIds) { + List ids = userIds.stream().filter(s -> s != null && !s.isBlank()).distinct().toList(); + if (ids.isEmpty()) { + return Map.of(); + } + return mapper.findUserNames(ids).stream() + .collect(Collectors.toMap(r -> r.get("username"), r -> r.get("fullName"), (a, b) -> a)); + } + + private static int totalPages(long total, int size) { + return size <= 0 ? 0 : (int) ((total + size - 1) / size); + } + + private static String blankToNull(String s) { + return (s == null || s.isBlank()) ? null : s; + } + + private static String str(Object o) { + return o == null ? "" : o.toString(); + } + + private static Long toLongObj(Object o) { + if (o == null) { + return null; + } + return (o instanceof Number n) ? n.longValue() : Long.parseLong(o.toString()); + } + + private static LocalDateTime toDt(Object o) { + if (o == null) { + return null; + } + if (o instanceof LocalDateTime dt) { + return dt; + } + if (o instanceof java.sql.Timestamp ts) { + return ts.toLocalDateTime(); + } + return null; + } + + private static String fmt(LocalDateTime dt) { + return dt != null ? dt.format(DT) : null; + } + + // 페이지 응답(ERP ApiResponse 안에 그대로 직렬화 — content/totalElements/page/size/totalPages 보존) + public record SentPage(List content, long totalElements, int page, int size, int totalPages) { + } + + public record ReceivedPage(List content, long totalElements, int page, int size, int totalPages) { + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/AttachmentController.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/AttachmentController.java new file mode 100644 index 0000000..1f419ea --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/AttachmentController.java @@ -0,0 +1,74 @@ +package com.zioinfo.mes.uiws.schedule.controller; + +import com.zioinfo.mes.common.ApiResponse; +import com.zioinfo.mes.uiws.schedule.dto.ScheduleDtos.AttachmentDto; +import com.zioinfo.mes.uiws.schedule.service.AttachmentService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +/** + * UIWS 이식 — 첨부파일(모듈 02, 폴리모픽 SCHEDULE/DIARY). 인증 필수(/api/attachments). + */ +@Tag(name = "UIWS-첨부", description = "UIWS 이식: 일정/일지 첨부파일") +@RestController +@RequestMapping("/api/attachments") +@RequiredArgsConstructor +public class AttachmentController { + + private final AttachmentService attachmentService; + + @Operation(summary = "첨부파일 업로드(일정/일지)") + @PostMapping + public ApiResponse upload( + @RequestParam("refType") String refType, + @RequestParam("refId") Long refId, + @RequestParam("file") MultipartFile file) { + return ApiResponse.ok(attachmentService.upload(refType, refId, file)); + } + + @Operation(summary = "첨부 다운로드") + @GetMapping("/{id}/download") + public ResponseEntity download(@PathVariable("id") Long id) { + AttachmentService.DownloadFile f = attachmentService.download(id); + Resource resource = new FileSystemResource(f.path()); + String contentType; + try { + contentType = Files.probeContentType(f.path()); + } catch (IOException e) { + contentType = null; + } + ContentDisposition cd = ContentDisposition.attachment() + .filename(f.fileNm(), StandardCharsets.UTF_8) + .build(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentDisposition(cd); + long len = f.path().toFile().length(); + if (len > 0) { + headers.setContentLength(len); + } + return ResponseEntity.ok() + .headers(headers) + .contentType(contentType != null ? MediaType.parseMediaType(contentType) : MediaType.APPLICATION_OCTET_STREAM) + .body(resource); + } + + @Operation(summary = "첨부 삭제") + @DeleteMapping("/{id}") + public ApiResponse delete(@PathVariable("id") Long id) { + attachmentService.delete(id); + return ApiResponse.ok(null); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/DiaryController.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/DiaryController.java new file mode 100644 index 0000000..f693031 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/DiaryController.java @@ -0,0 +1,60 @@ +package com.zioinfo.mes.uiws.schedule.controller; + +import com.zioinfo.mes.common.ApiResponse; +import com.zioinfo.mes.uiws.schedule.dto.ScheduleDtos.*; +import com.zioinfo.mes.uiws.schedule.service.DiaryService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; + +/** + * UIWS 이식 — 일지(모듈 02). 인증 필수(/api/diaries). + */ +@Tag(name = "UIWS-일지", description = "UIWS 이식: 일지") +@RestController +@RequestMapping("/api/diaries") +@RequiredArgsConstructor +public class DiaryController { + + private final DiaryService diaryService; + + @Operation(summary = "일지 목록") + @GetMapping + public ApiResponse list( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ApiResponse.ok(diaryService.list(fromDate, toDate, page, size)); + } + + @Operation(summary = "일지 등록") + @PostMapping + public ApiResponse create(@Valid @RequestBody DiarySaveDto dto) { + return ApiResponse.ok(diaryService.create(dto)); + } + + @Operation(summary = "일지 상세") + @GetMapping("/{id}") + public ApiResponse detail(@PathVariable("id") Long id) { + return ApiResponse.ok(diaryService.detail(id)); + } + + @Operation(summary = "일지 수정") + @PutMapping("/{id}") + public ApiResponse update(@PathVariable("id") Long id, @Valid @RequestBody DiarySaveDto dto) { + return ApiResponse.ok(diaryService.update(id, dto)); + } + + @Operation(summary = "일지 삭제") + @DeleteMapping("/{id}") + public ApiResponse delete(@PathVariable("id") Long id) { + diaryService.delete(id); + return ApiResponse.ok(null); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/ScheduleController.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/ScheduleController.java new file mode 100644 index 0000000..d97502f --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/controller/ScheduleController.java @@ -0,0 +1,78 @@ +package com.zioinfo.mes.uiws.schedule.controller; + +import com.zioinfo.mes.common.ApiResponse; +import com.zioinfo.mes.uiws.schedule.dto.ScheduleDtos.*; +import com.zioinfo.mes.uiws.schedule.service.ScheduleService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; +import java.util.List; + +/** + * UIWS 이식 — 일정(모듈 02). 인증 필수(/api/schedules). 원본 엔드포인트 보존. + */ +@Tag(name = "UIWS-일정", description = "UIWS 이식: 개인/부서 일정") +@RestController +@RequestMapping("/api/schedules") +@RequiredArgsConstructor +public class ScheduleController { + + private final ScheduleService scheduleService; + + @Operation(summary = "개인/부서 일정(달력 month/week/day)") + @GetMapping + public ApiResponse> calendar( + @RequestParam(defaultValue = "PERSONAL") String type, + @RequestParam(defaultValue = "month") String view, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate baseDate, + @RequestParam(required = false) String deptId) { + return ApiResponse.ok(scheduleService.calendar(type, view, baseDate, deptId)); + } + + @Operation(summary = "전체일정 목록") + @GetMapping("/all") + public ApiResponse all( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, + @RequestParam(required = false) String type, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ApiResponse.ok(scheduleService.all(fromDate, toDate, type, page, size)); + } + + @Operation(summary = "일정검색 팝업") + @GetMapping("/search") + public ApiResponse> search(@RequestParam(required = false) String keyword) { + return ApiResponse.ok(scheduleService.search(keyword)); + } + + @Operation(summary = "일정 등록") + @PostMapping + public ApiResponse create(@Valid @RequestBody ScheduleSaveDto dto) { + return ApiResponse.ok(scheduleService.create(dto)); + } + + @Operation(summary = "일정 상세") + @GetMapping("/{id}") + public ApiResponse detail(@PathVariable("id") Long id) { + return ApiResponse.ok(scheduleService.detail(id)); + } + + @Operation(summary = "일정 수정") + @PutMapping("/{id}") + public ApiResponse update(@PathVariable("id") Long id, @Valid @RequestBody ScheduleSaveDto dto) { + return ApiResponse.ok(scheduleService.update(id, dto)); + } + + @Operation(summary = "일정 삭제") + @DeleteMapping("/{id}") + public ApiResponse delete(@PathVariable("id") Long id) { + scheduleService.delete(id); + return ApiResponse.ok(null); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/dto/ScheduleDtos.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/dto/ScheduleDtos.java new file mode 100644 index 0000000..3deea7c --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/dto/ScheduleDtos.java @@ -0,0 +1,109 @@ +package com.zioinfo.mes.uiws.schedule.dto; + +import com.zioinfo.mes.uiws.schedule.model.UiwsAttach; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + +import java.util.List; + +/** + * 일정·일지·첨부(모듈 02) DTO. 원본 com.urp.uiws.schedule.dto.* 이식(shape 동일). + */ +public final class ScheduleDtos { + + private ScheduleDtos() { + } + + public record ScheduleDto( + Long scheduleId, + String scheType, + String title, + String scheGubunCd, + String importanceCd, + String startDt, + String endDt, + String ownerId, + String deptId + ) { + } + + public record ScheduleDetailDto( + Long scheduleId, + String scheType, + String title, + String scheGubunCd, + String importanceCd, + String startDt, + String endDt, + String ownerId, + String deptId, + String content, + String chargerId, + String chargerNm, + List attachments + ) { + } + + public record ScheduleSaveDto( + @NotBlank @Pattern(regexp = "PERSONAL|DEPT") String scheType, + @NotBlank String title, + String scheGubunCd, + String importanceCd, + @NotNull String startDt, + @NotNull String endDt, + String content, + String deptId, + String chargerId, + List attachmentIds + ) { + } + + public record DiaryDto( + Long diaryId, + String title, + String writerNm, + String diaryDate, + Long scheduleId + ) { + } + + public record DiaryDetailDto( + Long diaryId, + String title, + String writerNm, + String diaryDate, + Long scheduleId, + String content, + List attachments + ) { + } + + public record DiarySaveDto( + @NotBlank String title, + String content, + Long scheduleId, + String diaryDate, + List attachmentIds + ) { + } + + public record AttachmentDto( + Long attachId, + String refType, + Long refId, + String fileNm, + Long fileSize + ) { + public static AttachmentDto from(UiwsAttach a) { + return new AttachmentDto(a.getAttachId(), a.getRefType(), a.getRefId(), a.getFileNm(), a.getFileSize()); + } + } + + /** 페이지 래퍼(content/totalElements/page/size/totalPages). */ + public record DiaryPage(List content, long totalElements, int page, int size, int totalPages) { + } + + public record SchedulePage(List content, long totalElements, int page, int size, int totalPages) { + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/mapper/ScheduleMapper.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/mapper/ScheduleMapper.java new file mode 100644 index 0000000..eaf5d58 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/mapper/ScheduleMapper.java @@ -0,0 +1,93 @@ +package com.zioinfo.mes.uiws.schedule.mapper; + +import com.zioinfo.mes.uiws.schedule.model.UiwsAttach; +import com.zioinfo.mes.uiws.schedule.model.UiwsDiary; +import com.zioinfo.mes.uiws.schedule.model.UiwsSchedule; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +/** + * 일정·일지·첨부 MyBatis 매퍼. 원본 JPA ScheduleRepository/DiaryRepository/AttachRepository 변환 이식. + * 데이터 가시범위: scopeAll(true=ADMIN 전체) OR owner IN (ownerIds). ownerIds 는 항상 본인 포함(빈 IN 회피). + */ +@Mapper +public interface ScheduleMapper { + + // ── schedule + int insertSchedule(UiwsSchedule s); + + int updateSchedule(UiwsSchedule s); + + UiwsSchedule findScheduleById(@Param("scheduleId") Long scheduleId); + + boolean existsScheduleById(@Param("scheduleId") Long scheduleId); + + int deleteScheduleById(@Param("scheduleId") Long scheduleId); + + /** 달력: 기간 겹침([from,to) 배타 상한) + type + 개인소유/부서필터. */ + List findInRange(@Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("scheType") String scheType, + @Param("ownerId") String ownerId, + @Param("deptId") String deptId); + + List searchAll(@Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("scheType") String scheType, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds, + @Param("limit") int limit, + @Param("offset") int offset); + + long countAll(@Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, + @Param("scheType") String scheType, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds); + + List searchPopup(@Param("keyword") String keyword, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds); + + // ── diary + int insertDiary(UiwsDiary d); + + int updateDiary(UiwsDiary d); + + UiwsDiary findDiaryById(@Param("diaryId") Long diaryId); + + boolean existsDiaryById(@Param("diaryId") Long diaryId); + + int deleteDiaryById(@Param("diaryId") Long diaryId); + + List searchDiary(@Param("from") LocalDate from, + @Param("to") LocalDate to, + @Param("limit") int limit, + @Param("offset") int offset); + + long countDiary(@Param("from") LocalDate from, @Param("to") LocalDate to); + + // ── attach + int insertAttach(UiwsAttach a); + + UiwsAttach findAttachById(@Param("attachId") Long attachId); + + int updateAttachRef(@Param("attachId") Long attachId, + @Param("refType") String refType, + @Param("refId") Long refId, + @Param("actor") String actor); + + List findAttachByRef(@Param("refType") String refType, @Param("refId") Long refId); + + int deleteAttachById(@Param("attachId") Long attachId); + + int deleteAttachByRef(@Param("refType") String refType, @Param("refId") Long refId); + + // ── 사용자명 라벨(코어 user 재사용) + List> findUserNames(@Param("ids") List ids); +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsAttach.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsAttach.java new file mode 100644 index 0000000..24e3096 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsAttach.java @@ -0,0 +1,19 @@ +package com.zioinfo.mes.uiws.schedule.model; + +import lombok.Data; +import java.time.LocalDateTime; + +/** 첨부파일 폴리모픽 (tb_uiws_attach, ref_type=SCHEDULE|DIARY). 원본 com.urp.uiws.domain.Attach 이식. */ +@Data +public class UiwsAttach { + private Long attachId; + private String refType; + private Long refId; + private String fileNm; + private String filePath; + private Long fileSize; + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsDiary.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsDiary.java new file mode 100644 index 0000000..825cb61 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsDiary.java @@ -0,0 +1,20 @@ +package com.zioinfo.mes.uiws.schedule.model; + +import lombok.Data; +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** 일지 (tb_uiws_diary). 원본 com.urp.uiws.domain.Diary 이식. */ +@Data +public class UiwsDiary { + private Long diaryId; + private String title; + private String content; + private Long scheduleId; + private String writerId; + private LocalDate diaryDate; + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsSchedule.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsSchedule.java new file mode 100644 index 0000000..c7b13e9 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/model/UiwsSchedule.java @@ -0,0 +1,24 @@ +package com.zioinfo.mes.uiws.schedule.model; + +import lombok.Data; +import java.time.LocalDateTime; + +/** 일정 (tb_uiws_schedule). 원본 com.urp.uiws.domain.Schedule 이식. */ +@Data +public class UiwsSchedule { + private Long scheduleId; + private String scheType; // PERSONAL | DEPT + private String title; + private String scheGubunCd; + private String importanceCd; + private LocalDateTime startDt; + private LocalDateTime endDt; + private String content; + private String ownerId; + private String deptId; + private String chargerId; + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/AttachmentService.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/AttachmentService.java new file mode 100644 index 0000000..dcdcbad --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/AttachmentService.java @@ -0,0 +1,121 @@ +package com.zioinfo.mes.uiws.schedule.service; + +import com.zioinfo.mes.uiws.common.UiwsApiException; +import com.zioinfo.mes.uiws.common.UiwsCurrentUser; +import com.zioinfo.mes.uiws.common.UiwsErrorCode; +import com.zioinfo.mes.uiws.schedule.dto.ScheduleDtos.AttachmentDto; +import com.zioinfo.mes.uiws.schedule.mapper.ScheduleMapper; +import com.zioinfo.mes.uiws.schedule.model.UiwsAttach; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Set; + +/** + * 첨부파일(폴리모픽 SCHEDULE/DIARY) 업로드·삭제·연결. 원본 com.urp.uiws.schedule.service.AttachmentService 이식. + */ +@Service +@RequiredArgsConstructor +public class AttachmentService { + + public static final String REF_SCHEDULE = "SCHEDULE"; + public static final String REF_DIARY = "DIARY"; + private static final Set VALID_REF_TYPES = Set.of(REF_SCHEDULE, REF_DIARY); + + private final ScheduleMapper mapper; + private final FileStorageService fileStorageService; + + @Transactional + public AttachmentDto upload(String refType, Long refId, MultipartFile file) { + String type = normalizeRefType(refType); + if (refId == null) { + throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, "refId 는 필수입니다."); + } + FileStorageService.StoredFile stored = fileStorageService.store(file); + + String actor = UiwsCurrentUser.id(); + UiwsAttach a = new UiwsAttach(); + a.setRefType(type); + a.setRefId(refId); + a.setFileNm(stored.originalName()); + a.setFilePath(stored.relativePath()); + a.setFileSize(stored.size()); + a.setCreatedBy(actor); + a.setCreatedAt(LocalDateTime.now()); + mapper.insertAttach(a); + return AttachmentDto.from(a); + } + + public record DownloadFile(String fileNm, Path path) { + } + + @Transactional(readOnly = true) + public DownloadFile download(Long attachId) { + UiwsAttach a = mapper.findAttachById(attachId); + if (a == null) { + throw new UiwsApiException(UiwsErrorCode.ATTACH_NOT_FOUND); + } + Path path = fileStorageService.resolve(a.getFilePath()); + if (!Files.exists(path)) { + throw new UiwsApiException(UiwsErrorCode.ATTACH_NOT_FOUND, "파일이 존재하지 않습니다."); + } + return new DownloadFile(a.getFileNm(), path); + } + + @Transactional + public void delete(Long attachId) { + UiwsAttach a = mapper.findAttachById(attachId); + if (a == null) { + throw new UiwsApiException(UiwsErrorCode.ATTACH_NOT_FOUND); + } + fileStorageService.delete(a.getFilePath()); + mapper.deleteAttachById(attachId); + } + + /** 일정/일지 저장 시 attachmentIds 의 첨부들을 해당 대상으로 귀속(확정). */ + @Transactional + public void link(String refType, Long refId, List attachmentIds) { + String type = normalizeRefType(refType); + if (attachmentIds == null || attachmentIds.isEmpty()) { + return; + } + String actor = UiwsCurrentUser.id(); + for (Long id : attachmentIds) { + if (id == null) { + continue; + } + mapper.updateAttachRef(id, type, refId, actor); + } + } + + @Transactional(readOnly = true) + public List list(String refType, Long refId) { + return mapper.findAttachByRef(normalizeRefType(refType), refId) + .stream().map(AttachmentDto::from).toList(); + } + + /** 대상 삭제 시 귀속 첨부 일괄 제거(물리파일 포함). */ + @Transactional + public void deleteByRef(String refType, Long refId) { + String type = normalizeRefType(refType); + List rows = mapper.findAttachByRef(type, refId); + for (UiwsAttach a : rows) { + fileStorageService.delete(a.getFilePath()); + } + mapper.deleteAttachByRef(type, refId); + } + + private String normalizeRefType(String refType) { + String type = refType == null ? "" : refType.trim().toUpperCase(); + if (!VALID_REF_TYPES.contains(type)) { + throw new UiwsApiException(UiwsErrorCode.ATTACH_REF_TYPE_INVALID); + } + return type; + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/DiaryService.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/DiaryService.java new file mode 100644 index 0000000..464db37 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/DiaryService.java @@ -0,0 +1,133 @@ +package com.zioinfo.mes.uiws.schedule.service; + +import com.zioinfo.mes.uiws.common.UiwsApiException; +import com.zioinfo.mes.uiws.common.UiwsCurrentUser; +import com.zioinfo.mes.uiws.common.UiwsErrorCode; +import com.zioinfo.mes.uiws.schedule.dto.ScheduleDtos.*; +import com.zioinfo.mes.uiws.schedule.mapper.ScheduleMapper; +import com.zioinfo.mes.uiws.schedule.model.UiwsDiary; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 일지(모듈 02) 서비스 — 원본 com.urp.uiws.schedule.service.DiaryService MyBatis 변환 이식. + * 목록(페이징)·CRUD·첨부 연계. + */ +@Service +@RequiredArgsConstructor +public class DiaryService { + + private final ScheduleMapper mapper; + private final AttachmentService attachmentService; + + @Transactional(readOnly = true) + public DiaryPage list(LocalDate fromDate, LocalDate toDate, int page, int size) { + LocalDate to = (toDate != null) ? toDate : LocalDate.now(); + LocalDate from = (fromDate != null) ? fromDate : to.minusMonths(1); + long total = mapper.countDiary(from, to); + List rows = mapper.searchDiary(from, to, size, page * size); + Map names = userNames(rows.stream().map(UiwsDiary::getWriterId).toList()); + List content = rows.stream() + .map(d -> new DiaryDto(d.getDiaryId(), d.getTitle(), + names.getOrDefault(d.getWriterId(), d.getWriterId()), + d.getDiaryDate() != null ? d.getDiaryDate().toString() : null, + d.getScheduleId())) + .toList(); + return new DiaryPage(content, total, page, size, totalPages(total, size)); + } + + @Transactional + public DiaryDetailDto create(DiarySaveDto dto) { + String actor = UiwsCurrentUser.id(); + UiwsDiary d = new UiwsDiary(); + applySave(d, dto); + d.setWriterId(actor); + d.setCreatedBy(actor); + d.setCreatedAt(LocalDateTime.now()); + mapper.insertDiary(d); + attachmentService.link(AttachmentService.REF_DIARY, d.getDiaryId(), dto.attachmentIds()); + return toDetail(d); + } + + @Transactional(readOnly = true) + public DiaryDetailDto detail(Long id) { + return toDetail(find(id)); + } + + @Transactional + public DiaryDetailDto update(Long id, DiarySaveDto dto) { + String actor = UiwsCurrentUser.id(); + UiwsDiary d = find(id); + applySave(d, dto); + d.setUpdatedBy(actor); + d.setUpdatedAt(LocalDateTime.now()); + mapper.updateDiary(d); + attachmentService.link(AttachmentService.REF_DIARY, d.getDiaryId(), dto.attachmentIds()); + return toDetail(d); + } + + @Transactional + public void delete(Long id) { + if (!mapper.existsDiaryById(id)) { + throw new UiwsApiException(UiwsErrorCode.DIARY_NOT_FOUND); + } + attachmentService.deleteByRef(AttachmentService.REF_DIARY, id); + mapper.deleteDiaryById(id); + } + + // ================================================================== helpers + + private void applySave(UiwsDiary d, DiarySaveDto dto) { + d.setTitle(dto.title()); + d.setContent(dto.content()); + d.setScheduleId(dto.scheduleId()); + d.setDiaryDate(parseDateNullable(dto.diaryDate())); + } + + private DiaryDetailDto toDetail(UiwsDiary d) { + String writerNm = userNames(List.of(d.getWriterId())).getOrDefault(d.getWriterId(), d.getWriterId()); + List attachments = attachmentService.list(AttachmentService.REF_DIARY, d.getDiaryId()); + return new DiaryDetailDto(d.getDiaryId(), d.getTitle(), writerNm, + d.getDiaryDate() != null ? d.getDiaryDate().toString() : null, + d.getScheduleId(), d.getContent(), attachments); + } + + private UiwsDiary find(Long id) { + UiwsDiary d = mapper.findDiaryById(id); + if (d == null) { + throw new UiwsApiException(UiwsErrorCode.DIARY_NOT_FOUND); + } + return d; + } + + private Map userNames(List ids) { + List clean = ids.stream().filter(s -> s != null && !s.isBlank()).distinct().toList(); + if (clean.isEmpty()) { + return Map.of(); + } + return mapper.findUserNames(clean).stream() + .collect(Collectors.toMap(r -> r.get("username"), r -> r.get("fullName"), (a, b) -> a)); + } + + private static int totalPages(long total, int size) { + return size <= 0 ? 0 : (int) ((total + size - 1) / size); + } + + private static LocalDate parseDateNullable(String s) { + if (s == null || s.isBlank()) { + return null; + } + try { + return LocalDate.parse(s); + } catch (Exception e) { + throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, "날짜 형식이 올바르지 않습니다(yyyy-MM-dd)."); + } + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/FileStorageService.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/FileStorageService.java new file mode 100644 index 0000000..99a11ea --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/FileStorageService.java @@ -0,0 +1,93 @@ +package com.zioinfo.mes.uiws.schedule.service; + +import com.zioinfo.mes.uiws.common.UiwsApiException; +import com.zioinfo.mes.uiws.common.UiwsErrorCode; +import com.zioinfo.mes.uiws.config.UiwsProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.UUID; + +/** + * 첨부파일 로컬 스토리지(UIWS 이식). 경로순회 방지(파일명 정규화 + UUID 저장명), 일자별 디렉터리 분리. + * 저장 결과로 상대경로(file_path)를 반환한다. + */ +@Service +@RequiredArgsConstructor +public class FileStorageService { + + private static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("yyyy/MM/dd"); + + private final UiwsProperties properties; + + public record StoredFile(String originalName, String relativePath, long size) { + } + + public StoredFile store(MultipartFile file) { + if (file == null || file.isEmpty()) { + throw new UiwsApiException(UiwsErrorCode.FILE_EMPTY); + } + String original = StringUtils.cleanPath( + file.getOriginalFilename() != null ? file.getOriginalFilename() : "file"); + original = original.replace("\\", "_").replace("/", "_"); + if (original.contains("..")) { + original = original.replace("..", "_"); + } + String ext = ""; + int dot = original.lastIndexOf('.'); + if (dot >= 0) { + ext = original.substring(dot); + } + String subDir = LocalDate.now().format(DAY); + String storedName = UUID.randomUUID().toString().replace("-", "") + ext; + String relativePath = subDir + "/" + storedName; + + try { + Path root = Paths.get(properties.getUpload().getUploadDir()).toAbsolutePath().normalize(); + Path target = root.resolve(relativePath).normalize(); + if (!target.startsWith(root)) { + throw new UiwsApiException(UiwsErrorCode.FILE_STORAGE_ERROR, "허용되지 않은 저장 경로입니다."); + } + Files.createDirectories(target.getParent()); + file.transferTo(target.toFile()); + } catch (IOException e) { + throw new UiwsApiException(UiwsErrorCode.FILE_STORAGE_ERROR); + } + return new StoredFile(original, relativePath, file.getSize()); + } + + public Path resolve(String relativePath) { + if (relativePath == null || relativePath.isBlank()) { + throw new UiwsApiException(UiwsErrorCode.ATTACH_NOT_FOUND); + } + Path root = Paths.get(properties.getUpload().getUploadDir()).toAbsolutePath().normalize(); + Path target = root.resolve(relativePath).normalize(); + if (!target.startsWith(root)) { + throw new UiwsApiException(UiwsErrorCode.FILE_STORAGE_ERROR, "허용되지 않은 경로입니다."); + } + return target; + } + + public void delete(String relativePath) { + if (relativePath == null || relativePath.isBlank()) { + return; + } + try { + Path root = Paths.get(properties.getUpload().getUploadDir()).toAbsolutePath().normalize(); + Path target = root.resolve(relativePath).normalize(); + if (target.startsWith(root)) { + Files.deleteIfExists(target); + } + } catch (IOException ignore) { + // 물리파일 삭제 실패는 무시(메타 일관성 우선) + } + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/ScheduleService.java b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/ScheduleService.java new file mode 100644 index 0000000..348427e --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/schedule/service/ScheduleService.java @@ -0,0 +1,216 @@ +package com.zioinfo.mes.uiws.schedule.service; + +import com.zioinfo.mes.uiws.common.UiwsApiException; +import com.zioinfo.mes.uiws.common.UiwsCurrentUser; +import com.zioinfo.mes.uiws.common.UiwsDataScope; +import com.zioinfo.mes.uiws.common.UiwsErrorCode; +import com.zioinfo.mes.uiws.schedule.dto.ScheduleDtos.*; +import com.zioinfo.mes.uiws.schedule.mapper.ScheduleMapper; +import com.zioinfo.mes.uiws.schedule.model.UiwsSchedule; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAdjusters; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 일정(모듈 02) 서비스 — 원본 com.urp.uiws.schedule.service.ScheduleService 를 MyBatis 변환 이식. + * 달력(month/week/day)·전체목록·검색팝업·CRUD. 첨부 연계(attachmentIds). + */ +@Service +@RequiredArgsConstructor +public class ScheduleService { + + private static final String TYPE_PERSONAL = "PERSONAL"; + private static final String TYPE_DEPT = "DEPT"; + private static final DateTimeFormatter DT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + + private final ScheduleMapper mapper; + private final AttachmentService attachmentService; + + @Transactional(readOnly = true) + public List calendar(String type, String view, LocalDate baseDate, String deptId) { + String t = normalizeType(type); + LocalDate base = (baseDate != null) ? baseDate : LocalDate.now(); + LocalDate[] range = computeRange(view, base); + LocalDateTime from = range[0].atStartOfDay(); + LocalDateTime to = range[1].atStartOfDay(); // 배타 상한 + + String ownerId = TYPE_PERSONAL.equals(t) ? UiwsCurrentUser.id() : null; + String deptFilter = TYPE_DEPT.equals(t) ? blankToNull(deptId) : null; + + return mapper.findInRange(from, to, t, ownerId, deptFilter).stream().map(this::toDto).toList(); + } + + @Transactional(readOnly = true) + public SchedulePage all(LocalDate fromDate, LocalDate toDate, String type, int page, int size) { + LocalDate to = (toDate != null) ? toDate : LocalDate.now(); + LocalDate from = (fromDate != null) ? fromDate : to.minusMonths(1); + String t = (type == null || type.isBlank()) ? null : normalizeType(type); + UiwsDataScope.Scope scope = UiwsDataScope.current(); + LocalDateTime f = from.atStartOfDay(); + LocalDateTime tt = to.plusDays(1).atStartOfDay(); + long total = mapper.countAll(f, tt, t, scope.all(), scope.ownerIds()); + List content = mapper.searchAll(f, tt, t, scope.all(), scope.ownerIds(), size, page * size) + .stream().map(this::toDto).toList(); + return new SchedulePage(content, total, page, size, totalPages(total, size)); + } + + @Transactional(readOnly = true) + public List search(String keyword) { + UiwsDataScope.Scope scope = UiwsDataScope.current(); + return mapper.searchPopup(blankToNull(keyword), scope.all(), scope.ownerIds()) + .stream().map(this::toDto).toList(); + } + + @Transactional + public ScheduleDto create(ScheduleSaveDto dto) { + String actor = UiwsCurrentUser.id(); + UiwsSchedule s = new UiwsSchedule(); + applySave(s, dto); + s.setOwnerId(actor); + s.setCreatedBy(actor); + s.setCreatedAt(LocalDateTime.now()); + mapper.insertSchedule(s); + attachmentService.link(AttachmentService.REF_SCHEDULE, s.getScheduleId(), dto.attachmentIds()); + return toDto(s); + } + + @Transactional(readOnly = true) + public ScheduleDetailDto detail(Long id) { + return toDetail(find(id)); + } + + @Transactional + public ScheduleDetailDto update(Long id, ScheduleSaveDto dto) { + String actor = UiwsCurrentUser.id(); + UiwsSchedule s = find(id); + applySave(s, dto); + s.setUpdatedBy(actor); + s.setUpdatedAt(LocalDateTime.now()); + mapper.updateSchedule(s); + attachmentService.link(AttachmentService.REF_SCHEDULE, s.getScheduleId(), dto.attachmentIds()); + return toDetail(s); + } + + @Transactional + public void delete(Long id) { + if (!mapper.existsScheduleById(id)) { + throw new UiwsApiException(UiwsErrorCode.SCHEDULE_NOT_FOUND); + } + attachmentService.deleteByRef(AttachmentService.REF_SCHEDULE, id); + mapper.deleteScheduleById(id); + } + + // ================================================================== helpers + + private void applySave(UiwsSchedule s, ScheduleSaveDto dto) { + LocalDateTime start = parseDateTime(dto.startDt()); + LocalDateTime end = parseDateTime(dto.endDt()); + if (end.isBefore(start)) { + throw new UiwsApiException(UiwsErrorCode.SCHEDULE_DT_INVALID, "종료 일시가 시작 일시보다 빠릅니다."); + } + s.setScheType(normalizeType(dto.scheType())); + s.setTitle(dto.title()); + s.setScheGubunCd(blankToNull(dto.scheGubunCd())); + s.setImportanceCd(blankToNull(dto.importanceCd())); + s.setStartDt(start); + s.setEndDt(end); + s.setContent(dto.content()); + s.setDeptId(blankToNull(dto.deptId())); + s.setChargerId(blankToNull(dto.chargerId())); + } + + private ScheduleDto toDto(UiwsSchedule s) { + return new ScheduleDto(s.getScheduleId(), s.getScheType(), s.getTitle(), + s.getScheGubunCd(), s.getImportanceCd(), fmt(s.getStartDt()), fmt(s.getEndDt()), + s.getOwnerId(), s.getDeptId()); + } + + private ScheduleDetailDto toDetail(UiwsSchedule s) { + String chargerNm = null; + if (s.getChargerId() != null) { + chargerNm = userNames(List.of(s.getChargerId())).getOrDefault(s.getChargerId(), s.getChargerId()); + } + List attachments = attachmentService.list(AttachmentService.REF_SCHEDULE, s.getScheduleId()); + return new ScheduleDetailDto(s.getScheduleId(), s.getScheType(), s.getTitle(), + s.getScheGubunCd(), s.getImportanceCd(), fmt(s.getStartDt()), fmt(s.getEndDt()), + s.getOwnerId(), s.getDeptId(), s.getContent(), s.getChargerId(), chargerNm, attachments); + } + + private UiwsSchedule find(Long id) { + UiwsSchedule s = mapper.findScheduleById(id); + if (s == null) { + throw new UiwsApiException(UiwsErrorCode.SCHEDULE_NOT_FOUND); + } + return s; + } + + private Map userNames(List ids) { + List clean = ids.stream().filter(s -> s != null && !s.isBlank()).distinct().toList(); + if (clean.isEmpty()) { + return Map.of(); + } + return mapper.findUserNames(clean).stream() + .collect(Collectors.toMap(r -> r.get("username"), r -> r.get("fullName"), (a, b) -> a)); + } + + private LocalDate[] computeRange(String view, LocalDate base) { + String v = (view == null || view.isBlank()) ? "month" : view.trim().toLowerCase(); + return switch (v) { + case "day" -> new LocalDate[]{base, base.plusDays(1)}; + case "week" -> { + LocalDate start = base.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)); + yield new LocalDate[]{start, start.plusWeeks(1)}; + } + case "month" -> { + LocalDate start = base.withDayOfMonth(1); + yield new LocalDate[]{start, start.plusMonths(1)}; + } + default -> throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, + "view 는 month/week/day 중 하나여야 합니다."); + }; + } + + private String normalizeType(String type) { + String t = (type == null) ? "" : type.trim().toUpperCase(); + if (!TYPE_PERSONAL.equals(t) && !TYPE_DEPT.equals(t)) { + throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, "type 은 PERSONAL/DEPT 중 하나여야 합니다."); + } + return t; + } + + private static int totalPages(long total, int size) { + return size <= 0 ? 0 : (int) ((total + size - 1) / size); + } + + private static String blankToNull(String s) { + return (s == null || s.isBlank()) ? null : s; + } + + private static String fmt(LocalDateTime dt) { + return dt != null ? dt.format(DT) : null; + } + + private static LocalDateTime parseDateTime(String s) { + if (s == null || s.isBlank()) { + throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, "일시 값이 비어 있습니다."); + } + try { + if (s.length() <= 10) { + return LocalDate.parse(s).atStartOfDay(); + } + return LocalDateTime.parse(s); + } catch (Exception e) { + throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, + "일시 형식이 올바르지 않습니다(yyyy-MM-ddTHH:mm:ss)."); + } + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/stats/controller/StatsController.java b/backend/src/main/java/com/zioinfo/mes/uiws/stats/controller/StatsController.java new file mode 100644 index 0000000..a94c540 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/stats/controller/StatsController.java @@ -0,0 +1,48 @@ +package com.zioinfo.mes.uiws.stats.controller; + +import com.zioinfo.mes.common.ApiResponse; +import com.zioinfo.mes.uiws.stats.dto.StatsDtos.PivotResponse; +import com.zioinfo.mes.uiws.stats.service.StatsService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; + +/** + * UIWS 이식 — 업무통계(모듈 04, 동적 컬럼 피벗). 인증 필수(/api/stats). + * prefix /api/stats 는 ERP 기존 라우트와 미충돌(확인). 원본 엔드포인트 보존. + */ +@Tag(name = "UIWS-업무통계", description = "UIWS 이식: 근무현황 동적 피벗") +@RestController +@RequestMapping("/api/stats") +@RequiredArgsConstructor +public class StatsController { + + private final StatsService statsService; + + @Operation(summary = "개인별 근무현황(행=근무자×상태×유형, 동적열=근무처)") + @GetMapping("/personal-work") + public ApiResponse personalWork( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, + @RequestParam(required = false) String deptId, + @RequestParam(required = false) String userId, + @RequestParam(required = false) Boolean showStatus, + @RequestParam(required = false) Boolean showType) { + return ApiResponse.ok(statsService.personalWork(fromDate, toDate, deptId, userId, showStatus, showType)); + } + + @Operation(summary = "업체별 근무현황(행=근무처×유형, 동적열=근무자)") + @GetMapping("/company-work") + public ApiResponse companyWork( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, + @RequestParam(required = false) String companyId, + @RequestParam(required = false) String userId, + @RequestParam(required = false) Boolean showType) { + return ApiResponse.ok(statsService.companyWork(fromDate, toDate, companyId, userId, showType)); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/stats/dto/StatsDtos.java b/backend/src/main/java/com/zioinfo/mes/uiws/stats/dto/StatsDtos.java new file mode 100644 index 0000000..3313684 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/stats/dto/StatsDtos.java @@ -0,0 +1,25 @@ +package com.zioinfo.mes.uiws.stats.dto; + +import java.util.List; +import java.util.Map; + +/** + * 근무현황 통계(모듈 04) 동적 컬럼 피벗 DTO. 원본 com.urp.uiws.stats.dto.* 이식. + */ +public final class StatsDtos { + + private StatsDtos() { + } + + /** 피벗 열 메타. 고정열 예 {key:"worker",label:"근무자"}; 동적열 예 {key:"company_본사",label:"본사"}. */ + public record PivotColumn(String key, String label) { + } + + /** 동적 컬럼 피벗 응답. { fixedColumns, dynamicColumns, rows } */ + public record PivotResponse( + List fixedColumns, + List dynamicColumns, + List> rows + ) { + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/stats/mapper/StatsMapper.java b/backend/src/main/java/com/zioinfo/mes/uiws/stats/mapper/StatsMapper.java new file mode 100644 index 0000000..673793c --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/stats/mapper/StatsMapper.java @@ -0,0 +1,36 @@ +package com.zioinfo.mes.uiws.stats.mapper; + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +/** + * 근무현황 피벗 집계 매퍼. 원본 StatsRepository(JdbcTemplate 네이티브) → MyBatis 변환 이식. + * + * silo 정합(코어 TB_USER/TB_COMPANY/TB_CODE 미이식): + * - 근무자 라벨: mes_user.display_name (writer_id=username 조인). 미존재 시 writer_id 노출(COALESCE). + * - 근무처(company) 라벨: company_id 직접 사용(거래처 테이블 미이식). + * - 근무상태/근무유형 라벨: 코드값 직접 사용(공통코드 미이식). + * 결과는 long-form(그룹키 + cnt). 서비스가 동적 컬럼으로 피벗한다. + */ +@Mapper +public interface StatsMapper { + + /** 개인별: 행=근무자×근무상태×근무유형, 동적열 차원=근무처. 컬럼: worker, work_status, work_type, dyn, cnt. */ + List> personalWork(@Param("from") LocalDate from, + @Param("to") LocalDate to, + @Param("userId") String userId, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds); + + /** 업체별: 행=근무처×근무유형, 동적열 차원=근무자. 컬럼: company, work_type, dyn, cnt. */ + List> companyWork(@Param("from") LocalDate from, + @Param("to") LocalDate to, + @Param("companyId") String companyId, + @Param("userId") String userId, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds); +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/stats/service/StatsService.java b/backend/src/main/java/com/zioinfo/mes/uiws/stats/service/StatsService.java new file mode 100644 index 0000000..c15de03 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/stats/service/StatsService.java @@ -0,0 +1,165 @@ +package com.zioinfo.mes.uiws.stats.service; + +import com.zioinfo.mes.uiws.common.UiwsDataScope; +import com.zioinfo.mes.uiws.stats.dto.StatsDtos.PivotColumn; +import com.zioinfo.mes.uiws.stats.dto.StatsDtos.PivotResponse; +import com.zioinfo.mes.uiws.stats.mapper.StatsMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 근무현황 통계(모듈 04) — 동적 컬럼 피벗 서비스. 원본 com.urp.uiws.stats.service.StatsService 이식. + * long-form 집계를 wide-form 으로 피벗. showStatus/showType 토글. 기본 조회기간 = 최근 1주일. + * 데이터 스코프(ADMIN=전체/그 외=본인)는 UiwsDataScope 로 silo 판정. + */ +@Service +@RequiredArgsConstructor +public class StatsService { + + /** 행 식별 키 구분자(데이터에 등장하지 않는 제어문자). */ + private static final char SEP = ''; + + private final StatsMapper mapper; + + @Transactional(readOnly = true) + public PivotResponse personalWork(LocalDate fromDate, LocalDate toDate, + String deptId, String userId, + Boolean showStatus, Boolean showType) { + LocalDate[] range = range(fromDate, toDate); + UiwsDataScope.Scope scope = UiwsDataScope.current(); + // deptId 는 코어 dept 미이식으로 silo 에서 무시(파라미터 호환만 유지). + List> agg = mapper.personalWork( + range[0], range[1], emptyToNull(userId), scope.all(), scope.ownerIds()); + + boolean status = !Boolean.FALSE.equals(showStatus); + boolean type = !Boolean.FALSE.equals(showType); + + List fixed = new ArrayList<>(); + fixed.add(new PivotColumn("worker", "근무자")); + if (status) { + fixed.add(new PivotColumn("workStatus", "근무상태")); + } + if (type) { + fixed.add(new PivotColumn("workType", "근무유형")); + } + + return pivot(agg, fixed, "company", + row -> rowKey(row, status, type), + row -> { + Map base = new LinkedHashMap<>(); + base.put("worker", str(row.get("worker"))); + if (status) { + base.put("workStatus", str(row.get("work_status"))); + } + if (type) { + base.put("workType", str(row.get("work_type"))); + } + return base; + }); + } + + @Transactional(readOnly = true) + public PivotResponse companyWork(LocalDate fromDate, LocalDate toDate, + String companyId, String userId, + Boolean showType) { + LocalDate[] range = range(fromDate, toDate); + UiwsDataScope.Scope scope = UiwsDataScope.current(); + List> agg = mapper.companyWork( + range[0], range[1], emptyToNull(companyId), emptyToNull(userId), scope.all(), scope.ownerIds()); + + boolean type = !Boolean.FALSE.equals(showType); + + List fixed = new ArrayList<>(); + fixed.add(new PivotColumn("company", "근무처")); + if (type) { + fixed.add(new PivotColumn("workType", "근무유형")); + } + + return pivot(agg, fixed, "worker", + row -> str(row.get("company")) + SEP + (type ? str(row.get("work_type")) : ""), + row -> { + Map base = new LinkedHashMap<>(); + base.put("company", str(row.get("company"))); + if (type) { + base.put("workType", str(row.get("work_type"))); + } + return base; + }); + } + + // ================================================================== 피벗 공통 + + private interface RowKeyFn { + String key(Map row); + } + + private interface BaseFn { + Map base(Map row); + } + + private PivotResponse pivot(List> agg, List fixed, + String dynPrefix, RowKeyFn keyFn, BaseFn baseFn) { + Map dynCols = new LinkedHashMap<>(); + Map> rowMap = new LinkedHashMap<>(); + + for (Map r : agg) { + String dynLabel = str(r.get("dyn")); + String dynKey = dynPrefix + "_" + dynLabel; + dynCols.putIfAbsent(dynKey, new PivotColumn(dynKey, dynLabel)); + + String rk = keyFn.key(r); + Map row = rowMap.computeIfAbsent(rk, k -> baseFn.base(r)); + long cnt = toLong(r.get("cnt")); + row.merge(dynKey, cnt, (a, b) -> toLong(a) + toLong(b)); + } + + List dynamic = new ArrayList<>(dynCols.values()); + List> rows = new ArrayList<>(); + for (Map row : rowMap.values()) { + for (PivotColumn dc : dynamic) { + row.putIfAbsent(dc.key(), 0L); + } + rows.add(row); + } + return new PivotResponse(fixed, dynamic, rows); + } + + private String rowKey(Map row, boolean status, boolean type) { + StringBuilder sb = new StringBuilder(str(row.get("worker"))); + if (status) { + sb.append(SEP).append(str(row.get("work_status"))); + } + if (type) { + sb.append(SEP).append(str(row.get("work_type"))); + } + return sb.toString(); + } + + private LocalDate[] range(LocalDate fromDate, LocalDate toDate) { + LocalDate to = (toDate != null) ? toDate : LocalDate.now(); + LocalDate from = (fromDate != null) ? fromDate : to.minusWeeks(1); + return new LocalDate[]{from, to}; + } + + private static String emptyToNull(String s) { + return (s == null || s.isBlank()) ? null : s; + } + + private static String str(Object o) { + return o == null ? "" : o.toString(); + } + + private static long toLong(Object o) { + if (o == null) { + return 0L; + } + return (o instanceof Number n) ? n.longValue() : Long.parseLong(o.toString()); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/worklog/controller/WorklogController.java b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/controller/WorklogController.java new file mode 100644 index 0000000..44f4169 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/controller/WorklogController.java @@ -0,0 +1,108 @@ +package com.zioinfo.mes.uiws.worklog.controller; + +import com.zioinfo.mes.common.ApiResponse; +import com.zioinfo.mes.uiws.worklog.dto.WorklogDtos.*; +import com.zioinfo.mes.uiws.worklog.service.WorklogService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; +import java.util.List; + +/** + * UIWS 이식 — 업무일지(모듈 06). 인증 필수(/api/worklogs). + * 원본 /pdf(JasperReports) 엔드포인트는 ERP 의존성 미보유로 제외(보고서는 후속 트랙 — erp_feature_port.md 참조). + */ +@Tag(name = "UIWS-업무일지", description = "UIWS 이식: 업무일지/시간대별 상세/댓글") +@RestController +@RequestMapping("/api/worklogs") +@RequiredArgsConstructor +public class WorklogController { + + private final WorklogService worklogService; + + @Operation(summary = "업무일지 목록(리스트형, 기본 최근 1개월)") + @GetMapping + public ApiResponse list( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, + @RequestParam(required = false) String writerId, + @RequestParam(required = false) String progressCd, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ApiResponse.ok(worklogService.list(fromDate, toDate, writerId, progressCd, page, size)); + } + + @Operation(summary = "관리자 대시보드 — 진행상태별 건수") + @GetMapping("/dashboard/progress") + public ApiResponse> progressSummary( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate) { + return ApiResponse.ok(worklogService.progressSummary(fromDate, toDate)); + } + + @Operation(summary = "업무일지 목록(달력형)") + @GetMapping("/calendar") + public ApiResponse> calendar( + @RequestParam(required = false) String yearMonth, + @RequestParam(required = false) String writerId) { + return ApiResponse.ok(worklogService.calendar(yearMonth, writerId)); + } + + @Operation(summary = "업무일지 조회 팝업") + @GetMapping("/search") + public ApiResponse> search( + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String writerId) { + return ApiResponse.ok(worklogService.search(keyword, writerId)); + } + + @Operation(summary = "업무일지 등록") + @PostMapping + public ApiResponse create(@Valid @RequestBody WorklogSaveDto dto) { + return ApiResponse.ok(worklogService.create(dto)); + } + + @Operation(summary = "업무일지 상세") + @GetMapping("/{id}") + public ApiResponse detail(@PathVariable("id") Long id) { + return ApiResponse.ok(worklogService.detail(id)); + } + + @Operation(summary = "업무일지 수정(시간대별 일괄, _state)") + @PutMapping("/{id}") + public ApiResponse update(@PathVariable("id") Long id, @Valid @RequestBody WorklogSaveDto dto) { + return ApiResponse.ok(worklogService.update(id, dto)); + } + + @Operation(summary = "업무일지 삭제") + @DeleteMapping("/{id}") + public ApiResponse delete(@PathVariable("id") Long id) { + worklogService.delete(id); + return ApiResponse.ok(null); + } + + @Operation(summary = "댓글 등록(+알림)") + @PostMapping("/{id}/comments") + public ApiResponse addComment(@PathVariable("id") Long id, + @Valid @RequestBody CommentRequest req) { + return ApiResponse.ok(worklogService.addComment(id, req)); + } + + @Operation(summary = "댓글 확인 처리(일지 작성자 전용)") + @PostMapping("/comments/{cmtId}/confirm") + public ApiResponse confirmComment(@PathVariable("cmtId") Long cmtId) { + worklogService.confirmComment(cmtId); + return ApiResponse.ok(null); + } + + @Operation(summary = "내가 단 댓글 중 작성자 미확인 목록") + @GetMapping("/comments/unconfirmed") + public ApiResponse> unconfirmedComments() { + return ApiResponse.ok(worklogService.unconfirmedByMe()); + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/worklog/dto/WorklogDtos.java b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/dto/WorklogDtos.java new file mode 100644 index 0000000..fac6c6d --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/dto/WorklogDtos.java @@ -0,0 +1,118 @@ +package com.zioinfo.mes.uiws.worklog.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.zioinfo.mes.uiws.worklog.model.UiwsWorklogDtl; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.util.List; + +/** + * 업무일지(모듈 06) DTO. 원본 com.urp.uiws.worklog.dto.* 이식(shape 동일, _state 보존). + */ +public final class WorklogDtos { + + private WorklogDtos() { + } + + public record WorklogListDto( + Long worklogId, + String title, + String writerNm, + String workDate, + String progressCd, + long commentCount + ) { + } + + public record WorklogCalendarDto( + String workDate, + Long worklogId, + String workStatusNm, + boolean isHoliday, + String holidayNm + ) { + } + + public record WorklogDetailDto( + Long worklogId, + String title, + String writerId, + String writerNm, + String workDate, + String workStatusCd, + String progressCd, + String repeatYn, + String repeatStartDate, + String repeatEndDate, + List details, + List comments + ) { + } + + public record WorklogDtlDto( + Long dtlId, + Integer startHour, + Integer endHour, + String workTypeCd, + String companyId, + String workContent, + String issueContent, + Integer sortOrd, + String createdAt, + String updatedAt, + @JsonProperty("_state") String state + ) { + public static WorklogDtlDto from(UiwsWorklogDtl d) { + return new WorklogDtlDto( + d.getDtlId(), d.getStartHour(), d.getEndHour(), d.getWorkTypeCd(), d.getCompanyId(), + d.getWorkContent(), d.getIssueContent(), d.getSortOrd(), + d.getCreatedAt() != null ? d.getCreatedAt().toString() : null, + d.getUpdatedAt() != null ? d.getUpdatedAt().toString() : null, + null); + } + } + + public record WorklogSaveDto( + @NotBlank String title, + @NotBlank String writerId, + @NotNull String workDate, + @NotBlank String workStatusCd, + String progressCd, + String repeatYn, + String repeatStartDate, + String repeatEndDate, + @Valid List details + ) { + } + + public record WorklogCommentDto( + Long cmtId, + String cmtContent, + String writerNm, + String createdAt, + String kakaoSentYn, + String confirmYn + ) { + } + + public record CommentRequest(@NotBlank String cmtContent) { + } + + public record ProgressSummaryDto(String progressCd, String progressNm, long count) { + } + + public record UnconfirmedCommentDto( + Long cmtId, + Long worklogId, + String worklogTitle, + String writerNm, + String cmtContent, + String createdAt + ) { + } + + public record WorklogPage(List content, long totalElements, int page, int size, int totalPages) { + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/worklog/mapper/WorklogMapper.java b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/mapper/WorklogMapper.java new file mode 100644 index 0000000..3f83da9 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/mapper/WorklogMapper.java @@ -0,0 +1,96 @@ +package com.zioinfo.mes.uiws.worklog.mapper; + +import com.zioinfo.mes.uiws.worklog.model.UiwsWorklog; +import com.zioinfo.mes.uiws.worklog.model.UiwsWorklogCmt; +import com.zioinfo.mes.uiws.worklog.model.UiwsWorklogDtl; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +/** + * 업무일지 MyBatis 매퍼. 원본 JPA Worklog/WorklogDtl/WorklogCmt Repository 변환 이식. + * 진행상태 집계는 ported tb_uiws_worklog 기반(코어 TB_CODE 미이식 → 코드값 직접 집계). + */ +@Mapper +public interface WorklogMapper { + + // ── worklog 헤더 + int insertWorklog(UiwsWorklog w); + + int updateWorklog(UiwsWorklog w); + + UiwsWorklog findWorklogById(@Param("worklogId") Long worklogId); + + boolean existsWorklogById(@Param("worklogId") Long worklogId); + + int deleteWorklogById(@Param("worklogId") Long worklogId); + + List searchList(@Param("from") LocalDate from, + @Param("to") LocalDate to, + @Param("writerId") String writerId, + @Param("progressCd") String progressCd, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds, + @Param("limit") int limit, + @Param("offset") int offset); + + long countList(@Param("from") LocalDate from, + @Param("to") LocalDate to, + @Param("writerId") String writerId, + @Param("progressCd") String progressCd, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds); + + List findByMonth(@Param("from") LocalDate from, + @Param("to") LocalDate to, + @Param("writerId") String writerId, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds); + + List searchPopup(@Param("keyword") String keyword, + @Param("writerId") String writerId, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds); + + /** 진행상태별 건수(progress_cd, cnt). */ + List> progressSummary(@Param("from") LocalDate from, + @Param("to") LocalDate to, + @Param("scopeAll") boolean scopeAll, + @Param("ownerIds") List ownerIds); + + // ── 상세(dtl) + int insertDtl(UiwsWorklogDtl d); + + int updateDtl(UiwsWorklogDtl d); + + int deleteDtlById(@Param("dtlId") Long dtlId); + + List findDtlByWorklogId(@Param("worklogId") Long worklogId); + + // ── 댓글(cmt) + int insertCmt(UiwsWorklogCmt c); + + UiwsWorklogCmt findCmtById(@Param("cmtId") Long cmtId); + + int updateCmtKakaoSent(@Param("cmtId") Long cmtId); + + int confirmCmt(@Param("cmtId") Long cmtId, @Param("actor") String actor); + + List findCmtByWorklogId(@Param("worklogId") Long worklogId); + + List> countCommentsByWorklogIds(@Param("ids") List ids); + + List findUnconfirmedByWriter(@Param("writerId") String writerId); + + // ── 사용자명 라벨(코어 user 재사용) + List> findUserNames(@Param("ids") List ids); + + /** 댓글 알림 메일 발송 대상 이메일(username 기준). */ + String findUserEmail(@Param("username") String username); + + List findWorklogsByIds(@Param("ids") List ids); +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklog.java b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklog.java new file mode 100644 index 0000000..4519baf --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklog.java @@ -0,0 +1,23 @@ +package com.zioinfo.mes.uiws.worklog.model; + +import lombok.Data; +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** 업무일지 헤더 (tb_uiws_worklog). 원본 com.urp.uiws.domain.Worklog 이식. */ +@Data +public class UiwsWorklog { + private Long worklogId; + private String title; + private String writerId; + private LocalDate workDate; + private String workStatusCd; + private String progressCd; // ONGOING | DONE + private String repeatYn; // Y | N + private LocalDate repeatStartDate; + private LocalDate repeatEndDate; + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklogCmt.java b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklogCmt.java new file mode 100644 index 0000000..44b5ece --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklogCmt.java @@ -0,0 +1,19 @@ +package com.zioinfo.mes.uiws.worklog.model; + +import lombok.Data; +import java.time.LocalDateTime; + +/** 업무일지 댓글 (tb_uiws_worklog_cmt). 원본 com.urp.uiws.domain.WorklogCmt 이식. */ +@Data +public class UiwsWorklogCmt { + private Long cmtId; + private Long worklogId; + private String cmtContent; + private String writerId; + private String kakaoSentYn; + private String confirmYn; + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklogDtl.java b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklogDtl.java new file mode 100644 index 0000000..d66367b --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/model/UiwsWorklogDtl.java @@ -0,0 +1,22 @@ +package com.zioinfo.mes.uiws.worklog.model; + +import lombok.Data; +import java.time.LocalDateTime; + +/** 업무일지 시간대별 상세 (tb_uiws_worklog_dtl). 원본 com.urp.uiws.domain.WorklogDtl 이식. */ +@Data +public class UiwsWorklogDtl { + private Long dtlId; + private Long worklogId; + private Integer startHour; + private Integer endHour; + private String workTypeCd; + private String companyId; + private String workContent; + private String issueContent; + private Integer sortOrd; + private String createdBy; + private LocalDateTime createdAt; + private String updatedBy; + private LocalDateTime updatedAt; +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/worklog/service/WorklogNotifier.java b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/service/WorklogNotifier.java new file mode 100644 index 0000000..98cc4d1 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/service/WorklogNotifier.java @@ -0,0 +1,31 @@ +package com.zioinfo.mes.uiws.worklog.service; + +import com.zioinfo.mes.uiws.common.mail.MailSender; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * 업무일지 댓글 알림 — 원본 NaverWorksNotifier(외부 메신저) 대신 MailSender 폴백으로 이식. + * 보안 불변규칙(외부 API 금지) 준수: 외부 메신저 호출 없이 메일/로그 채널로만 알림한다. + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class WorklogNotifier { + + private final MailSender mailSender; + + /** + * 일지 작성자에게 댓글 알림. 발송되면 true(=KAKAO_SENT_YN 'Y' 선반영). + * email 미보유 시 로그만 남기고 false. + */ + public boolean notifyComment(String writerId, String email, String subject, String body) { + if (email == null || email.isBlank()) { + log.info("[UIWS-WL-NOTIFY] no email for writer={} (skip mail, log only)", writerId); + return false; + } + mailSender.send(email, subject, body); + return true; + } +} diff --git a/backend/src/main/java/com/zioinfo/mes/uiws/worklog/service/WorklogService.java b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/service/WorklogService.java new file mode 100644 index 0000000..954ac72 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mes/uiws/worklog/service/WorklogService.java @@ -0,0 +1,438 @@ +package com.zioinfo.mes.uiws.worklog.service; + +import com.zioinfo.mes.uiws.common.UiwsApiException; +import com.zioinfo.mes.uiws.common.UiwsCurrentUser; +import com.zioinfo.mes.uiws.common.UiwsDataScope; +import com.zioinfo.mes.uiws.common.UiwsErrorCode; +import com.zioinfo.mes.uiws.worklog.dto.WorklogDtos.*; +import com.zioinfo.mes.uiws.worklog.mapper.WorklogMapper; +import com.zioinfo.mes.uiws.worklog.model.UiwsWorklog; +import com.zioinfo.mes.uiws.worklog.model.UiwsWorklogCmt; +import com.zioinfo.mes.uiws.worklog.model.UiwsWorklogDtl; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 업무일지(모듈 06) 서비스 — 원본 com.urp.uiws.worklog.service.WorklogService MyBatis 변환 이식. + * + * silo 단순화(코어 TB_CODE/TB_DEPT 미이식): + * - 근무상태/진행 코드 라벨: 코드값 그대로 노출(공통코드 미이식). 진행 라벨은 ONGOING/DONE 한글 매핑만 내장. + * - 진행상태 집계: ONGOING/DONE 고정 셋 0건 포함 반환(차트 범례 안정). + * - 댓글 권한: 원본 "관할 상무 이상"(부서계층+직급) → ERP RBAC MANAGER/ADMIN/CFO 로 완화 이식. + * - 댓글 알림: NaverWorks(외부) → MailSender 폴백(외부 API 금지 준수). + */ +@Service +@RequiredArgsConstructor +public class WorklogService { + + private static final String DEFAULT_PROGRESS = "ONGOING"; + private static final DateTimeFormatter DT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + /** 진행 코드 → 라벨(공통코드 미이식 silo 보정). */ + private static final Map PROGRESS_LABEL = Map.of("ONGOING", "진행중", "DONE", "종료"); + + private final WorklogMapper mapper; + private final WorklogNotifier notifier; + + // ------------------------------------------------------------------ 목록(리스트형) + @Transactional(readOnly = true) + public WorklogPage list(LocalDate fromDate, LocalDate toDate, String writerId, String progressCd, int page, int size) { + LocalDate to = (toDate != null) ? toDate : LocalDate.now(); + LocalDate from = (fromDate != null) ? fromDate : to.minusMonths(1); + UiwsDataScope.Scope scope = UiwsDataScope.current(); + String wid = blankToNull(writerId); + String pc = blankToNull(progressCd); + long total = mapper.countList(from, to, wid, pc, scope.all(), scope.ownerIds()); + List rows = mapper.searchList(from, to, wid, pc, scope.all(), scope.ownerIds(), size, page * size); + return new WorklogPage(toListDtos(rows), total, page, size, totalPages(total, size)); + } + + // ------------------------------------------------------------------ 목록(달력형) + @Transactional(readOnly = true) + public List calendar(String yearMonth, String writerId) { + YearMonth ym = parseYearMonth(yearMonth); + LocalDate from = ym.atDay(1); + LocalDate to = ym.atEndOfMonth(); + UiwsDataScope.Scope scope = UiwsDataScope.current(); + List rows = mapper.findByMonth(from, to, blankToNull(writerId), scope.all(), scope.ownerIds()); + // 공휴일 마스터 미연동 → isHoliday=false. 근무상태 라벨은 코드값 노출(공통코드 미이식). + return rows.stream() + .map(w -> new WorklogCalendarDto(w.getWorkDate().toString(), w.getWorklogId(), + w.getWorkStatusCd(), false, null)) + .toList(); + } + + // ------------------------------------------------------------------ 조회 팝업 + @Transactional(readOnly = true) + public List search(String keyword, String writerId) { + UiwsDataScope.Scope scope = UiwsDataScope.current(); + List rows = mapper.searchPopup(blankToNull(keyword), blankToNull(writerId), scope.all(), scope.ownerIds()); + return toListDtos(rows); + } + + // ------------------------------------------------------------------ 대시보드: 진행상태별 집계 + @Transactional(readOnly = true) + public List progressSummary(LocalDate fromDate, LocalDate toDate) { + LocalDate to = (toDate != null) ? toDate : LocalDate.now(); + LocalDate from = (fromDate != null) ? fromDate : to.minusMonths(1); + UiwsDataScope.Scope scope = UiwsDataScope.current(); + Map counts = new LinkedHashMap<>(); + for (Map r : mapper.progressSummary(from, to, scope.all(), scope.ownerIds())) { + counts.put(str(r.get("progressCd")), toLong(r.get("cnt"))); + } + // 코드 정의 순서(진행중→종료)로 0건 포함 반환. + List out = new ArrayList<>(); + for (String code : List.of("ONGOING", "DONE")) { + out.add(new ProgressSummaryDto(code, PROGRESS_LABEL.getOrDefault(code, code), counts.getOrDefault(code, 0L))); + } + // 정의 외 코드값도 누락 없이 추가 + counts.forEach((k, v) -> { + if (!"ONGOING".equals(k) && !"DONE".equals(k)) { + out.add(new ProgressSummaryDto(k, k, v)); + } + }); + return out; + } + + // ------------------------------------------------------------------ 등록 + @Transactional + public WorklogDetailDto create(WorklogSaveDto dto) { + String actor = UiwsCurrentUser.id(); + UiwsWorklog w = new UiwsWorklog(); + applyHeader(w, dto); + w.setWriterId((dto.writerId() != null && !dto.writerId().isBlank()) ? dto.writerId() : actor); + w.setCreatedBy(actor); + w.setCreatedAt(LocalDateTime.now()); + mapper.insertWorklog(w); + + List toInsert = (dto.details() == null) ? List.of() + : dto.details().stream().filter(d -> !"DEL".equalsIgnoreCase(safeState(d.state()))).toList(); + validateNoOverlap(toInsert); + for (WorklogDtlDto d : toInsert) { + mapper.insertDtl(newDtl(w.getWorklogId(), d, actor)); + } + return detail(w.getWorklogId()); + } + + // ------------------------------------------------------------------ 상세 + @Transactional(readOnly = true) + public WorklogDetailDto detail(Long worklogId) { + return toDetail(findWorklog(worklogId)); + } + + // ------------------------------------------------------------------ 수정(시간대별 일괄, _state) + @Transactional + public WorklogDetailDto update(Long worklogId, WorklogSaveDto dto) { + String actor = UiwsCurrentUser.id(); + UiwsWorklog w = findWorklog(worklogId); + applyHeader(w, dto); + if (dto.writerId() != null && !dto.writerId().isBlank()) { + w.setWriterId(dto.writerId()); + } + w.setUpdatedBy(actor); + w.setUpdatedAt(LocalDateTime.now()); + mapper.updateWorklog(w); + + List existing = mapper.findDtlByWorklogId(worklogId); + Map existingById = existing.stream() + .collect(Collectors.toMap(UiwsWorklogDtl::getDtlId, d -> d)); + + List details = (dto.details() == null) ? List.of() : dto.details(); + List survivors = new ArrayList<>(); + for (WorklogDtlDto d : details) { + String st = safeState(d.state()); + if ("DEL".equalsIgnoreCase(st)) { + if (d.dtlId() != null && existingById.containsKey(d.dtlId())) { + mapper.deleteDtlById(d.dtlId()); + } + continue; + } + if ("MOD".equalsIgnoreCase(st) && d.dtlId() != null) { + UiwsWorklogDtl tgt = existingById.get(d.dtlId()); + if (tgt == null) { + throw new UiwsApiException(UiwsErrorCode.WORKLOG_NOT_FOUND, "수정 대상 상세를 찾을 수 없습니다."); + } + applyDtl(tgt, d); + tgt.setUpdatedBy(actor); + tgt.setUpdatedAt(LocalDateTime.now()); + mapper.updateDtl(tgt); + survivors.add(d); + continue; + } + // _state 미표기 + 기존 dtlId 보유 = 미변경 유지행 → INSERT 금지 + if (d.dtlId() != null && existingById.containsKey(d.dtlId())) { + survivors.add(d); + continue; + } + // ADD 또는 진짜 신규 → INSERT + mapper.insertDtl(newDtl(worklogId, d, actor)); + survivors.add(d); + } + validateNoOverlap(survivors); + return detail(worklogId); + } + + // ------------------------------------------------------------------ 삭제 + @Transactional + public void delete(Long worklogId) { + if (!mapper.existsWorklogById(worklogId)) { + throw new UiwsApiException(UiwsErrorCode.WORKLOG_NOT_FOUND); + } + // 상세/댓글은 DB ON DELETE CASCADE. 헤더 삭제로 일괄 제거. + mapper.deleteWorklogById(worklogId); + } + + // ------------------------------------------------------------------ 댓글 등록(+알림) + @Transactional + public WorklogCommentDto addComment(Long worklogId, CommentRequest req) { + String actor = UiwsCurrentUser.id(); + UiwsWorklog w = findWorklog(worklogId); + assertCanComment(); + + UiwsWorklogCmt c = new UiwsWorklogCmt(); + c.setWorklogId(worklogId); + c.setCmtContent(req.cmtContent()); + c.setWriterId(actor); + c.setKakaoSentYn("N"); + c.setConfirmYn("N"); + c.setCreatedBy(actor); + c.setCreatedAt(LocalDateTime.now()); + mapper.insertCmt(c); + + // 알림: 일지 작성자에게 메일 폴백(외부 메신저 미사용). + String writerEmail = userEmail(w.getWriterId()); + String subject = "[UIWS] 업무일지 새 댓글: " + w.getTitle(); + String body = "업무일지에 새 댓글이 등록되었습니다.\n내용: " + req.cmtContent(); + boolean sent = notifier.notifyComment(w.getWriterId(), writerEmail, subject, body); + if (sent) { + mapper.updateCmtKakaoSent(c.getCmtId()); + c.setKakaoSentYn("Y"); + } + + String writerNm = userNames(List.of(actor)).getOrDefault(actor, actor); + return new WorklogCommentDto(c.getCmtId(), c.getCmtContent(), writerNm, + fmt(c.getCreatedAt()), c.getKakaoSentYn(), c.getConfirmYn()); + } + + // ------------------------------------------------------------------ 댓글 확인(작성자 전용) + @Transactional + public void confirmComment(Long cmtId) { + String actor = UiwsCurrentUser.id(); + UiwsWorklogCmt c = mapper.findCmtById(cmtId); + if (c == null) { + throw new UiwsApiException(UiwsErrorCode.WORKLOG_NOT_FOUND, "댓글을 찾을 수 없습니다."); + } + UiwsWorklog w = findWorklog(c.getWorklogId()); + if (!w.getWriterId().equals(actor)) { + throw new UiwsApiException(UiwsErrorCode.FORBIDDEN, "본인 업무일지의 댓글만 확인 처리할 수 있습니다."); + } + mapper.confirmCmt(cmtId, actor); + } + + // ------------------------------------------------------------------ 내가 단 댓글 중 작성자 미확인 목록 + @Transactional(readOnly = true) + public List unconfirmedByMe() { + String me = UiwsCurrentUser.id(); + List rows = mapper.findUnconfirmedByWriter(me); + if (rows.isEmpty()) { + return List.of(); + } + List worklogIds = rows.stream().map(UiwsWorklogCmt::getWorklogId).distinct().toList(); + Map worklogs = mapper.findWorklogsByIds(worklogIds).stream() + .collect(Collectors.toMap(UiwsWorklog::getWorklogId, wl -> wl)); + Map writerNames = userNames( + worklogs.values().stream().map(UiwsWorklog::getWriterId).toList()); + return rows.stream().map(c -> { + UiwsWorklog wl = worklogs.get(c.getWorklogId()); + return new UnconfirmedCommentDto(c.getCmtId(), c.getWorklogId(), + wl != null ? wl.getTitle() : null, + wl != null ? writerNames.getOrDefault(wl.getWriterId(), wl.getWriterId()) : null, + c.getCmtContent(), fmt(c.getCreatedAt())); + }).toList(); + } + + // ================================================================== helpers + + /** 댓글 권한(silo 완화): ERP RBAC MANAGER/ADMIN/CFO 만 작성 가능. */ + private void assertCanComment() { + if (!UiwsCurrentUser.isManagerOrAbove()) { + throw new UiwsApiException(UiwsErrorCode.FORBIDDEN, "댓글은 관리자/매니저 권한만 작성할 수 있습니다."); + } + } + + private List toListDtos(List rows) { + Map cmtCounts = commentCounts(rows.stream().map(UiwsWorklog::getWorklogId).toList()); + Map writerNames = userNames(rows.stream().map(UiwsWorklog::getWriterId).toList()); + return rows.stream() + .map(w -> new WorklogListDto(w.getWorklogId(), w.getTitle(), + writerNames.getOrDefault(w.getWriterId(), w.getWriterId()), + w.getWorkDate().toString(), w.getProgressCd(), + cmtCounts.getOrDefault(w.getWorklogId(), 0L))) + .toList(); + } + + private WorklogDetailDto toDetail(UiwsWorklog w) { + List dtls = mapper.findDtlByWorklogId(w.getWorklogId()); + List cmts = mapper.findCmtByWorklogId(w.getWorklogId()); + List nameIds = new ArrayList<>(); + nameIds.add(w.getWriterId()); + cmts.forEach(c -> nameIds.add(c.getWriterId())); + Map writerNames = userNames(nameIds); + + List details = dtls.stream().map(WorklogDtlDto::from).toList(); + List comments = cmts.stream() + .map(c -> new WorklogCommentDto(c.getCmtId(), c.getCmtContent(), + writerNames.getOrDefault(c.getWriterId(), c.getWriterId()), + fmt(c.getCreatedAt()), c.getKakaoSentYn(), c.getConfirmYn())) + .toList(); + return new WorklogDetailDto(w.getWorklogId(), w.getTitle(), w.getWriterId(), + writerNames.getOrDefault(w.getWriterId(), w.getWriterId()), w.getWorkDate().toString(), + w.getWorkStatusCd(), w.getProgressCd(), w.getRepeatYn(), + w.getRepeatStartDate() != null ? w.getRepeatStartDate().toString() : null, + w.getRepeatEndDate() != null ? w.getRepeatEndDate().toString() : null, + details, comments); + } + + private void applyHeader(UiwsWorklog w, WorklogSaveDto dto) { + w.setTitle(dto.title()); + w.setWorkDate(parseDate(dto.workDate())); + w.setWorkStatusCd(dto.workStatusCd()); + w.setProgressCd((dto.progressCd() != null && !dto.progressCd().isBlank()) ? dto.progressCd() : DEFAULT_PROGRESS); + w.setRepeatYn((dto.repeatYn() != null && !dto.repeatYn().isBlank()) ? dto.repeatYn() : "N"); + w.setRepeatStartDate(parseDateNullable(dto.repeatStartDate())); + w.setRepeatEndDate(parseDateNullable(dto.repeatEndDate())); + } + + private UiwsWorklogDtl newDtl(Long worklogId, WorklogDtlDto d, String actor) { + UiwsWorklogDtl e = new UiwsWorklogDtl(); + e.setWorklogId(worklogId); + applyDtl(e, d); + e.setCreatedBy(actor); + e.setCreatedAt(LocalDateTime.now()); + return e; + } + + private void applyDtl(UiwsWorklogDtl e, WorklogDtlDto d) { + if (d.startHour() == null || d.endHour() == null + || d.startHour() < 0 || d.endHour() > 24 || d.endHour() < d.startHour()) { + throw new UiwsApiException(UiwsErrorCode.WORKLOG_TIME_INVALID); + } + e.setStartHour(d.startHour()); + e.setEndHour(d.endHour()); + e.setWorkTypeCd(d.workTypeCd()); + e.setCompanyId(d.companyId()); + e.setWorkContent(d.workContent()); + e.setIssueContent(d.issueContent()); + e.setSortOrd(d.sortOrd() != null ? d.sortOrd() : 0); + } + + private void validateNoOverlap(List details) { + List rows = details.stream() + .filter(d -> d.startHour() != null && d.endHour() != null) + .sorted((a, b) -> Integer.compare(a.startHour(), b.startHour())) + .toList(); + for (int i = 1; i < rows.size(); i++) { + WorklogDtlDto prev = rows.get(i - 1); + WorklogDtlDto cur = rows.get(i); + if (cur.startHour() < prev.endHour()) { + throw new UiwsApiException(UiwsErrorCode.WORKLOG_TIME_OVERLAP); + } + } + } + + private UiwsWorklog findWorklog(Long id) { + UiwsWorklog w = mapper.findWorklogById(id); + if (w == null) { + throw new UiwsApiException(UiwsErrorCode.WORKLOG_NOT_FOUND); + } + return w; + } + + private Map commentCounts(List worklogIds) { + if (worklogIds == null || worklogIds.isEmpty()) { + return Map.of(); + } + Map result = new LinkedHashMap<>(); + for (Map cc : mapper.countCommentsByWorklogIds(worklogIds)) { + result.put(toLong(cc.get("worklogId")), toLong(cc.get("cnt"))); + } + return result; + } + + private Map userNames(List userIds) { + List ids = userIds.stream().filter(s -> s != null && !s.isBlank()).distinct().toList(); + if (ids.isEmpty()) { + return Map.of(); + } + return mapper.findUserNames(ids).stream() + .collect(Collectors.toMap(r -> r.get("username"), r -> r.get("fullName"), (a, b) -> a)); + } + + /** writerId(username) → email (댓글 알림 메일 발송용). 미보유 시 null. */ + private String userEmail(String writerId) { + if (writerId == null || writerId.isBlank()) { + return null; + } + return mapper.findUserEmail(writerId); + } + + private static int totalPages(long total, int size) { + return size <= 0 ? 0 : (int) ((total + size - 1) / size); + } + + private static String blankToNull(String s) { + return (s == null || s.isBlank()) ? null : s; + } + + private static String safeState(String s) { + return s == null ? "" : s.trim(); + } + + private static String str(Object o) { + return o == null ? "" : o.toString(); + } + + private static long toLong(Object o) { + if (o == null) { + return 0L; + } + return (o instanceof Number n) ? n.longValue() : Long.parseLong(o.toString()); + } + + private static String fmt(LocalDateTime dt) { + return dt != null ? dt.format(DT) : null; + } + + private static LocalDate parseDate(String s) { + try { + return LocalDate.parse(s); + } catch (Exception e) { + throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, "날짜 형식이 올바르지 않습니다(yyyy-MM-dd)."); + } + } + + private static LocalDate parseDateNullable(String s) { + return (s == null || s.isBlank()) ? null : parseDate(s); + } + + private static YearMonth parseYearMonth(String s) { + try { + if (s == null || s.isBlank()) { + return YearMonth.now(); + } + return YearMonth.parse(s); + } catch (Exception e) { + throw new UiwsApiException(UiwsErrorCode.INVALID_REQUEST, "yearMonth 형식이 올바르지 않습니다(yyyy-MM)."); + } + } +} diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml index 7b1057b..b36dff0 100644 --- a/backend/src/main/resources/application.yml +++ b/backend/src/main/resources/application.yml @@ -15,8 +15,11 @@ spring: minimum-idle: 1 sql: init: - mode: ${SQL_INIT_MODE:never} - schema-locations: classpath:db/schema.sql + # UIWS 이식: 91_uiws_port.sql(tb_uiws_* + mes_user 2FA ALTER, 전부 멱등)만 부팅 시 적용. + # 기존 schema.sql 은 deploy_server 가 psql 로 별도 적용(비멱등 시드 충돌 회피). + mode: ${SQL_INIT_MODE:always} + schema-locations: classpath:db/91_uiws_port.sql + continue-on-error: true servlet: multipart: max-file-size: 20MB @@ -34,6 +37,19 @@ springdoc: swagger-ui: path: /api/mes/swagger +# ── UIWS 이식 모듈 설정 (worklog/schedule/message/stats + 2FA 레이어) ────────── +mes: + uiws: + auth: + twofa-enabled: ${UIWS_2FA:true} # off=기존 단일로그인 회귀 0 + verify-token-validity-seconds: 300 # 1차 통과 후 verify-token 5분 + email-code-validity-seconds: 300 # 이메일 인증코드 5분 + max-login-fail: 5 # 실패 5회 누적 시 계정 잠금 + mail: + mode: ${UIWS_MAIL_MODE:log} # LogMailSender 폴백(외부 API 0). 운영 smtp 시 별도 빈 + upload: + upload-dir: ${UIWS_UPLOAD_DIR:./uploads/uiws} + guardia: erp-url: ${ERP_URL:http://localhost:8003} itsm-url: ${ITSM_URL:http://localhost:9001} diff --git a/backend/src/main/resources/db/91_uiws_port.sql b/backend/src/main/resources/db/91_uiws_port.sql new file mode 100644 index 0000000..c6b6a91 --- /dev/null +++ b/backend/src/main/resources/db/91_uiws_port.sql @@ -0,0 +1,251 @@ +-- ============================================================================ +-- UIWS 업무 테이블 이식 (MES, ERP 파일럿 복제·치환) — 2026-06-20, uiws-schema-porter +-- 계획서: .claude/agents/_workspace/uiws_port_plan.md (schema-porter 트랙 6.1) +-- 원본: workspace/uiws/db/{03_worklog,04_schedule,05_message,02_core(2FA)}.sql +-- +-- 네임스페이스 격리: UIWS TB_* → 소문자 tb_uiws_ 프리픽스 (기존 tb_audit_log 등과 충돌 회피). +-- 멱등: 전부 CREATE TABLE IF NOT EXISTS / ADD COLUMN IF NOT EXISTS / ON CONFLICT DO NOTHING. +-- mode:always 재실행 시 완전 멱등(기존 schema.sql·시드 무영향). +-- FK 정책: tb_uiws_* 내부 참조만 물리 FK. 외부 user/code/company/dept FK는 논리참조로 완화 +-- (UIWS는 VARCHAR USER_ID 키 / ERP user PK는 BIGSERIAL — 키 체계 불일치 → 컬럼만 유지). +-- 코드값(WORK_STATUS_CD/WORK_TYPE_CD/RCV_TYPE 등): TB_CODE 미이식 → 일반 컬럼 + CHECK만 유지. +-- ============================================================================ + +SET client_encoding = 'UTF8'; + +-- ─────────────────────────────────────────────────────────────────────────── +-- [worklog] tb_uiws_worklog — 업무일지 헤더 (원본 TB_WORKLOG) +-- ─────────────────────────────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS tb_uiws_worklog ( + worklog_id BIGINT GENERATED ALWAYS AS IDENTITY, + title VARCHAR(200) NOT NULL, + writer_id VARCHAR(20) NOT NULL, -- 논리참조(UIWS USER_ID) + work_date DATE NOT NULL, + work_status_cd VARCHAR(30) NOT NULL, -- WORK_STATUS 코드값(논리) + progress_cd VARCHAR(30) NOT NULL DEFAULT 'ONGOING', + repeat_yn CHAR(1) NOT NULL DEFAULT 'N', + repeat_start_date DATE, + repeat_end_date DATE, + created_by VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_worklog PRIMARY KEY (worklog_id), + CONSTRAINT ck_uiws_worklog_progress CHECK (progress_cd IN ('ONGOING','DONE')), + CONSTRAINT ck_uiws_worklog_repeat_yn CHECK (repeat_yn IN ('Y','N')) +); +COMMENT ON TABLE tb_uiws_worklog IS 'UIWS 이식: 업무일지 헤더 (근무일자/근무상태/반복)'; + +-- tb_uiws_worklog_dtl — 시간대별 상세 (통계 집계 원천, 원본 TB_WORKLOG_DTL) +CREATE TABLE IF NOT EXISTS tb_uiws_worklog_dtl ( + dtl_id BIGINT GENERATED ALWAYS AS IDENTITY, + worklog_id BIGINT NOT NULL, + start_hour INT NOT NULL, + end_hour INT NOT NULL, + work_type_cd VARCHAR(30) NOT NULL, -- WORK_TYPE 코드값(논리) + company_id VARCHAR(20) NOT NULL, -- 논리참조(UIWS COMPANY_ID) + work_content TEXT, + issue_content TEXT, + sort_ord INT DEFAULT 0, + created_by VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_worklog_dtl PRIMARY KEY (dtl_id), + CONSTRAINT fk_uiws_dtl_worklog FOREIGN KEY (worklog_id) + REFERENCES tb_uiws_worklog (worklog_id) ON DELETE CASCADE, + CONSTRAINT ck_uiws_dtl_start_hour CHECK (start_hour BETWEEN 0 AND 24), + CONSTRAINT ck_uiws_dtl_end_hour CHECK (end_hour BETWEEN 0 AND 24), + CONSTRAINT ck_uiws_dtl_hour_order CHECK (end_hour >= start_hour) +); +COMMENT ON TABLE tb_uiws_worklog_dtl IS 'UIWS 이식: 업무일지 시간대별 상세 (헤더 삭제 시 CASCADE)'; + +-- tb_uiws_worklog_cmt — 댓글 (원본 TB_WORKLOG_CMT) +CREATE TABLE IF NOT EXISTS tb_uiws_worklog_cmt ( + cmt_id BIGINT GENERATED ALWAYS AS IDENTITY, + worklog_id BIGINT NOT NULL, + cmt_content TEXT NOT NULL, + writer_id VARCHAR(20) NOT NULL, -- 논리참조 + kakao_sent_yn CHAR(1) NOT NULL DEFAULT 'N', + confirm_yn CHAR(1) NOT NULL DEFAULT 'N', + created_by VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_worklog_cmt PRIMARY KEY (cmt_id), + CONSTRAINT fk_uiws_cmt_worklog FOREIGN KEY (worklog_id) + REFERENCES tb_uiws_worklog (worklog_id) ON DELETE CASCADE, + CONSTRAINT ck_uiws_cmt_confirm_yn CHECK (confirm_yn IN ('Y','N')), + CONSTRAINT ck_uiws_cmt_kakao_yn CHECK (kakao_sent_yn IN ('Y','N')) +); +COMMENT ON TABLE tb_uiws_worklog_cmt IS 'UIWS 이식: 업무일지 댓글 (등록 시 카카오 알림톡)'; + +CREATE INDEX IF NOT EXISTS ix_uiws_worklog_date_writer ON tb_uiws_worklog (work_date, writer_id, work_status_cd); +CREATE INDEX IF NOT EXISTS ix_uiws_worklog_writer ON tb_uiws_worklog (writer_id); +CREATE INDEX IF NOT EXISTS ix_uiws_dtl_type_company ON tb_uiws_worklog_dtl (work_type_cd, company_id); +CREATE INDEX IF NOT EXISTS ix_uiws_dtl_worklog ON tb_uiws_worklog_dtl (worklog_id); +CREATE INDEX IF NOT EXISTS ix_uiws_dtl_company ON tb_uiws_worklog_dtl (company_id); +CREATE INDEX IF NOT EXISTS ix_uiws_cmt_worklog ON tb_uiws_worklog_cmt (worklog_id); + +-- ─────────────────────────────────────────────────────────────────────────── +-- [schedule] tb_uiws_schedule — 일정 개인/부서 (원본 TB_SCHEDULE) +-- ─────────────────────────────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS tb_uiws_schedule ( + schedule_id BIGINT GENERATED ALWAYS AS IDENTITY, + sche_type VARCHAR(10) NOT NULL, + title VARCHAR(200) NOT NULL, + sche_gubun_cd VARCHAR(30), + importance_cd VARCHAR(30), + start_dt TIMESTAMP NOT NULL, + end_dt TIMESTAMP NOT NULL, + content TEXT, + owner_id VARCHAR(20) NOT NULL, -- 논리참조 + dept_id VARCHAR(20), -- 논리참조 + charger_id VARCHAR(20), -- 논리참조 + created_by VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_schedule PRIMARY KEY (schedule_id), + CONSTRAINT ck_uiws_sche_type CHECK (sche_type IN ('PERSONAL','DEPT')), + CONSTRAINT ck_uiws_sche_dt_order CHECK (end_dt >= start_dt) +); +COMMENT ON TABLE tb_uiws_schedule IS 'UIWS 이식: 일정(개인 PERSONAL / 부서 DEPT)'; + +-- tb_uiws_diary — 일지(일정 연계 선택, 원본 TB_DIARY) +CREATE TABLE IF NOT EXISTS tb_uiws_diary ( + diary_id BIGINT GENERATED ALWAYS AS IDENTITY, + title VARCHAR(200) NOT NULL, + content TEXT, + schedule_id BIGINT, + writer_id VARCHAR(20) NOT NULL, -- 논리참조 + diary_date DATE, + created_by VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_diary PRIMARY KEY (diary_id), + CONSTRAINT fk_uiws_diary_sche FOREIGN KEY (schedule_id) + REFERENCES tb_uiws_schedule (schedule_id) ON DELETE SET NULL +); +COMMENT ON TABLE tb_uiws_diary IS 'UIWS 이식: 일지 (일정 연계 선택, 일정 삭제 시 연계 해제)'; + +-- tb_uiws_attach — 첨부파일 폴리모픽 (원본 TB_ATTACH, 물리 FK 미적용) +CREATE TABLE IF NOT EXISTS tb_uiws_attach ( + attach_id BIGINT GENERATED ALWAYS AS IDENTITY, + ref_type VARCHAR(20) NOT NULL, + ref_id BIGINT NOT NULL, + file_nm VARCHAR(255) NOT NULL, + file_path VARCHAR(500) NOT NULL, + file_size BIGINT, + created_by VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_attach PRIMARY KEY (attach_id), + CONSTRAINT ck_uiws_attach_ref_type CHECK (ref_type IN ('SCHEDULE','DIARY')), + CONSTRAINT ck_uiws_attach_size CHECK (file_size IS NULL OR file_size >= 0) +); +COMMENT ON TABLE tb_uiws_attach IS 'UIWS 이식: 첨부파일 (폴리모픽 REF_TYPE=SCHEDULE/DIARY)'; + +CREATE INDEX IF NOT EXISTS ix_uiws_sche_dt_range ON tb_uiws_schedule (start_dt, end_dt, sche_type); +CREATE INDEX IF NOT EXISTS ix_uiws_sche_owner ON tb_uiws_schedule (owner_id); +CREATE INDEX IF NOT EXISTS ix_uiws_sche_dept ON tb_uiws_schedule (dept_id); +CREATE INDEX IF NOT EXISTS ix_uiws_diary_sche ON tb_uiws_diary (schedule_id); +CREATE INDEX IF NOT EXISTS ix_uiws_diary_writer ON tb_uiws_diary (writer_id, diary_date); +CREATE INDEX IF NOT EXISTS ix_uiws_attach_ref ON tb_uiws_attach (ref_type, ref_id); + +-- ─────────────────────────────────────────────────────────────────────────── +-- [message] tb_uiws_message — 쪽지 헤더 (원본 TB_MESSAGE) +-- REF_WORKLOG_ID → tb_uiws_worklog (내부 FK 유지), REPLY_TO_ID → 자기참조. +-- ─────────────────────────────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS tb_uiws_message ( + message_id BIGINT GENERATED ALWAYS AS IDENTITY, + sender_id VARCHAR(20) NOT NULL, -- 논리참조 + title VARCHAR(200) NOT NULL, + content TEXT NOT NULL, + ref_worklog_id BIGINT, + reply_to_id BIGINT, + sent_at TIMESTAMP NOT NULL DEFAULT now(), + sender_del_yn CHAR(1) NOT NULL DEFAULT 'N', + created_by VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_message PRIMARY KEY (message_id), + CONSTRAINT fk_uiws_msg_worklog FOREIGN KEY (ref_worklog_id) + REFERENCES tb_uiws_worklog (worklog_id) ON DELETE SET NULL, + CONSTRAINT fk_uiws_msg_reply FOREIGN KEY (reply_to_id) + REFERENCES tb_uiws_message (message_id), + CONSTRAINT ck_uiws_msg_sender_del_yn CHECK (sender_del_yn IN ('Y','N')) +); +COMMENT ON TABLE tb_uiws_message IS 'UIWS 이식: 쪽지 헤더 (참조 업무일지/답장 원본 자기참조)'; + +-- tb_uiws_message_rcv — 수신자 (원본 TB_MESSAGE_RCV) +CREATE TABLE IF NOT EXISTS tb_uiws_message_rcv ( + rcv_id BIGINT GENERATED ALWAYS AS IDENTITY, + message_id BIGINT NOT NULL, + receiver_id VARCHAR(20) NOT NULL, -- 논리참조 + rcv_type VARCHAR(10) NOT NULL, -- MSG_RCV_TYPE 코드값(논리) + read_yn CHAR(1) NOT NULL DEFAULT 'N', + read_at TIMESTAMP, + receiver_del_yn CHAR(1) NOT NULL DEFAULT 'N', + created_by VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_message_rcv PRIMARY KEY (rcv_id), + CONSTRAINT fk_uiws_rcv_message FOREIGN KEY (message_id) + REFERENCES tb_uiws_message (message_id) ON DELETE CASCADE, + CONSTRAINT uq_uiws_rcv_msg_receiver UNIQUE (message_id, receiver_id), + CONSTRAINT ck_uiws_rcv_type CHECK (rcv_type IN ('RECV','REF')), + CONSTRAINT ck_uiws_rcv_read_yn CHECK (read_yn IN ('Y','N')), + CONSTRAINT ck_uiws_rcv_del_yn CHECK (receiver_del_yn IN ('Y','N')) +); +COMMENT ON TABLE tb_uiws_message_rcv IS 'UIWS 이식: 쪽지 수신자(수신 RECV/참조 REF, 개봉여부)'; + +CREATE INDEX IF NOT EXISTS ix_uiws_rcv_receiver_read ON tb_uiws_message_rcv (receiver_id, read_yn); +CREATE INDEX IF NOT EXISTS ix_uiws_rcv_message ON tb_uiws_message_rcv (message_id); +CREATE INDEX IF NOT EXISTS ix_uiws_msg_sender ON tb_uiws_message (sender_id, sent_at); + +-- ─────────────────────────────────────────────────────────────────────────── +-- [2FA] tb_uiws_login_verify — 로그인 2차 검증 코드 (원본 TB_LOGIN_VERIFY) +-- USER_ID 는 논리참조(외부 user FK 미적용 — 키 체계 불일치). +-- ─────────────────────────────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS tb_uiws_login_verify ( + verify_id BIGINT GENERATED ALWAYS AS IDENTITY, + user_id VARCHAR(50) NOT NULL, -- MES username 논리참조 + verify_method VARCHAR(20) NOT NULL DEFAULT 'EMAIL', + verify_code VARCHAR(10) NOT NULL, + expire_at TIMESTAMP NOT NULL, + verified_yn CHAR(1) NOT NULL DEFAULT 'N', + created_by VARCHAR(20) NOT NULL DEFAULT 'SYSTEM', + created_at TIMESTAMP NOT NULL DEFAULT now(), + updated_by VARCHAR(20), + updated_at TIMESTAMP, + CONSTRAINT pk_tb_uiws_login_verify PRIMARY KEY (verify_id), + CONSTRAINT ck_uiws_verify_yn CHECK (verified_yn IN ('Y','N')), + CONSTRAINT ck_uiws_verify_method CHECK (verify_method IN ('EMAIL','OTP')) +); +COMMENT ON TABLE tb_uiws_login_verify IS 'UIWS 이식(2FA): 로그인 2차 검증 코드(이메일/OTP, 만료)'; +CREATE INDEX IF NOT EXISTS ix_uiws_verify_user ON tb_uiws_login_verify (user_id, verified_yn); + +-- ─────────────────────────────────────────────────────────────────────────── +-- [2FA] 기존 user 테이블 컬럼 보강 (DROP/재정의 금지 — ADD COLUMN IF NOT EXISTS 멱등) +-- ★ MES mes_user 는 email 컬럼 미보유(원본: username/password_hash/display_name/role/is_active) +-- → 2FA 발송 대상 확보를 위해 email 포함 6컬럼 ALTER(Portal 사례와 동일, ERP는 email 기보유라 5컬럼). +-- 이메일·인증코드·만료시각, 실패 카운트(기본 0), 잠금(기본 false), OTP 시크릿. +-- ─────────────────────────────────────────────────────────────────────────── +ALTER TABLE mes_user ADD COLUMN IF NOT EXISTS email VARCHAR(255); +ALTER TABLE mes_user ADD COLUMN IF NOT EXISTS email_verify_code VARCHAR(10); +ALTER TABLE mes_user ADD COLUMN IF NOT EXISTS email_verify_expire TIMESTAMP; +ALTER TABLE mes_user ADD COLUMN IF NOT EXISTS login_fail_count INT DEFAULT 0; +ALTER TABLE mes_user ADD COLUMN IF NOT EXISTS locked BOOLEAN DEFAULT false; +ALTER TABLE mes_user ADD COLUMN IF NOT EXISTS otp_secret VARCHAR(255); + +-- ─────────────────────────────────────────────────────────────────────────── +-- [메뉴] MES 는 DB 메뉴/RBAC 테이블 부재(NAV는 프론트 정적 정의) → SQL 메뉴 시드 대상 없음. +-- "업무 (UIWS)" 메뉴는 프론트 Sidebar/Route 에 추가(코드). 여기서는 주석으로만 명시. +-- ─────────────────────────────────────────────────────────────────────────── + +-- end 91_uiws_port.sql diff --git a/backend/src/main/resources/mapper/UserMapper.xml b/backend/src/main/resources/mapper/UserMapper.xml index 5203a0c..913401c 100644 --- a/backend/src/main/resources/mapper/UserMapper.xml +++ b/backend/src/main/resources/mapper/UserMapper.xml @@ -11,10 +11,18 @@ + + + + + + + diff --git a/backend/src/main/resources/mapper/uiws/LoginVerifyMapper.xml b/backend/src/main/resources/mapper/uiws/LoginVerifyMapper.xml new file mode 100644 index 0000000..b6cbf4a --- /dev/null +++ b/backend/src/main/resources/mapper/uiws/LoginVerifyMapper.xml @@ -0,0 +1,16 @@ + + + + + + + + INSERT INTO tb_uiws_login_verify + (user_id, verify_method, verify_code, expire_at, verified_yn, created_by, created_at) + VALUES + (#{userId}, #{verifyMethod}, #{verifyCode}, #{expireAt}, #{verifiedYn}, #{createdBy}, #{createdAt}) + + + diff --git a/backend/src/main/resources/mapper/uiws/MessageMapper.xml b/backend/src/main/resources/mapper/uiws/MessageMapper.xml new file mode 100644 index 0000000..f91af10 --- /dev/null +++ b/backend/src/main/resources/mapper/uiws/MessageMapper.xml @@ -0,0 +1,137 @@ + + + + + + + + + INSERT INTO tb_uiws_message + (sender_id, title, content, ref_worklog_id, reply_to_id, sent_at, sender_del_yn, created_by, created_at) + VALUES + (#{senderId}, #{title}, #{content}, #{refWorklogId}, #{replyToId}, #{sentAt}, #{senderDelYn}, #{createdBy}, #{createdAt}) + + + + + + + + + + + + UPDATE tb_uiws_message + SET sender_del_yn = 'Y', updated_by = #{actor}, updated_at = now() + WHERE sender_id = #{senderId} + AND message_id IN + #{id} + + + + + INSERT INTO tb_uiws_message_rcv + (message_id, receiver_id, rcv_type, read_yn, receiver_del_yn, created_by, created_at) + VALUES + (#{messageId}, #{receiverId}, #{rcvType}, #{readYn}, #{receiverDelYn}, #{createdBy}, #{createdAt}) + + + + + + + + + + + + UPDATE tb_uiws_message_rcv + SET read_yn = 'Y', read_at = #{readAt}, updated_by = #{actor}, updated_at = now() + WHERE rcv_id = #{rcvId} + + + + UPDATE tb_uiws_message_rcv + SET receiver_del_yn = 'Y', updated_by = #{actor}, updated_at = now() + WHERE receiver_id = #{receiverId} + AND message_id IN + #{id} + + + + + + + + + + diff --git a/backend/src/main/resources/mapper/uiws/ScheduleMapper.xml b/backend/src/main/resources/mapper/uiws/ScheduleMapper.xml new file mode 100644 index 0000000..c7d4837 --- /dev/null +++ b/backend/src/main/resources/mapper/uiws/ScheduleMapper.xml @@ -0,0 +1,168 @@ + + + + + + + + + INSERT INTO tb_uiws_schedule + (sche_type, title, sche_gubun_cd, importance_cd, start_dt, end_dt, content, + owner_id, dept_id, charger_id, created_by, created_at) + VALUES + (#{scheType}, #{title}, #{scheGubunCd}, #{importanceCd}, #{startDt}, #{endDt}, #{content}, + #{ownerId}, #{deptId}, #{chargerId}, #{createdBy}, #{createdAt}) + + + + UPDATE tb_uiws_schedule SET + sche_type = #{scheType}, title = #{title}, sche_gubun_cd = #{scheGubunCd}, + importance_cd = #{importanceCd}, start_dt = #{startDt}, end_dt = #{endDt}, + content = #{content}, dept_id = #{deptId}, charger_id = #{chargerId}, + updated_by = #{updatedBy}, updated_at = #{updatedAt} + WHERE schedule_id = #{scheduleId} + + + + + + + + DELETE FROM tb_uiws_schedule WHERE schedule_id = #{scheduleId} + + + + + + + WHERE start_dt < #{to} + AND end_dt >= #{from} + AND sche_type = #{scheType} + + AND owner_id IN + #{oid} + + + + + + + + + + + + INSERT INTO tb_uiws_diary + (title, content, schedule_id, writer_id, diary_date, created_by, created_at) + VALUES + (#{title}, #{content}, #{scheduleId}, #{writerId}, #{diaryDate}, #{createdBy}, #{createdAt}) + + + + UPDATE tb_uiws_diary SET + title = #{title}, content = #{content}, schedule_id = #{scheduleId}, diary_date = #{diaryDate}, + updated_by = #{updatedBy}, updated_at = #{updatedAt} + WHERE diary_id = #{diaryId} + + + + + + + + DELETE FROM tb_uiws_diary WHERE diary_id = #{diaryId} + + + + + + + + + INSERT INTO tb_uiws_attach + (ref_type, ref_id, file_nm, file_path, file_size, created_by, created_at) + VALUES + (#{refType}, #{refId}, #{fileNm}, #{filePath}, #{fileSize}, #{createdBy}, #{createdAt}) + + + + + + UPDATE tb_uiws_attach + SET ref_type = #{refType}, ref_id = #{refId}, updated_by = #{actor}, updated_at = now() + WHERE attach_id = #{attachId} + + + + + + DELETE FROM tb_uiws_attach WHERE attach_id = #{attachId} + + + + DELETE FROM tb_uiws_attach WHERE ref_type = #{refType} AND ref_id = #{refId} + + + + + + diff --git a/backend/src/main/resources/mapper/uiws/StatsMapper.xml b/backend/src/main/resources/mapper/uiws/StatsMapper.xml new file mode 100644 index 0000000..fd8824d --- /dev/null +++ b/backend/src/main/resources/mapper/uiws/StatsMapper.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + diff --git a/backend/src/main/resources/mapper/uiws/WorklogMapper.xml b/backend/src/main/resources/mapper/uiws/WorklogMapper.xml new file mode 100644 index 0000000..5d5ae7b --- /dev/null +++ b/backend/src/main/resources/mapper/uiws/WorklogMapper.xml @@ -0,0 +1,181 @@ + + + + + + + + + INSERT INTO tb_uiws_worklog + (title, writer_id, work_date, work_status_cd, progress_cd, repeat_yn, + repeat_start_date, repeat_end_date, created_by, created_at) + VALUES + (#{title}, #{writerId}, #{workDate}, #{workStatusCd}, #{progressCd}, #{repeatYn}, + #{repeatStartDate}, #{repeatEndDate}, #{createdBy}, #{createdAt}) + + + + UPDATE tb_uiws_worklog SET + title = #{title}, writer_id = #{writerId}, work_date = #{workDate}, + work_status_cd = #{workStatusCd}, progress_cd = #{progressCd}, repeat_yn = #{repeatYn}, + repeat_start_date = #{repeatStartDate}, repeat_end_date = #{repeatEndDate}, + updated_by = #{updatedBy}, updated_at = #{updatedAt} + WHERE worklog_id = #{worklogId} + + + + + + + + DELETE FROM tb_uiws_worklog WHERE worklog_id = #{worklogId} + + + + + AND writer_id IN + #{oid} + + + + + + + + + + + + + + + + INSERT INTO tb_uiws_worklog_dtl + (worklog_id, start_hour, end_hour, work_type_cd, company_id, work_content, issue_content, + sort_ord, created_by, created_at) + VALUES + (#{worklogId}, #{startHour}, #{endHour}, #{workTypeCd}, #{companyId}, #{workContent}, #{issueContent}, + #{sortOrd}, #{createdBy}, #{createdAt}) + + + + UPDATE tb_uiws_worklog_dtl SET + start_hour = #{startHour}, end_hour = #{endHour}, work_type_cd = #{workTypeCd}, + company_id = #{companyId}, work_content = #{workContent}, issue_content = #{issueContent}, + sort_ord = #{sortOrd}, updated_by = #{updatedBy}, updated_at = #{updatedAt} + WHERE dtl_id = #{dtlId} + + + + DELETE FROM tb_uiws_worklog_dtl WHERE dtl_id = #{dtlId} + + + + + + + INSERT INTO tb_uiws_worklog_cmt + (worklog_id, cmt_content, writer_id, kakao_sent_yn, confirm_yn, created_by, created_at) + VALUES + (#{worklogId}, #{cmtContent}, #{writerId}, #{kakaoSentYn}, #{confirmYn}, #{createdBy}, #{createdAt}) + + + + + + UPDATE tb_uiws_worklog_cmt SET kakao_sent_yn = 'Y' WHERE cmt_id = #{cmtId} + + + + UPDATE tb_uiws_worklog_cmt + SET confirm_yn = 'Y', updated_by = #{actor}, updated_at = now() + WHERE cmt_id = #{cmtId} + + + + + + + + + + + + + + + + diff --git a/backend/src/main/resources/static/assets/index-BLHiicbF.js b/backend/src/main/resources/static/assets/index-BLHiicbF.js deleted file mode 100644 index 1b532fb..0000000 --- a/backend/src/main/resources/static/assets/index-BLHiicbF.js +++ /dev/null @@ -1,480 +0,0 @@ -var D1=e=>{throw TypeError(e)};var Qm=(e,t,n)=>t.has(e)||D1("Cannot "+n);var I=(e,t,n)=>(Qm(e,t,"read from private field"),n?n.call(e):t.get(e)),be=(e,t,n)=>t.has(e)?D1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),fe=(e,t,n,r)=>(Qm(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Dt=(e,t,n)=>(Qm(e,t,"access private method"),n);var Af=(e,t,n,r)=>({set _(a){fe(e,t,a,n)},get _(){return I(e,t,r)}});(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();var Nf=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function _e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hE={exports:{}},Sp={};/** - * @license React - * react-jsx-runtime.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var R3=Symbol.for("react.transitional.element"),k3=Symbol.for("react.fragment");function pE(e,t,n){var r=null;if(n!==void 0&&(r=""+n),t.key!==void 0&&(r=""+t.key),"key"in t){n={};for(var a in t)a!=="key"&&(n[a]=t[a])}else n=t;return t=n.ref,{$$typeof:R3,type:e,key:r,ref:t!==void 0?t:null,props:n}}Sp.Fragment=k3;Sp.jsx=pE;Sp.jsxs=pE;hE.exports=Sp;var o=hE.exports,mE={exports:{}},he={};/** - * @license React - * react.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ib=Symbol.for("react.transitional.element"),D3=Symbol.for("react.portal"),L3=Symbol.for("react.fragment"),z3=Symbol.for("react.strict_mode"),B3=Symbol.for("react.profiler"),I3=Symbol.for("react.consumer"),U3=Symbol.for("react.context"),q3=Symbol.for("react.forward_ref"),H3=Symbol.for("react.suspense"),F3=Symbol.for("react.memo"),yE=Symbol.for("react.lazy"),G3=Symbol.for("react.activity"),L1=Symbol.iterator;function K3(e){return e===null||typeof e!="object"?null:(e=L1&&e[L1]||e["@@iterator"],typeof e=="function"?e:null)}var vE={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},gE=Object.assign,xE={};function ws(e,t,n){this.props=e,this.context=t,this.refs=xE,this.updater=n||vE}ws.prototype.isReactComponent={};ws.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ws.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function bE(){}bE.prototype=ws.prototype;function lb(e,t,n){this.props=e,this.context=t,this.refs=xE,this.updater=n||vE}var ob=lb.prototype=new bE;ob.constructor=lb;gE(ob,ws.prototype);ob.isPureReactComponent=!0;var z1=Array.isArray;function xv(){}var We={H:null,A:null,T:null,S:null},jE=Object.prototype.hasOwnProperty;function sb(e,t,n){var r=n.ref;return{$$typeof:ib,type:e,key:t,ref:r!==void 0?r:null,props:n}}function V3(e,t){return sb(e.type,t,e.props)}function cb(e){return typeof e=="object"&&e!==null&&e.$$typeof===ib}function Y3(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var B1=/\/+/g;function Wm(e,t){return typeof e=="object"&&e!==null&&e.key!=null?Y3(""+e.key):t.toString(36)}function X3(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(xv,xv):(e.status="pending",e.then(function(t){e.status==="pending"&&(e.status="fulfilled",e.value=t)},function(t){e.status==="pending"&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function Gl(e,t,n,r,a){var i=typeof e;(i==="undefined"||i==="boolean")&&(e=null);var l=!1;if(e===null)l=!0;else switch(i){case"bigint":case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case ib:case D3:l=!0;break;case yE:return l=e._init,Gl(l(e._payload),t,n,r,a)}}if(l)return a=a(e),l=r===""?"."+Wm(e,0):r,z1(a)?(n="",l!=null&&(n=l.replace(B1,"$&/")+"/"),Gl(a,t,n,"",function(u){return u})):a!=null&&(cb(a)&&(a=V3(a,n+(a.key==null||e&&e.key===a.key?"":(""+a.key).replace(B1,"$&/")+"/")+l)),t.push(a)),1;l=0;var s=r===""?".":r+":";if(z1(e))for(var c=0;c>>1,X=$[V];if(0>>1;Va(ie,q))aea(Se,ie)?($[V]=Se,$[ae]=q,V=ae):($[V]=ie,$[Q]=q,V=Q);else if(aea(Se,q))$[V]=Se,$[ae]=q,V=ae;else break e}}return L}function a($,L){var q=$.sortIndex-L.sortIndex;return q!==0?q:$.id-L.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var l=Date,s=l.now();e.unstable_now=function(){return l.now()-s}}var c=[],u=[],f=1,d=null,h=3,m=!1,j=!1,v=!1,p=!1,y=typeof setTimeout=="function"?setTimeout:null,g=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;function x($){for(var L=n(u);L!==null;){if(L.callback===null)r(u);else if(L.startTime<=$)r(u),L.sortIndex=L.expirationTime,t(c,L);else break;L=n(u)}}function w($){if(v=!1,x($),!j)if(n(c)!==null)j=!0,S||(S=!0,P());else{var L=n(u);L!==null&&E(w,L.startTime-$)}}var S=!1,A=-1,N=5,C=-1;function M(){return p?!0:!(e.unstable_now()-C$&&M());){var V=d.callback;if(typeof V=="function"){d.callback=null,h=d.priorityLevel;var X=V(d.expirationTime<=$);if($=e.unstable_now(),typeof X=="function"){d.callback=X,x($),L=!0;break t}d===n(c)&&r(c),x($)}else r(c);d=n(c)}if(d!==null)L=!0;else{var J=n(u);J!==null&&E(w,J.startTime-$),L=!1}}break e}finally{d=null,h=q,m=!1}L=void 0}}finally{L?P():S=!1}}}var P;if(typeof b=="function")P=function(){b(R)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,_=B.port2;B.port1.onmessage=R,P=function(){_.postMessage(null)}}else P=function(){y(R,0)};function E($,L){A=y(function(){$(e.unstable_now())},L)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function($){$.callback=null},e.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):N=0<$?Math.floor(1e3/$):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_next=function($){switch(h){case 1:case 2:case 3:var L=3;break;default:L=h}var q=h;h=L;try{return $()}finally{h=q}},e.unstable_requestPaint=function(){p=!0},e.unstable_runWithPriority=function($,L){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var q=h;h=$;try{return L()}finally{h=q}},e.unstable_scheduleCallback=function($,L,q){var V=e.unstable_now();switch(typeof q=="object"&&q!==null?(q=q.delay,q=typeof q=="number"&&0V?($.sortIndex=q,t(u,$),n(c)===null&&$===n(u)&&(v?(g(A),A=-1):v=!0,E(w,q-V))):($.sortIndex=X,t(c,$),j||m||(j=!0,S||(S=!0,P()))),$},e.unstable_shouldYield=M,e.unstable_wrapCallback=function($){var L=h;return function(){var q=h;h=L;try{return $.apply(this,arguments)}finally{h=q}}}})(OE);wE.exports=OE;var Z3=wE.exports,AE={exports:{}},ln={};/** - * @license React - * react-dom.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var J3=O;function NE(e){var t="https://react.dev/errors/"+e;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(EE)}catch(e){console.error(e)}}EE(),AE.exports=ln;var nR=AE.exports;/** - * @license React - * react-dom-client.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Et=Z3,CE=O,rR=nR;function F(e){var t="https://react.dev/errors/"+e;if(1Xl||(e.current=Av[Xl],Av[Xl]=null,Xl--)}function qe(e,t){Xl++,Av[Xl]=e.current,e.current=t}var Lr=Ur(null),Gc=Ur(null),ri=Ur(null),Dd=Ur(null);function Ld(e,t){switch(qe(ri,t),qe(Gc,e),qe(Lr,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Yj(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Yj(t),e=e_(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Rt(Lr),qe(Lr,e)}function Ro(){Rt(Lr),Rt(Gc),Rt(ri)}function Nv(e){e.memoizedState!==null&&qe(Dd,e);var t=Lr.current,n=e_(t,e.type);t!==n&&(qe(Gc,e),qe(Lr,n))}function zd(e){Gc.current===e&&(Rt(Lr),Rt(Gc)),Dd.current===e&&(Rt(Dd),nu._currentValue=al)}var Zm,H1;function zi(e){if(Zm===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);Zm=t&&t[1]||"",H1=-1)":-1a||c[r]!==u[a]){var f=` -`+c[r].replace(" at new "," at ");return e.displayName&&f.includes("")&&(f=f.replace("",e.displayName)),f}while(1<=r&&0<=a);break}}}finally{Jm=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?zi(n):""}function sR(e,t){switch(e.tag){case 26:case 27:case 5:return zi(e.type);case 16:return zi("Lazy");case 13:return e.child!==t&&t!==null?zi("Suspense Fallback"):zi("Suspense");case 19:return zi("SuspenseList");case 0:case 15:return ey(e.type,!1);case 11:return ey(e.type.render,!1);case 1:return ey(e.type,!0);case 31:return zi("Activity");default:return""}}function F1(e){try{var t="",n=null;do t+=sR(e,n),n=e,e=e.return;while(e);return t}catch(r){return` -Error generating stack: `+r.message+` -`+r.stack}}var Ev=Object.prototype.hasOwnProperty,db=Et.unstable_scheduleCallback,ty=Et.unstable_cancelCallback,cR=Et.unstable_shouldYield,uR=Et.unstable_requestPaint,En=Et.unstable_now,fR=Et.unstable_getCurrentPriorityLevel,kE=Et.unstable_ImmediatePriority,DE=Et.unstable_UserBlockingPriority,Bd=Et.unstable_NormalPriority,dR=Et.unstable_LowPriority,LE=Et.unstable_IdlePriority,hR=Et.log,pR=Et.unstable_setDisableYieldValue,Yu=null,Cn=null;function Xa(e){if(typeof hR=="function"&&pR(e),Cn&&typeof Cn.setStrictMode=="function")try{Cn.setStrictMode(Yu,e)}catch{}}var _n=Math.clz32?Math.clz32:vR,mR=Math.log,yR=Math.LN2;function vR(e){return e>>>=0,e===0?32:31-(mR(e)/yR|0)|0}var _f=256,Tf=262144,Pf=4194304;function Bi(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ap(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var a=0,i=e.suspendedLanes,l=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s!==0?(r=s&~i,r!==0?a=Bi(r):(l&=s,l!==0?a=Bi(l):n||(n=s&~e,n!==0&&(a=Bi(n))))):(s=r&~i,s!==0?a=Bi(s):l!==0?a=Bi(l):n||(n=r&~e,n!==0&&(a=Bi(n)))),a===0?0:t!==0&&t!==a&&!(t&i)&&(i=a&-a,n=t&-t,i>=n||i===32&&(n&4194048)!==0)?t:a}function Xu(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function gR(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function zE(){var e=Pf;return Pf<<=1,!(Pf&62914560)&&(Pf=4194304),e}function ny(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Qu(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function xR(e,t,n,r,a,i){var l=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,u=e.hiddenUpdates;for(n=l&~n;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var AR=/[\n"\\]/g;function Kn(e){return e.replace(AR,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function Tv(e,t,n,r,a,i,l,s){e.name="",l!=null&&typeof l!="function"&&typeof l!="symbol"&&typeof l!="boolean"?e.type=l:e.removeAttribute("type"),t!=null?l==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Hn(t)):e.value!==""+Hn(t)&&(e.value=""+Hn(t)):l!=="submit"&&l!=="reset"||e.removeAttribute("value"),t!=null?Pv(e,l,Hn(t)):n!=null?Pv(e,l,Hn(n)):r!=null&&e.removeAttribute("value"),a==null&&i!=null&&(e.defaultChecked=!!i),a!=null&&(e.checked=a&&typeof a!="function"&&typeof a!="symbol"),s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"?e.name=""+Hn(s):e.removeAttribute("name")}function VE(e,t,n,r,a,i,l,s){if(i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(e.type=i),t!=null||n!=null){if(!(i!=="submit"&&i!=="reset"||t!=null)){_v(e);return}n=n!=null?""+Hn(n):"",t=t!=null?""+Hn(t):n,s||t===e.value||(e.value=t),e.defaultValue=t}r=r??a,r=typeof r!="function"&&typeof r!="symbol"&&!!r,e.checked=s?e.checked:!!r,e.defaultChecked=!!r,l!=null&&typeof l!="function"&&typeof l!="symbol"&&typeof l!="boolean"&&(e.name=l),_v(e)}function Pv(e,t,n){t==="number"&&Id(e.ownerDocument)===e||e.defaultValue===""+n||(e.defaultValue=""+n)}function mo(e,t,n,r){if(e=e.options,t){t={};for(var a=0;a"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$v=!1;if(ma)try{var Zs={};Object.defineProperty(Zs,"passive",{get:function(){$v=!0}}),window.addEventListener("test",Zs,Zs),window.removeEventListener("test",Zs,Zs)}catch{$v=!1}var Qa=null,gb=null,vd=null;function ZE(){if(vd)return vd;var e,t=gb,n=t.length,r,a="value"in Qa?Qa.value:Qa.textContent,i=a.length;for(e=0;e=wc),tj=" ",nj=!1;function e2(e,t){switch(e){case"keyup":return JR.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function t2(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Zl=!1;function tk(e,t){switch(e){case"compositionend":return t2(t);case"keypress":return t.which!==32?null:(nj=!0,tj);case"textInput":return e=t.data,e===tj&&nj?null:e;default:return null}}function nk(e,t){if(Zl)return e==="compositionend"||!bb&&e2(e,t)?(e=ZE(),vd=gb=Qa=null,Zl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=oj(n)}}function i2(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?i2(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function l2(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Id(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Id(e.document)}return t}function jb(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var uk=ma&&"documentMode"in document&&11>=document.documentMode,Jl=null,Rv=null,Ac=null,kv=!1;function cj(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;kv||Jl==null||Jl!==Id(r)||(r=Jl,"selectionStart"in r&&jb(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ac&&Yc(Ac,r)||(Ac=r,r=ah(Rv,"onSelect"),0>=l,a-=l,Mr=1<<32-_n(t)+a|n<N?(C=A,A=null):C=A.sibling;var M=h(y,A,b[N],x);if(M===null){A===null&&(A=C);break}e&&A&&M.alternate===null&&t(y,A),g=i(M,g,N),S===null?w=M:S.sibling=M,S=M,A=C}if(N===b.length)return n(y,A),we&&ea(y,N),w;if(A===null){for(;NN?(C=A,A=null):C=A.sibling;var R=h(y,A,M.value,x);if(R===null){A===null&&(A=C);break}e&&A&&R.alternate===null&&t(y,A),g=i(R,g,N),S===null?w=R:S.sibling=R,S=R,A=C}if(M.done)return n(y,A),we&&ea(y,N),w;if(A===null){for(;!M.done;N++,M=b.next())M=d(y,M.value,x),M!==null&&(g=i(M,g,N),S===null?w=M:S.sibling=M,S=M);return we&&ea(y,N),w}for(A=r(A);!M.done;N++,M=b.next())M=m(A,y,N,M.value,x),M!==null&&(e&&M.alternate!==null&&A.delete(M.key===null?N:M.key),g=i(M,g,N),S===null?w=M:S.sibling=M,S=M);return e&&A.forEach(function(P){return t(y,P)}),we&&ea(y,N),w}function p(y,g,b,x){if(typeof b=="object"&&b!==null&&b.type===Yl&&b.key===null&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case Cf:e:{for(var w=b.key;g!==null;){if(g.key===w){if(w=b.type,w===Yl){if(g.tag===7){n(y,g.sibling),x=a(g,b.props.children),x.return=y,y=x;break e}}else if(g.elementType===w||typeof w=="object"&&w!==null&&w.$$typeof===ka&&Ii(w)===g.type){n(y,g.sibling),x=a(g,b.props),ec(x,b),x.return=y,y=x;break e}n(y,g);break}else t(y,g);g=g.sibling}b.type===Yl?(x=il(b.props.children,y.mode,x,b.key),x.return=y,y=x):(x=xd(b.type,b.key,b.props,null,y.mode,x),ec(x,b),x.return=y,y=x)}return l(y);case yc:e:{for(w=b.key;g!==null;){if(g.key===w)if(g.tag===4&&g.stateNode.containerInfo===b.containerInfo&&g.stateNode.implementation===b.implementation){n(y,g.sibling),x=a(g,b.children||[]),x.return=y,y=x;break e}else{n(y,g);break}else t(y,g);g=g.sibling}x=fy(b,y.mode,x),x.return=y,y=x}return l(y);case ka:return b=Ii(b),p(y,g,b,x)}if(vc(b))return j(y,g,b,x);if(Ws(b)){if(w=Ws(b),typeof w!="function")throw Error(F(150));return b=w.call(b),v(y,g,b,x)}if(typeof b.then=="function")return p(y,g,kf(b),x);if(b.$$typeof===aa)return p(y,g,Rf(y,b),x);Df(y,b)}return typeof b=="string"&&b!==""||typeof b=="number"||typeof b=="bigint"?(b=""+b,g!==null&&g.tag===6?(n(y,g.sibling),x=a(g,b),x.return=y,y=x):(n(y,g),x=uy(b,y.mode,x),x.return=y,y=x),l(y)):n(y,g)}return function(y,g,b,x){try{Wc=0;var w=p(y,g,b,x);return go=null,w}catch(A){if(A===Es||A===Pp)throw A;var S=On(29,A,null,y.mode);return S.lanes=x,S.return=y,S}finally{}}}var yl=j2(!0),S2=j2(!1),Da=!1;function Tb(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function qv(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function ii(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function li(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ne&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,t=qd(e),h2(e,null,n),t}return Tp(e,r,t,n),qd(e)}function Ec(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194048)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,IE(e,n)}}function hy(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var a=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};i===null?a=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?a=i=t:i=i.next=t}else a=i=t;n={baseState:r.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Hv=!1;function Cc(){if(Hv){var e=vo;if(e!==null)throw e}}function _c(e,t,n,r){Hv=!1;var a=e.updateQueue;Da=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,s=a.shared.pending;if(s!==null){a.shared.pending=null;var c=s,u=c.next;c.next=null,l===null?i=u:l.next=u,l=c;var f=e.alternate;f!==null&&(f=f.updateQueue,s=f.lastBaseUpdate,s!==l&&(s===null?f.firstBaseUpdate=u:s.next=u,f.lastBaseUpdate=c))}if(i!==null){var d=a.baseState;l=0,f=u=c=null,s=i;do{var h=s.lane&-536870913,m=h!==s.lane;if(m?(je&h)===h:(r&h)===h){h!==0&&h===Lo&&(Hv=!0),f!==null&&(f=f.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});e:{var j=e,v=s;h=t;var p=n;switch(v.tag){case 1:if(j=v.payload,typeof j=="function"){d=j.call(p,d,h);break e}d=j;break e;case 3:j.flags=j.flags&-65537|128;case 0:if(j=v.payload,h=typeof j=="function"?j.call(p,d,h):j,h==null)break e;d=Ze({},d,h);break e;case 2:Da=!0}}h=s.callback,h!==null&&(e.flags|=64,m&&(e.flags|=8192),m=a.callbacks,m===null?a.callbacks=[h]:m.push(h))}else m={lane:h,tag:s.tag,payload:s.payload,callback:s.callback,next:null},f===null?(u=f=m,c=d):f=f.next=m,l|=h;if(s=s.next,s===null){if(s=a.shared.pending,s===null)break;m=s,s=m.next,m.next=null,a.lastBaseUpdate=m,a.shared.pending=null}}while(!0);f===null&&(c=d),a.baseState=c,a.firstBaseUpdate=u,a.lastBaseUpdate=f,i===null&&(a.shared.lanes=0),vi|=l,e.lanes=l,e.memoizedState=d}}function w2(e,t){if(typeof e!="function")throw Error(F(191,e));e.call(t)}function O2(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ei?i:8;var l=ue.T,s={};ue.T=s,Hb(e,!1,t,n);try{var c=a(),u=ue.S;if(u!==null&&u(s,c),c!==null&&typeof c=="object"&&typeof c.then=="function"){var f=xk(c,r);Tc(e,t,f,Tn(e))}else Tc(e,t,r,Tn(e))}catch(d){Tc(e,t,{then:function(){},status:"rejected",reason:d},Tn())}finally{Ee.p=i,l!==null&&s.types!==null&&(l.types=s.types),ue.T=l}}function Ak(){}function Yv(e,t,n,r){if(e.tag!==5)throw Error(F(476));var a=X2(e).queue;Y2(e,a,t,al,n===null?Ak:function(){return Q2(e),n(r)})}function X2(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:al,baseState:al,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:va,lastRenderedState:al},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:va,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Q2(e){var t=X2(e);t.next===null&&(t=e.alternate.memoizedState),Tc(e,t.next.queue,{},Tn())}function qb(){return qt(nu)}function W2(){return pt().memoizedState}function Z2(){return pt().memoizedState}function Nk(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=Tn();e=ii(n);var r=li(t,e,n);r!==null&&(hn(r,t,n),Ec(r,t,n)),t={cache:Eb()},e.payload=t;return}t=t.return}}function Ek(e,t,n){var r=Tn();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},kp(e)?eC(t,n):(n=wb(e,t,n,r),n!==null&&(hn(n,e,r),tC(n,t,r)))}function J2(e,t,n){var r=Tn();Tc(e,t,n,r)}function Tc(e,t,n,r){var a={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(kp(e))eC(t,a);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,s=i(l,n);if(a.hasEagerState=!0,a.eagerState=s,Mn(s,l))return Tp(e,t,a,0),ze===null&&_p(),!1}catch{}finally{}if(n=wb(e,t,a,r),n!==null)return hn(n,e,r),tC(n,t,r),!0}return!1}function Hb(e,t,n,r){if(r={lane:2,revertLane:Zb(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},kp(e)){if(t)throw Error(F(479))}else t=wb(e,n,r,2),t!==null&&hn(t,e,2)}function kp(e){var t=e.alternate;return e===pe||t!==null&&t===pe}function eC(e,t){xo=Yd=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tC(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,IE(e,n)}}var Jc={readContext:qt,use:$p,useCallback:st,useContext:st,useEffect:st,useImperativeHandle:st,useLayoutEffect:st,useInsertionEffect:st,useMemo:st,useReducer:st,useRef:st,useState:st,useDebugValue:st,useDeferredValue:st,useTransition:st,useSyncExternalStore:st,useId:st,useHostTransitionStatus:st,useFormState:st,useActionState:st,useOptimistic:st,useMemoCache:st,useCacheRefresh:st};Jc.useEffectEvent=st;var nC={readContext:qt,use:$p,useCallback:function(e,t){return Qt().memoizedState=[e,t===void 0?null:t],e},useContext:qt,useEffect:Oj,useImperativeHandle:function(e,t,n){n=n!=null?n.concat([e]):null,Sd(4194308,4,H2.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Sd(4194308,4,e,t)},useInsertionEffect:function(e,t){Sd(4,2,e,t)},useMemo:function(e,t){var n=Qt();t=t===void 0?null:t;var r=e();if(vl){Xa(!0);try{e()}finally{Xa(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Qt();if(n!==void 0){var a=n(t);if(vl){Xa(!0);try{n(t)}finally{Xa(!1)}}}else a=t;return r.memoizedState=r.baseState=a,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:a},r.queue=e,e=e.dispatch=Ek.bind(null,pe,e),[r.memoizedState,e]},useRef:function(e){var t=Qt();return e={current:e},t.memoizedState=e},useState:function(e){e=Kv(e);var t=e.queue,n=J2.bind(null,pe,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:Ib,useDeferredValue:function(e,t){var n=Qt();return Ub(n,e,t)},useTransition:function(){var e=Kv(!1);return e=Y2.bind(null,pe,e.queue,!0,!1),Qt().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=pe,a=Qt();if(we){if(n===void 0)throw Error(F(407));n=n()}else{if(n=t(),ze===null)throw Error(F(349));je&127||_2(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,Oj(P2.bind(null,r,i,e),[e]),r.flags|=2048,Bo(9,{destroy:void 0},T2.bind(null,r,i,n,t),null),n},useId:function(){var e=Qt(),t=ze.identifierPrefix;if(we){var n=$r,r=Mr;n=(r&~(1<<32-_n(r)-1)).toString(32)+n,t="_"+t+"R_"+n,n=Xd++,0<\/script>",i=i.removeChild(i.firstChild);break;case"select":i=typeof r.is=="string"?l.createElement("select",{is:r.is}):l.createElement("select"),r.multiple?i.multiple=!0:r.size&&(i.size=r.size);break;default:i=typeof r.is=="string"?l.createElement(a,{is:r.is}):l.createElement(a)}}i[Bt]=t,i[mn]=r;e:for(l=t.child;l!==null;){if(l.tag===5||l.tag===6)i.appendChild(l.stateNode);else if(l.tag!==4&&l.tag!==27&&l.child!==null){l.child.return=l,l=l.child;continue}if(l===t)break e;for(;l.sibling===null;){if(l.return===null||l.return===t)break e;l=l.return}l.sibling.return=l.return,l=l.sibling}t.stateNode=i;e:switch(Ht(i,a,r),a){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}r&&Vr(t)}}return Ke(t),jy(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Vr(t);else{if(typeof r!="string"&&t.stateNode===null)throw Error(F(166));if(e=ri.current,Ll(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=It,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[Bt]=t,e=!!(e.nodeValue===n||r!==null&&r.suppressHydrationWarning===!0||JC(e.nodeValue,n)),e||mi(t,!0)}else e=ih(e).createTextNode(r),e[Bt]=t,t.stateNode=e}return Ke(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Ll(t),n!==null){if(e===null){if(!r)throw Error(F(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(F(557));e[Bt]=t}else pl(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ke(t),e=!1}else n=dy(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(wn(t),t):(wn(t),null);if(t.flags&128)throw Error(F(558))}return Ke(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Ll(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(F(318));if(a=t.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(F(317));a[Bt]=t}else pl(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Ke(t),a=!1}else a=dy(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(wn(t),t):(wn(t),null)}return wn(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),i=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(i=r.memoizedState.cachePool.pool),i!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Lf(t,t.updateQueue),Ke(t),null);case 4:return Ro(),e===null&&Jb(t.stateNode.containerInfo),Ke(t),null;case 10:return fa(t.type),Ke(t),null;case 19:if(Rt(ht),r=t.memoizedState,r===null)return Ke(t),null;if(a=(t.flags&128)!==0,i=r.rendering,i===null)if(a)tc(r,!1);else{if(ft!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(i=Vd(e),i!==null){for(t.flags|=128,tc(r,!1),e=i.updateQueue,t.updateQueue=e,Lf(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)p2(n,e),n=n.sibling;return qe(ht,ht.current&1|2),we&&ea(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&En()>Jd&&(t.flags|=128,a=!0,tc(r,!1),t.lanes=4194304)}else{if(!a)if(e=Vd(i),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Lf(t,e),tc(r,!0),r.tail===null&&r.tailMode==="hidden"&&!i.alternate&&!we)return Ke(t),null}else 2*En()-r.renderingStartTime>Jd&&n!==536870912&&(t.flags|=128,a=!0,tc(r,!1),t.lanes=4194304);r.isBackwards?(i.sibling=t.child,t.child=i):(e=r.last,e!==null?e.sibling=i:t.child=i,r.last=i)}return r.tail!==null?(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=En(),e.sibling=null,n=ht.current,qe(ht,a?n&1|2:n&1),we&&ea(t,r.treeForkCount),e):(Ke(t),null);case 22:case 23:return wn(t),Pb(),r=t.memoizedState!==null,e!==null?e.memoizedState!==null!==r&&(t.flags|=8192):r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Ke(t),t.subtreeFlags&6&&(t.flags|=8192)):Ke(t),n=t.updateQueue,n!==null&&Lf(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&Rt(ll),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),fa(bt),Ke(t),null;case 25:return null;case 30:return null}throw Error(F(156,t.tag))}function Mk(e,t){switch(Nb(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return fa(bt),Ro(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return zd(t),null;case 31:if(t.memoizedState!==null){if(wn(t),t.alternate===null)throw Error(F(340));pl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(wn(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(F(340));pl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Rt(ht),null;case 4:return Ro(),null;case 10:return fa(t.type),null;case 22:case 23:return wn(t),Pb(),e!==null&&Rt(ll),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return fa(bt),null;case 25:return null;default:return null}}function pC(e,t){switch(Nb(t),t.tag){case 3:fa(bt),Ro();break;case 26:case 27:case 5:zd(t);break;case 4:Ro();break;case 31:t.memoizedState!==null&&wn(t);break;case 13:wn(t);break;case 19:Rt(ht);break;case 10:fa(t.type);break;case 22:case 23:wn(t),Pb(),e!==null&&Rt(ll);break;case 24:fa(bt)}}function tf(e,t){try{var n=t.updateQueue,r=n!==null?n.lastEffect:null;if(r!==null){var a=r.next;n=a;do{if((n.tag&e)===e){r=void 0;var i=n.create,l=n.inst;r=i(),l.destroy=r}n=n.next}while(n!==a)}}catch(s){Me(t,t.return,s)}}function yi(e,t,n){try{var r=t.updateQueue,a=r!==null?r.lastEffect:null;if(a!==null){var i=a.next;r=i;do{if((r.tag&e)===e){var l=r.inst,s=l.destroy;if(s!==void 0){l.destroy=void 0,a=t;var c=n,u=s;try{u()}catch(f){Me(a,c,f)}}}r=r.next}while(r!==i)}}catch(f){Me(t,t.return,f)}}function mC(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{O2(t,n)}catch(r){Me(e,e.return,r)}}}function yC(e,t,n){n.props=gl(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(r){Me(e,t,r)}}function Pc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n=="function"?e.refCleanup=n(r):n.current=r}}catch(a){Me(e,t,a)}}function Rr(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r=="function")try{r()}catch(a){Me(e,t,a)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n=="function")try{n(null)}catch(a){Me(e,t,a)}else n.current=null}function vC(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":n.autoFocus&&r.focus();break e;case"img":n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(a){Me(e,e.return,a)}}function Sy(e,t,n){try{var r=e.stateNode;eD(r,e.type,n,t),r[mn]=t}catch(a){Me(e,e.return,a)}}function gC(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Oi(e.type)||e.tag===4}function wy(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||gC(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Oi(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Jv(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=ia));else if(r!==4&&(r===27&&Oi(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Jv(e,t,n),e=e.sibling;e!==null;)Jv(e,t,n),e=e.sibling}function Zd(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&Oi(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Zd(e,t,n),e=e.sibling;e!==null;)Zd(e,t,n),e=e.sibling}function xC(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,a=t.attributes;a.length;)t.removeAttributeNode(a[0]);Ht(t,r,n),t[Bt]=e,t[mn]=n}catch(i){Me(e,e.return,i)}}var ra=!1,xt=!1,Oy=!1,Lj=typeof WeakSet=="function"?WeakSet:Set,Pt=null;function $k(e,t){if(e=e.containerInfo,lg=ch,e=l2(e),jb(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,s=-1,c=-1,u=0,f=0,d=e,h=null;t:for(;;){for(var m;d!==n||a!==0&&d.nodeType!==3||(s=l+a),d!==i||r!==0&&d.nodeType!==3||(c=l+r),d.nodeType===3&&(l+=d.nodeValue.length),(m=d.firstChild)!==null;)h=d,d=m;for(;;){if(d===e)break t;if(h===n&&++u===a&&(s=l),h===i&&++f===r&&(c=l),(m=d.nextSibling)!==null)break;d=h,h=d.parentNode}d=m}n=s===-1||c===-1?null:{start:s,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(og={focusedElem:e,selectionRange:n},ch=!1,Pt=t;Pt!==null;)if(t=Pt,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Pt=e;else for(;Pt!==null;){switch(t=Pt,i=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(n=0;n title"))),Ht(i,r,n),i[Bt]=e,Mt(i),r=i;break e;case"link":var l=rS("link","href",a).get(r+(n.href||""));if(l){for(var s=0;sp&&(l=p,p=v,v=l);var y=sj(s,v),g=sj(s,p);if(y&&g&&(m.rangeCount!==1||m.anchorNode!==y.node||m.anchorOffset!==y.offset||m.focusNode!==g.node||m.focusOffset!==g.offset)){var b=d.createRange();b.setStart(y.node,y.offset),m.removeAllRanges(),v>p?(m.addRange(b),m.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),m.addRange(b))}}}}for(d=[],m=s;m=m.parentNode;)m.nodeType===1&&d.push({element:m,left:m.scrollLeft,top:m.scrollTop});for(typeof s.focus=="function"&&s.focus(),s=0;sn?32:n,ue.T=null,n=ng,ng=null;var i=si,l=da;if(At=0,Uo=si=null,da=0,Ne&6)throw Error(F(331));var s=Ne;if(Ne|=4,TC(i.current),EC(i,i.current,l,n),Ne=s,nf(0,!1),Cn&&typeof Cn.onPostCommitFiberRoot=="function")try{Cn.onPostCommitFiberRoot(Yu,i)}catch{}return!0}finally{Ee.p=a,ue.T=r,GC(e,t)}}function Uj(e,t,n){t=Vn(n,t),t=Qv(e.stateNode,t,2),e=li(e,t,2),e!==null&&(Qu(e,2),qr(e))}function Me(e,t,n){if(e.tag===3)Uj(e,e,n);else for(;t!==null;){if(t.tag===3){Uj(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(oi===null||!oi.has(r))){e=Vn(n,e),n=oC(2),r=li(t,n,2),r!==null&&(sC(n,r,t,e),Qu(r,2),qr(r));break}}t=t.return}}function Ny(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Dk;var a=new Set;r.set(t,a)}else a=r.get(t),a===void 0&&(a=new Set,r.set(t,a));a.has(n)||(Xb=!0,a.add(n),e=Uk.bind(null,e,t,n),t.then(e,e))}function Uk(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,ze===e&&(je&n)===n&&(ft===4||ft===3&&(je&62914560)===je&&300>En()-Dp?!(Ne&2)&&qo(e,0):Qb|=n,Io===je&&(Io=0)),qr(e)}function VC(e,t){t===0&&(t=zE()),e=_l(e,t),e!==null&&(Qu(e,t),qr(e))}function qk(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),VC(e,n)}function Hk(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(F(314))}r!==null&&r.delete(t),VC(e,n)}function Fk(e,t){return db(e,t)}var nh=null,Vl=null,ag=!1,rh=!1,Ey=!1,Ja=0;function qr(e){e!==Vl&&e.next===null&&(Vl===null?nh=Vl=e:Vl=Vl.next=e),rh=!0,ag||(ag=!0,Kk())}function nf(e,t){if(!Ey&&rh){Ey=!0;do for(var n=!1,r=nh;r!==null;){if(e!==0){var a=r.pendingLanes;if(a===0)var i=0;else{var l=r.suspendedLanes,s=r.pingedLanes;i=(1<<31-_n(42|e)+1)-1,i&=a&~(l&~s),i=i&201326741?i&201326741|1:i?i|2:0}i!==0&&(n=!0,qj(r,i))}else i=je,i=Ap(r,r===ze?i:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(i&3)||Xu(r,i)||(n=!0,qj(r,i));r=r.next}while(n);Ey=!1}}function Gk(){YC()}function YC(){rh=ag=!1;var e=0;Ja!==0&&nD()&&(e=Ja);for(var t=En(),n=null,r=nh;r!==null;){var a=r.next,i=XC(r,t);i===0?(r.next=null,n===null?nh=a:n.next=a,a===null&&(Vl=n)):(n=r,(e!==0||i&3)&&(rh=!0)),r=a}At!==0&&At!==5||nf(e),Ja!==0&&(Ja=0)}function XC(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,a=e.expirationTimes,i=e.pendingLanes&-62914561;0s)break;var f=c.transferSize,d=c.initiatorType;f&&Vj(d)&&(c=c.responseEnd,l+=f*(c"u"?null:document;function a_(e,t,n){var r=_s;if(r&&typeof t=="string"&&t){var a=Kn(t);a='link[rel="'+e+'"][href="'+a+'"]',typeof n=="string"&&(a+='[crossorigin="'+n+'"]'),eS.has(a)||(eS.add(a),e={rel:e,crossOrigin:n,href:t},r.querySelector(a)===null&&(t=r.createElement("link"),Ht(t,"link",e),Mt(t),r.head.appendChild(t)))}}function fD(e){Oa.D(e),a_("dns-prefetch",e,null)}function dD(e,t){Oa.C(e,t),a_("preconnect",e,t)}function hD(e,t,n){Oa.L(e,t,n);var r=_s;if(r&&e&&t){var a='link[rel="preload"][as="'+Kn(t)+'"]';t==="image"&&n&&n.imageSrcSet?(a+='[imagesrcset="'+Kn(n.imageSrcSet)+'"]',typeof n.imageSizes=="string"&&(a+='[imagesizes="'+Kn(n.imageSizes)+'"]')):a+='[href="'+Kn(e)+'"]';var i=a;switch(t){case"style":i=Ho(e);break;case"script":i=Ts(e)}er.has(i)||(e=Ze({rel:"preload",href:t==="image"&&n&&n.imageSrcSet?void 0:e,as:t},n),er.set(i,e),r.querySelector(a)!==null||t==="style"&&r.querySelector(rf(i))||t==="script"&&r.querySelector(af(i))||(t=r.createElement("link"),Ht(t,"link",e),Mt(t),r.head.appendChild(t)))}}function pD(e,t){Oa.m(e,t);var n=_s;if(n&&e){var r=t&&typeof t.as=="string"?t.as:"script",a='link[rel="modulepreload"][as="'+Kn(r)+'"][href="'+Kn(e)+'"]',i=a;switch(r){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=Ts(e)}if(!er.has(i)&&(e=Ze({rel:"modulepreload",href:e},t),er.set(i,e),n.querySelector(a)===null)){switch(r){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(n.querySelector(af(i)))return}r=n.createElement("link"),Ht(r,"link",e),Mt(r),n.head.appendChild(r)}}}function mD(e,t,n){Oa.S(e,t,n);var r=_s;if(r&&e){var a=po(r).hoistableStyles,i=Ho(e);t=t||"default";var l=a.get(i);if(!l){var s={loading:0,preload:null};if(l=r.querySelector(rf(i)))s.loading=5;else{e=Ze({rel:"stylesheet",href:e,"data-precedence":t},n),(n=er.get(i))&&e0(e,n);var c=l=r.createElement("link");Mt(c),Ht(c,"link",e),c._p=new Promise(function(u,f){c.onload=u,c.onerror=f}),c.addEventListener("load",function(){s.loading|=1}),c.addEventListener("error",function(){s.loading|=2}),s.loading|=4,Nd(l,t,r)}l={type:"stylesheet",instance:l,count:1,state:s},a.set(i,l)}}}function yD(e,t){Oa.X(e,t);var n=_s;if(n&&e){var r=po(n).hoistableScripts,a=Ts(e),i=r.get(a);i||(i=n.querySelector(af(a)),i||(e=Ze({src:e,async:!0},t),(t=er.get(a))&&t0(e,t),i=n.createElement("script"),Mt(i),Ht(i,"link",e),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},r.set(a,i))}}function vD(e,t){Oa.M(e,t);var n=_s;if(n&&e){var r=po(n).hoistableScripts,a=Ts(e),i=r.get(a);i||(i=n.querySelector(af(a)),i||(e=Ze({src:e,async:!0,type:"module"},t),(t=er.get(a))&&t0(e,t),i=n.createElement("script"),Mt(i),Ht(i,"link",e),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},r.set(a,i))}}function tS(e,t,n,r){var a=(a=ri.current)?lh(a):null;if(!a)throw Error(F(446));switch(e){case"meta":case"title":return null;case"style":return typeof n.precedence=="string"&&typeof n.href=="string"?(t=Ho(n.href),n=po(a).hoistableStyles,r=n.get(t),r||(r={type:"style",instance:null,count:0,state:null},n.set(t,r)),r):{type:"void",instance:null,count:0,state:null};case"link":if(n.rel==="stylesheet"&&typeof n.href=="string"&&typeof n.precedence=="string"){e=Ho(n.href);var i=po(a).hoistableStyles,l=i.get(e);if(l||(a=a.ownerDocument||a,l={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(e,l),(i=a.querySelector(rf(e)))&&!i._p&&(l.instance=i,l.state.loading=5),er.has(e)||(n={rel:"preload",as:"style",href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},er.set(e,n),i||gD(a,e,n,l.state))),t&&r===null)throw Error(F(528,""));return l}if(t&&r!==null)throw Error(F(529,""));return null;case"script":return t=n.async,n=n.src,typeof n=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Ts(n),n=po(a).hoistableScripts,r=n.get(t),r||(r={type:"script",instance:null,count:0,state:null},n.set(t,r)),r):{type:"void",instance:null,count:0,state:null};default:throw Error(F(444,e))}}function Ho(e){return'href="'+Kn(e)+'"'}function rf(e){return'link[rel="stylesheet"]['+e+"]"}function i_(e){return Ze({},e,{"data-precedence":e.precedence,precedence:null})}function gD(e,t,n,r){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?r.loading=1:(t=e.createElement("link"),r.preload=t,t.addEventListener("load",function(){return r.loading|=1}),t.addEventListener("error",function(){return r.loading|=2}),Ht(t,"link",n),Mt(t),e.head.appendChild(t))}function Ts(e){return'[src="'+Kn(e)+'"]'}function af(e){return"script[async]"+e}function nS(e,t,n){if(t.count++,t.instance===null)switch(t.type){case"style":var r=e.querySelector('style[data-href~="'+Kn(n.href)+'"]');if(r)return t.instance=r,Mt(r),r;var a=Ze({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement("style"),Mt(r),Ht(r,"style",a),Nd(r,n.precedence,e),t.instance=r;case"stylesheet":a=Ho(n.href);var i=e.querySelector(rf(a));if(i)return t.state.loading|=4,t.instance=i,Mt(i),i;r=i_(n),(a=er.get(a))&&e0(r,a),i=(e.ownerDocument||e).createElement("link"),Mt(i);var l=i;return l._p=new Promise(function(s,c){l.onload=s,l.onerror=c}),Ht(i,"link",r),t.state.loading|=4,Nd(i,n.precedence,e),t.instance=i;case"script":return i=Ts(n.src),(a=e.querySelector(af(i)))?(t.instance=a,Mt(a),a):(r=n,(a=er.get(i))&&(r=Ze({},n),t0(r,a)),e=e.ownerDocument||e,a=e.createElement("script"),Mt(a),Ht(a,"link",r),e.head.appendChild(a),t.instance=a);case"void":return null;default:throw Error(F(443,t.type))}else t.type==="stylesheet"&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Nd(r,n.precedence,e));return t.instance}function Nd(e,t,n){for(var r=n.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),a=r.length?r[r.length-1]:null,i=a,l=0;l title"):null)}function xD(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;switch(t.rel){case"stylesheet":return e=t.disabled,typeof t.precedence=="string"&&e==null;default:return!0}case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function l_(e){return!(e.type==="stylesheet"&&!(e.state.loading&3))}function bD(e,t,n,r){if(n.type==="stylesheet"&&(typeof r.media!="string"||matchMedia(r.media).matches!==!1)&&!(n.state.loading&4)){if(n.instance===null){var a=Ho(r.href),i=t.querySelector(rf(a));if(i){t=i._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=oh.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=i,Mt(i);return}i=t.ownerDocument||t,r=i_(r),(a=er.get(a))&&e0(r,a),i=i.createElement("link"),Mt(i);var l=i;l._p=new Promise(function(s,c){l.onload=s,l.onerror=c}),Ht(i,"link",r),n.instance=i}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=oh.bind(e),t.addEventListener("load",n),t.addEventListener("error",n))}}var $y=0;function jD(e,t){return e.stylesheets&&e.count===0&&Cd(e,e.stylesheets),0$y?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(a)}}:null}function oh(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Cd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var sh=null;function Cd(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,sh=new Map,t.forEach(SD,e),sh=null,oh.call(e))}function SD(e,t){if(!(t.state.loading&4)){var n=sh.get(e);if(n)var r=n.get(null);else{n=new Map,sh.set(e,n);for(var a=e.querySelectorAll("link[data-precedence],style[data-precedence]"),i=0;i"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(p_)}catch(e){console.error(e)}}p_(),SE.exports=wp;var TD=SE.exports;const PD=_e(TD);/** - * react-router v7.17.0 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */var fS="popstate";function dS(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function MD(e={}){function t(r,a){var u;let i=(u=a.state)==null?void 0:u.masked,{pathname:l,search:s,hash:c}=i||r.location;return mg("",{pathname:l,search:s,hash:c},a.state&&a.state.usr||null,a.state&&a.state.key||"default",i?{pathname:r.location.pathname,search:r.location.search,hash:r.location.hash}:void 0)}function n(r,a){return typeof a=="string"?a:iu(a)}return RD(t,n,null,e)}function tt(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function br(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function $D(){return Math.random().toString(36).substring(2,10)}function hS(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function mg(e,t,n=null,r,a){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?Ps(t):t,state:n,key:t&&t.key||r||$D(),mask:a}}function iu({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Ps(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function RD(e,t,n,r={}){let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,s="POP",c=null,u=f();u==null&&(u=0,l.replaceState({...l.state,idx:u},""));function f(){return(l.state||{idx:null}).idx}function d(){s="POP";let p=f(),y=p==null?null:p-u;u=p,c&&c({action:s,location:v.location,delta:y})}function h(p,y){s="PUSH";let g=dS(p)?p:mg(v.location,p,y);u=f()+1;let b=hS(g,u),x=v.createHref(g.mask||g);try{l.pushState(b,"",x)}catch(w){if(w instanceof DOMException&&w.name==="DataCloneError")throw w;a.location.assign(x)}i&&c&&c({action:s,location:v.location,delta:1})}function m(p,y){s="REPLACE";let g=dS(p)?p:mg(v.location,p,y);u=f();let b=hS(g,u),x=v.createHref(g.mask||g);l.replaceState(b,"",x),i&&c&&c({action:s,location:v.location,delta:0})}function j(p){return kD(a,p)}let v={get action(){return s},get location(){return e(a,l)},listen(p){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(fS,d),c=p,()=>{a.removeEventListener(fS,d),c=null}},createHref(p){return t(a,p)},createURL:j,encodeLocation(p){let y=j(p);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:h,replace:m,go(p){return l.go(p)}};return v}function kD(e,t,n=!1){let r="http://localhost";e&&(r=e.location.origin!=="null"?e.location.origin:e.location.href),tt(r,"No window.location.(origin|href) available to create URL");let a=typeof t=="string"?t:iu(t);return a=a.replace(/ $/,"%20"),!n&&a.startsWith("//")&&(a=r+a),new URL(a,r)}function m_(e,t,n="/"){return DD(e,t,n,!1)}function DD(e,t,n,r,a){let i=typeof t=="string"?Ps(t):t,l=ba(i.pathname||"/",n);if(l==null)return null;let s=LD(e),c=null,u=XD(l);for(let f=0;c==null&&f{let f={relativePath:u===void 0?l.path||"":u,caseSensitive:l.caseSensitive===!0,childrenIndex:s,route:l};if(f.relativePath.startsWith("/")){if(!f.relativePath.startsWith(r)&&c)return;tt(f.relativePath.startsWith(r),`Absolute route path "${f.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),f.relativePath=f.relativePath.slice(r.length)}let d=mr([r,f.relativePath]),h=n.concat(f);l.children&&l.children.length>0&&(tt(l.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${d}".`),y_(l.children,t,h,d,c)),!(l.path==null&&!l.index)&&t.push({path:d,score:GD(d,l.index),routesMeta:h})};return e.forEach((l,s)=>{var c;if(l.path===""||!((c=l.path)!=null&&c.includes("?")))i(l,s);else for(let u of v_(l.path))i(l,s,!0,u)}),t}function v_(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return a?[i,""]:[i];let l=v_(r.join("/")),s=[];return s.push(...l.map(c=>c===""?i:[i,c].join("/"))),a&&s.push(...l),s.map(c=>e.startsWith("/")&&c===""?"/":c)}function zD(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:KD(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var BD=/^:[\w-]+$/,ID=3,UD=2,qD=1,HD=10,FD=-2,pS=e=>e==="*";function GD(e,t){let n=e.split("/"),r=n.length;return n.some(pS)&&(r+=FD),t&&(r+=UD),n.filter(a=>!pS(a)).reduce((a,i)=>a+(BD.test(i)?ID:i===""?qD:HD),r)}function KD(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function VD(e,t,n=!1){let{routesMeta:r}=e,a={},i="/",l=[];for(let s=0;s{if(f==="*"){let j=s[h]||"";l=i.slice(0,i.length-j.length).replace(/(.)\/+$/,"$1")}const m=s[h];return d&&!m?u[f]=void 0:u[f]=(m||"").replace(/%2F/g,"/"),u},{}),pathname:i,pathnameBase:l,pattern:e}}function YD(e,t=!1,n=!0){br(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,s,c,u,f)=>{if(r.push({paramName:s,isOptional:c!=null}),c){let d=f.charAt(u+l.length);return d&&d!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function XD(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return br(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function ba(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}var QD=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function WD(e,t="/"){let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?Ps(e):e,i;return n?(n=g_(n),n.startsWith("/")?i=mS(n.substring(1),"/"):i=mS(n,t)):i=t,{pathname:i,search:e4(r),hash:t4(a)}}function mS(e,t){let n=dh(t).split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function Ry(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in and the router will parse it for you.`}function ZD(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function l0(e){let t=ZD(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function Up(e,t,n,r=!1){let a;typeof e=="string"?a=Ps(e):(a={...e},tt(!a.pathname||!a.pathname.includes("?"),Ry("?","pathname","search",a)),tt(!a.pathname||!a.pathname.includes("#"),Ry("#","pathname","hash",a)),tt(!a.search||!a.search.includes("#"),Ry("#","search","hash",a)));let i=e===""||a.pathname==="",l=i?"/":a.pathname,s;if(l==null)s=n;else{let d=t.length-1;if(!r&&l.startsWith("..")){let h=l.split("/");for(;h[0]==="..";)h.shift(),d-=1;a.pathname=h.join("/")}s=d>=0?t[d]:"/"}let c=WD(a,s),u=l&&l!=="/"&&l.endsWith("/"),f=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(u||f)&&(c.pathname+="/"),c}var g_=e=>e.replace(/\/\/+/g,"/"),mr=e=>g_(e.join("/")),dh=e=>e.replace(/\/+$/,""),JD=e=>dh(e).replace(/^\/*/,"/"),e4=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,t4=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,n4=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function r4(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function a4(e){let t=e.map(n=>n.route.path).filter(Boolean);return mr(t)||"/"}var x_=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function b_(e,t){let n=e;if(typeof n!="string"||!QD.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,a=!1;if(x_)try{let i=new URL(window.location.href),l=n.startsWith("//")?new URL(i.protocol+n):new URL(n),s=ba(l.pathname,t);l.origin===i.origin&&s!=null?n=s+l.search+l.hash:a=!0}catch{br(!1,` contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:a,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var j_=["POST","PUT","PATCH","DELETE"];new Set(j_);var i4=["GET",...j_];new Set(i4);var Ms=O.createContext(null);Ms.displayName="DataRouter";var qp=O.createContext(null);qp.displayName="DataRouterState";var S_=O.createContext(!1);function l4(){return O.useContext(S_)}var w_=O.createContext({isTransitioning:!1});w_.displayName="ViewTransition";var o4=O.createContext(new Map);o4.displayName="Fetchers";var s4=O.createContext(null);s4.displayName="Await";var kn=O.createContext(null);kn.displayName="Navigation";var lf=O.createContext(null);lf.displayName="Location";var Sr=O.createContext({outlet:null,matches:[],isDataRoute:!1});Sr.displayName="Route";var o0=O.createContext(null);o0.displayName="RouteError";var O_="REACT_ROUTER_ERROR",c4="REDIRECT",u4="ROUTE_ERROR_RESPONSE";function f4(e){if(e.startsWith(`${O_}:${c4}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.location=="string"&&typeof t.reloadDocument=="boolean"&&typeof t.replace=="boolean")return t}catch{}}function d4(e){if(e.startsWith(`${O_}:${u4}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new n4(t.status,t.statusText,t.data)}catch{}}function h4(e,{relative:t}={}){tt($s(),"useHref() may be used only in the context of a component.");let{basename:n,navigator:r}=O.useContext(kn),{hash:a,pathname:i,search:l}=of(e,{relative:t}),s=i;return n!=="/"&&(s=i==="/"?n:mr([n,i])),r.createHref({pathname:s,search:l,hash:a})}function $s(){return O.useContext(lf)!=null}function Hr(){return tt($s(),"useLocation() may be used only in the context of a component."),O.useContext(lf).location}var A_="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function N_(e){O.useContext(kn).static||O.useLayoutEffect(e)}function Hp(){let{isDataRoute:e}=O.useContext(Sr);return e?C4():p4()}function p4(){tt($s(),"useNavigate() may be used only in the context of a component.");let e=O.useContext(Ms),{basename:t,navigator:n}=O.useContext(kn),{matches:r}=O.useContext(Sr),{pathname:a}=Hr(),i=JSON.stringify(l0(r)),l=O.useRef(!1);return N_(()=>{l.current=!0}),O.useCallback((c,u={})=>{if(br(l.current,A_),!l.current)return;if(typeof c=="number"){n.go(c);return}let f=Up(c,JSON.parse(i),a,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:mr([t,f.pathname])),(u.replace?n.replace:n.push)(f,u.state,u)},[t,n,i,a,e])}var m4=O.createContext(null);function y4(e){let t=O.useContext(Sr).outlet;return O.useMemo(()=>t&&O.createElement(m4.Provider,{value:e},t),[t,e])}function of(e,{relative:t}={}){let{matches:n}=O.useContext(Sr),{pathname:r}=Hr(),a=JSON.stringify(l0(n));return O.useMemo(()=>Up(e,JSON.parse(a),r,t==="path"),[e,a,r,t])}function v4(e,t){return E_(e,t)}function E_(e,t,n){var p;tt($s(),"useRoutes() may be used only in the context of a component.");let{navigator:r}=O.useContext(kn),{matches:a}=O.useContext(Sr),i=a[a.length-1],l=i?i.params:{},s=i?i.pathname:"/",c=i?i.pathnameBase:"/",u=i&&i.route;{let y=u&&u.path||"";__(s,!u||y.endsWith("*")||y.endsWith("*?"),`You rendered descendant (or called \`useRoutes()\`) at "${s}" (under ) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. - -Please change the parent to .`)}let f=Hr(),d;if(t){let y=typeof t=="string"?Ps(t):t;tt(c==="/"||((p=y.pathname)==null?void 0:p.startsWith(c)),`When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${y.pathname}" was given in the \`location\` prop.`),d=y}else d=f;let h=d.pathname||"/",m=h;if(c!=="/"){let y=c.replace(/^\//,"").split("/");m="/"+h.replace(/^\//,"").split("/").slice(y.length).join("/")}let j=n&&n.state.matches.length?n.state.matches.map(y=>Object.assign(y,{route:n.manifest[y.route.id]||y.route})):m_(e,{pathname:m});br(u||j!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),br(j==null||j[j.length-1].route.element!==void 0||j[j.length-1].route.Component!==void 0||j[j.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an with a null value by default resulting in an "empty" page.`);let v=S4(j&&j.map(y=>Object.assign({},y,{params:Object.assign({},l,y.params),pathname:mr([c,r.encodeLocation?r.encodeLocation(y.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?c:mr([c,r.encodeLocation?r.encodeLocation(y.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:y.pathnameBase])})),a,n);return t&&v?O.createElement(lf.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",mask:void 0,...d},navigationType:"POP"}},v):v}function g4(){let e=E4(),t=r4(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",a={padding:"0.5rem",backgroundColor:r},i={padding:"2px 4px",backgroundColor:r},l=null;return console.error("Error handled by React Router default ErrorBoundary:",e),l=O.createElement(O.Fragment,null,O.createElement("p",null,"💿 Hey developer 👋"),O.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",O.createElement("code",{style:i},"ErrorBoundary")," or"," ",O.createElement("code",{style:i},"errorElement")," prop on your route.")),O.createElement(O.Fragment,null,O.createElement("h2",null,"Unexpected Application Error!"),O.createElement("h3",{style:{fontStyle:"italic"}},t),n?O.createElement("pre",{style:a},n):null,l)}var x4=O.createElement(g4,null),C_=class extends O.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=d4(e.digest);n&&(e=n)}let t=e!==void 0?O.createElement(Sr.Provider,{value:this.props.routeContext},O.createElement(o0.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?O.createElement(b4,{error:e},t):t}};C_.contextType=S_;var ky=new WeakMap;function b4({children:e,error:t}){let{basename:n}=O.useContext(kn);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=f4(t.digest);if(r){let a=ky.get(t);if(a)throw a;let i=b_(r.location,n);if(x_&&!ky.get(t))if(i.isExternal||r.reloadDocument)window.location.href=i.absoluteURL||i.to;else{const l=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:r.replace}));throw ky.set(t,l),l}return O.createElement("meta",{httpEquiv:"refresh",content:`0;url=${i.absoluteURL||i.to}`})}}return e}function j4({routeContext:e,match:t,children:n}){let r=O.useContext(Ms);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),O.createElement(Sr.Provider,{value:e},n)}function S4(e,t=[],n){let r=n==null?void 0:n.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let a=e,i=r==null?void 0:r.errors;if(i!=null){let f=a.findIndex(d=>d.route.id&&(i==null?void 0:i[d.route.id])!==void 0);tt(f>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(i).join(",")}`),a=a.slice(0,Math.min(a.length,f+1))}let l=!1,s=-1;if(n&&r){l=r.renderFallback;for(let f=0;f=0?a=a.slice(0,s+1):a=[a[0]];break}}}}let c=n==null?void 0:n.onError,u=r&&c?(f,d)=>{var h,m;c(f,{location:r.location,params:((m=(h=r.matches)==null?void 0:h[0])==null?void 0:m.params)??{},pattern:a4(r.matches),errorInfo:d})}:void 0;return a.reduceRight((f,d,h)=>{let m,j=!1,v=null,p=null;r&&(m=i&&d.route.id?i[d.route.id]:void 0,v=d.route.errorElement||x4,l&&(s<0&&h===0?(__("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),j=!0,p=null):s===h&&(j=!0,p=d.route.hydrateFallbackElement||null)));let y=t.concat(a.slice(0,h+1)),g=()=>{let b;return m?b=v:j?b=p:d.route.Component?b=O.createElement(d.route.Component,null):d.route.element?b=d.route.element:b=f,O.createElement(j4,{match:d,routeContext:{outlet:f,matches:y,isDataRoute:r!=null},children:b})};return r&&(d.route.ErrorBoundary||d.route.errorElement||h===0)?O.createElement(C_,{location:r.location,revalidation:r.revalidation,component:v,error:m,children:g(),routeContext:{outlet:null,matches:y,isDataRoute:!0},onError:u}):g()},null)}function s0(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function w4(e){let t=O.useContext(Ms);return tt(t,s0(e)),t}function O4(e){let t=O.useContext(qp);return tt(t,s0(e)),t}function A4(e){let t=O.useContext(Sr);return tt(t,s0(e)),t}function c0(e){let t=A4(e),n=t.matches[t.matches.length-1];return tt(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function N4(){return c0("useRouteId")}function E4(){var r;let e=O.useContext(o0),t=O4("useRouteError"),n=c0("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function C4(){let{router:e}=w4("useNavigate"),t=c0("useNavigate"),n=O.useRef(!1);return N_(()=>{n.current=!0}),O.useCallback(async(a,i={})=>{br(n.current,A_),n.current&&(typeof a=="number"?await e.navigate(a):await e.navigate(a,{fromRouteId:t,...i}))},[e,t])}var yS={};function __(e,t,n){!t&&!yS[e]&&(yS[e]=!0,br(!1,n))}O.memo(_4);function _4({routes:e,manifest:t,future:n,state:r,isStatic:a,onError:i}){return E_(e,void 0,{manifest:t,state:r,isStatic:a,onError:i})}function T_({to:e,replace:t,state:n,relative:r}){tt($s()," may be used only in the context of a component.");let{static:a}=O.useContext(kn);br(!a," must not be used on the initial render in a . This is a no-op, but you should modify your code so the is only ever rendered in response to some user interaction or state change.");let{matches:i}=O.useContext(Sr),{pathname:l}=Hr(),s=Hp(),c=Up(e,l0(i),l,r==="path"),u=JSON.stringify(c);return O.useEffect(()=>{s(JSON.parse(u),{replace:t,state:n,relative:r})},[s,u,r,t,n]),null}function T4(e){return y4(e.context)}function Oe(e){tt(!1,"A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .")}function P4({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:a,static:i=!1,useTransitions:l}){tt(!$s(),"You cannot render a inside another . You should never have more than one in your app.");let s=e.replace(/^\/*/,"/"),c=O.useMemo(()=>({basename:s,navigator:a,static:i,useTransitions:l,future:{}}),[s,a,i,l]);typeof n=="string"&&(n=Ps(n));let{pathname:u="/",search:f="",hash:d="",state:h=null,key:m="default",mask:j}=n,v=O.useMemo(()=>{let p=ba(u,s);return p==null?null:{location:{pathname:p,search:f,hash:d,state:h,key:m,mask:j},navigationType:r}},[s,u,f,d,h,m,r,j]);return br(v!=null,` is not able to match the URL "${u}${f}${d}" because it does not start with the basename, so the won't render anything.`),v==null?null:O.createElement(kn.Provider,{value:c},O.createElement(lf.Provider,{children:t,value:v}))}function M4({children:e,location:t}){return v4(yg(e),t)}function yg(e,t=[]){let n=[];return O.Children.forEach(e,(r,a)=>{if(!O.isValidElement(r))return;let i=[...t,a];if(r.type===O.Fragment){n.push.apply(n,yg(r.props.children,i));return}tt(r.type===Oe,`[${typeof r.type=="string"?r.type:r.type.name}] is not a component. All component children of must be a or `),tt(!r.props.index||!r.props.children,"An index route cannot have child routes.");let l={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=yg(r.props.children,i)),n.push(l)}),n}var Td="get",Pd="application/x-www-form-urlencoded";function Fp(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function $4(e){return Fp(e)&&e.tagName.toLowerCase()==="button"}function R4(e){return Fp(e)&&e.tagName.toLowerCase()==="form"}function k4(e){return Fp(e)&&e.tagName.toLowerCase()==="input"}function D4(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function L4(e,t){return e.button===0&&(!t||t==="_self")&&!D4(e)}var Hf=null;function z4(){if(Hf===null)try{new FormData(document.createElement("form"),0),Hf=!1}catch{Hf=!0}return Hf}var B4=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Dy(e){return e!=null&&!B4.has(e)?(br(!1,`"${e}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${Pd}"`),null):e}function I4(e,t){let n,r,a,i,l;if(R4(e)){let s=e.getAttribute("action");r=s?ba(s,t):null,n=e.getAttribute("method")||Td,a=Dy(e.getAttribute("enctype"))||Pd,i=new FormData(e)}else if($4(e)||k4(e)&&(e.type==="submit"||e.type==="image")){let s=e.form;if(s==null)throw new Error('Cannot submit a + ) +} diff --git a/frontend/src/components/uiws/ui.tsx b/frontend/src/components/uiws/ui.tsx new file mode 100644 index 0000000..a801939 --- /dev/null +++ b/frontend/src/components/uiws/ui.tsx @@ -0,0 +1,171 @@ +/* + * UIWS 이식 공통 컴포넌트 키트 — 색상 하드코딩 금지(테마 토큰 var(--uiws-*)만 사용). + * 다크/라이트 양 모드에서 대비/가독성 정상. 기존 ERP 컴포넌트와 충돌 회피 위해 components/uiws/ 네임스페이스. + */ +import { type ReactNode, type CSSProperties } from 'react' + +const card: CSSProperties = { + background: 'var(--uiws-surface)', + border: '1px solid var(--uiws-border)', + borderRadius: 12, + boxShadow: 'var(--uiws-shadow)', +} + +export function PageHeader({ title, subtitle, actions }: { title: string; subtitle?: string; actions?: ReactNode }) { + return ( +
+
+

{title}

+ {subtitle &&
{subtitle}
} +
+
{actions}
+
+ ) +} + +export function Panel({ children, style }: { children: ReactNode; style?: CSSProperties }) { + return
{children}
+} + +export function Button({ + children, onClick, variant = 'primary', type = 'button', disabled, +}: { + children: ReactNode; onClick?: () => void; variant?: 'primary' | 'ghost' | 'danger' + type?: 'button' | 'submit'; disabled?: boolean +}) { + const styles: Record = { + primary: { background: 'var(--uiws-primary)', color: 'var(--uiws-primary-contrast)', border: 'none' }, + ghost: { background: 'transparent', color: 'var(--uiws-text-muted)', border: '1px solid var(--uiws-border)' }, + danger: { background: 'var(--uiws-danger)', color: '#fff', border: 'none' }, + } + return ( + + ) +} + +export function Input({ + value, onChange, placeholder, type = 'text', style, +}: { + value: string; onChange: (v: string) => void; placeholder?: string; type?: string; style?: CSSProperties +}) { + return ( + onChange(e.target.value)} + style={{ padding: '9px 12px', borderRadius: 8, fontSize: 13, + background: 'var(--uiws-input-bg)', border: '1px solid var(--uiws-border)', color: 'var(--uiws-text)', ...style }} /> + ) +} + +export function FormField({ label, children }: { label: string; children: ReactNode }) { + return ( + + ) +} + +export function SearchBar({ children }: { children: ReactNode }) { + return ( + + {children} + + ) +} + +export interface Column { + key: string + header: string + render?: (row: T) => ReactNode + width?: number | string + align?: 'left' | 'center' | 'right' +} + +export function DataGrid>({ + columns, rows, rowKey, onRowClick, empty = '데이터가 없습니다.', +}: { + columns: Column[]; rows: T[]; rowKey: (row: T) => string | number + onRowClick?: (row: T) => void; empty?: string +}) { + return ( +
+ + + + {columns.map(c => ( + + ))} + + + + {rows.length === 0 ? ( + + ) : rows.map(row => ( + onRowClick?.(row)} + style={{ cursor: onRowClick ? 'pointer' : 'default', borderBottom: '1px solid var(--uiws-border)' }} + onMouseEnter={e => (e.currentTarget.style.background = 'var(--uiws-row-hover)')} + onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}> + {columns.map(c => ( + + ))} + + ))} + +
{c.header}
{empty}
+ {c.render ? c.render(row) : String(row[c.key] ?? '')} +
+
+ ) +} + +export function Pagination({ page, totalPages, onChange }: { page: number; totalPages: number; onChange: (p: number) => void }) { + if (totalPages <= 1) return null + return ( +
+ + + {page + 1} / {totalPages} + + +
+ ) +} + +export function YnBadge({ yn, yes = '읽음', no = '안읽음' }: { yn: string; yes?: string; no?: string }) { + const on = yn === 'Y' + return ( + + {on ? yes : no} + + ) +} + +export function Modal({ title, onClose, children, footer }: { title: string; onClose: () => void; children: ReactNode; footer?: ReactNode }) { + return ( +
+
e.stopPropagation()} + style={{ ...card, width: 'min(560px, 92vw)', maxHeight: '88vh', overflow: 'auto', padding: 22 }}> +
+

{title}

+ +
+
{children}
+ {footer &&
{footer}
} +
+
+ ) +} + +export function Spinner({ label = '불러오는 중...' }: { label?: string }) { + return
{label}
+} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 4a1b150..303352d 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -2,9 +2,13 @@ import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import './index.css' +import './theme/theme.css' +import { ThemeProvider } from './theme/ThemeContext' ReactDOM.createRoot(document.getElementById('root')!).render( - + + + ) diff --git a/frontend/src/pages/Login.tsx b/frontend/src/pages/Login.tsx index 45169c8..fbe30cb 100644 --- a/frontend/src/pages/Login.tsx +++ b/frontend/src/pages/Login.tsx @@ -2,29 +2,52 @@ import { useState } from 'react' import { useNavigate } from 'react-router-dom' import { Cpu } from 'lucide-react' import { login, getMe } from '../api/client' +import { verify2fa } from '../api/uiws' +/** + * GUARDiA MES 로그인 — UIWS 2FA 레이어 대응. + * 1차 login 응답이 twofa="true" 면 인증코드 입력 단계로 전환(verifyToken 보관) → + * /api/mes/auth/verify 로 코드 검증 후 access 토큰 저장. twofa!="true"(off)면 즉시 로그인(회귀 0). + * 인증코드는 서버 로그/메일로만 전달 — 화면/응답에 코드 노출 없음. + */ export default function Login() { const [username, setUsername] = useState('admin') const [password, setPassword] = useState('') const [err, setErr] = useState('') const [busy, setBusy] = useState(false) + const [step, setStep] = useState<'login' | 'verify'>('login') + const [verifyToken, setVerifyToken] = useState('') + const [maskedEmail, setMaskedEmail] = useState('') + const [code, setCode] = useState('') const nav = useNavigate() + // access 토큰 저장 + getMe 로 role/username 보관(Sidebar RBAC 가드 의존) → 대시보드 이동 + const finish = async (token?: string) => { + if (!token) throw new Error('no token') + localStorage.setItem('mes_token', token) + try { + const me = await getMe() + const d = me.data?.data || {} + if (d.role) localStorage.setItem('mes_role', d.role) + if (d.username) localStorage.setItem('mes_user', d.username) + } catch { /* noop */ } + nav('/dashboard') + } + const submit = async (e: React.FormEvent) => { e.preventDefault() setErr(''); setBusy(true) try { const res = await login(username, password) - const token = res.data?.data?.token - if (!token) throw new Error('no token') - localStorage.setItem('mes_token', token) - try { - const me = await getMe() - const d = me.data?.data || {} - if (d.role) localStorage.setItem('mes_role', d.role) - if (d.username) localStorage.setItem('mes_user', d.username) - } catch { /* noop */ } - nav('/dashboard') + const data = res.data?.data || {} + if (data.twofa === 'true') { + // 2단계: verify-token 보관 후 코드 입력 화면으로(코드는 미표시) + setVerifyToken(data.verifyToken) + setMaskedEmail(data.maskedEmail || '') + setStep('verify') + return + } + await finish(data.token) } catch { setErr('로그인 실패 — 아이디/비밀번호를 확인하세요.') } finally { @@ -32,25 +55,63 @@ export default function Login() { } } + const submitCode = async (e: React.FormEvent) => { + e.preventDefault() + setErr(''); setBusy(true) + try { + const res = await verify2fa(verifyToken, code.trim()) + await finish(res.data?.data?.token) + } catch { + setErr('인증 코드가 올바르지 않거나 만료되었습니다.') + } finally { + setBusy(false) + } + } + return (
- +
GUARDiA MES

AI 제조실행시스템 · WMS · MES · QMS

- - setUsername(e.target.value)} - className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" /> - - setPassword(e.target.value)} - className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" /> + + {step === 'login' ? ( + <> + + setUsername(e.target.value)} + className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" /> + + setPassword(e.target.value)} + className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" /> + + ) : ( + <> +

+ 2차 인증 코드를 입력하세요{maskedEmail ? ` (${maskedEmail})` : ''}. +

+ + setCode(e.target.value)} + inputMode="numeric" autoFocus placeholder="6자리 코드" + className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none tracking-widest" /> + + )} + {err &&

{err}

} -

admin / manager / worker · admin123

+ {step === 'verify' && ( + + )} + {step === 'login' && ( +

admin / manager / worker · admin123

+ )}
) diff --git a/frontend/src/pages/uiws/MessageBox.tsx b/frontend/src/pages/uiws/MessageBox.tsx new file mode 100644 index 0000000..a2aa19b --- /dev/null +++ b/frontend/src/pages/uiws/MessageBox.tsx @@ -0,0 +1,118 @@ +import { useEffect, useState } from 'react' +import { listReceived, listSent, receivedDetail, sentDetail, sendMessage } from '../../api/uiws' +import { PageHeader, SearchBar, Input, Button, DataGrid, Pagination, Modal, FormField, YnBadge, Spinner, type Column } from '../../components/uiws/ui' + +type Tab = 'received' | 'sent' + +export default function MessageBox() { + const [tab, setTab] = useState('received') + const [rows, setRows] = useState([]) + const [page, setPage] = useState(0) + const [totalPages, setTotalPages] = useState(0) + const [keyword, setKeyword] = useState('') + const [loading, setLoading] = useState(false) + const [compose, setCompose] = useState(false) + const [detail, setDetail] = useState(null) + + const load = async () => { + setLoading(true) + try { + const fn = tab === 'received' ? listReceived : listSent + const res = await fn({ page, size: 20, titleKeyword: keyword || undefined }) + const data = res.data.data + setRows(data.content ?? []) + setTotalPages(data.totalPages ?? 0) + } finally { + setLoading(false) + } + } + useEffect(() => { load() }, [tab, page]) + + const receivedCols: Column[] = [ + { key: 'title', header: '제목' }, + { key: 'senderNm', header: '보낸사람', width: 130 }, + { key: 'sentAt', header: '받은시각', width: 170 }, + { key: 'readYn', header: '상태', width: 90, render: r => }, + ] + const sentCols: Column[] = [ + { key: 'title', header: '제목' }, + { key: 'receiverSummary', header: '받는사람', width: 160 }, + { key: 'open', header: '개봉', width: 100, align: 'center', render: r => `${r.openCount}/${r.totalCount}` }, + { key: 'sentAt', header: '보낸시각', width: 170 }, + ] + + const open = async (r: any) => { + const res = tab === 'received' ? await receivedDetail(r.messageId) : await sentDetail(r.messageId) + setDetail({ ...res.data.data, _tab: tab }) + if (tab === 'received') load() // 개봉처리 반영 + } + + return ( +
+ setCompose(true)}>+ 쪽지 보내기} /> + + + + +
+ + + + + {loading ? : ( + <> + r.messageId} onRowClick={open} empty="쪽지가 없습니다." /> + + + )} + + {compose && setCompose(false)} onSent={() => { setCompose(false); load() }} />} + {detail && setDetail(null)} />} +
+ ) +} + +function Compose({ onClose, onSent }: { onClose: () => void; onSent: () => void }) { + const [receiverId, setReceiverId] = useState('') + const [title, setTitle] = useState('') + const [content, setContent] = useState('') + const [err, setErr] = useState('') + const send = async () => { + setErr('') + try { + await sendMessage({ title, content, receivers: [{ receiverId, rcvType: 'RECV' }] }) + onSent() + } catch (e: any) { setErr(e?.response?.data?.message || '전송 실패') } + } + return ( + }> + + + + {err &&
{err}
} +
+ ) +} + +function DetailModal({ detail, onClose }: { detail: any; onClose: () => void }) { + return ( + 닫기}> +
+ {detail._tab === 'received' ? `보낸사람: ${detail.senderNm}` : `개봉 ${detail.openCount}/${detail.totalCount}`} · {detail.sentAt} +
+
{detail.content}
+ {detail._tab === 'sent' && detail.receivers && ( +
+
수신자 개봉현황
+ {detail.receivers.map((r: any, i: number) => ( +
+ {r.receiverNm} ({r.rcvType}) +
+ ))} +
+ )} +
+ ) +} diff --git a/frontend/src/pages/uiws/ScheduleCalendar.tsx b/frontend/src/pages/uiws/ScheduleCalendar.tsx new file mode 100644 index 0000000..5a03426 --- /dev/null +++ b/frontend/src/pages/uiws/ScheduleCalendar.tsx @@ -0,0 +1,121 @@ +import { useEffect, useState } from 'react' +import { scheduleCalendar, createSchedule, scheduleDetail, deleteSchedule } from '../../api/uiws' +import { PageHeader, Panel, Button, Modal, FormField, Input, Spinner } from '../../components/uiws/ui' + +interface Sched { scheduleId: number; title: string; startDt: string; endDt: string; scheType: string; importanceCd?: string } + +const WEEK = ['일', '월', '화', '수', '목', '금', '토'] + +export default function ScheduleCalendar() { + const [base, setBase] = useState(new Date()) + const [type, setType] = useState<'PERSONAL' | 'DEPT'>('PERSONAL') + const [items, setItems] = useState([]) + const [loading, setLoading] = useState(false) + const [showForm, setShowForm] = useState(null) // date string + const [detail, setDetail] = useState(null) + + const ym = `${base.getFullYear()}-${String(base.getMonth() + 1).padStart(2, '0')}` + + const load = async () => { + setLoading(true) + try { + const res = await scheduleCalendar({ type, view: 'month', baseDate: `${ym}-01` }) + setItems(res.data.data ?? []) + } finally { + setLoading(false) + } + } + useEffect(() => { load() }, [ym, type]) + + const first = new Date(base.getFullYear(), base.getMonth(), 1) + const startPad = first.getDay() + const daysInMonth = new Date(base.getFullYear(), base.getMonth() + 1, 0).getDate() + const cells: (number | null)[] = [...Array(startPad).fill(null), ...Array.from({ length: daysInMonth }, (_, i) => i + 1)] + + const byDay = (d: number) => { + const ds = `${ym}-${String(d).padStart(2, '0')}` + return items.filter(s => (s.startDt ?? '').slice(0, 10) <= ds && ds <= (s.endDt ?? '').slice(0, 10)) + } + + const move = (delta: number) => setBase(new Date(base.getFullYear(), base.getMonth() + delta, 1)) + + return ( +
+ setShowForm(`${ym}-01`)}>+ 일정 등록} /> + + + +
{ym}
+ +
+ + + + + {loading ? : ( +
+
+ {WEEK.map((w, i) => ( +
{w}
+ ))} + {cells.map((d, i) => ( +
d && setShowForm(`${ym}-${String(d).padStart(2, '0')}`)} + style={{ minHeight: 96, padding: 6, borderRight: '1px solid var(--uiws-border)', borderBottom: '1px solid var(--uiws-border)', + cursor: d ? 'pointer' : 'default' }}> + {d &&
{d}
} + {d && byDay(d).slice(0, 3).map(s => ( +
{ e.stopPropagation(); scheduleDetail(s.scheduleId).then(r => setDetail(r.data.data)) }} + style={{ fontSize: 11, padding: '2px 6px', borderRadius: 6, marginBottom: 3, + background: 'var(--uiws-primary-soft)', color: 'var(--uiws-primary)', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}> + {s.title} +
+ ))} +
+ ))} +
+
+ )} + + {showForm && setShowForm(null)} onSaved={() => { setShowForm(null); load() }} />} + {detail && setDetail(null)} onDeleted={() => { setDetail(null); load() }} />} +
+ ) +} + +function ScheduleForm({ date, type, onClose, onSaved }: { date: string; type: string; onClose: () => void; onSaved: () => void }) { + const [title, setTitle] = useState('') + const [startDt, setStartDt] = useState(`${date}T09:00:00`) + const [endDt, setEndDt] = useState(`${date}T18:00:00`) + const [content, setContent] = useState('') + const [err, setErr] = useState('') + const save = async () => { + setErr('') + try { + await createSchedule({ scheType: type, title, startDt, endDt, content, attachmentIds: [] }) + onSaved() + } catch (e: any) { setErr(e?.response?.data?.message || '저장 실패') } + } + return ( + }> + + + + + {err &&
{err}
} +
+ ) +} + +function ScheduleDetailModal({ detail, onClose, onDeleted }: { detail: any; onClose: () => void; onDeleted: () => void }) { + const remove = async () => { await deleteSchedule(detail.scheduleId); onDeleted() } + return ( + }> +
{detail.scheType} · {detail.startDt} ~ {detail.endDt}
+
{detail.content || '내용 없음'}
+
+ ) +} diff --git a/frontend/src/pages/uiws/StatsPivot.tsx b/frontend/src/pages/uiws/StatsPivot.tsx new file mode 100644 index 0000000..cc9f825 --- /dev/null +++ b/frontend/src/pages/uiws/StatsPivot.tsx @@ -0,0 +1,74 @@ +import { useEffect, useState } from 'react' +import { personalWorkStats, companyWorkStats } from '../../api/uiws' +import { PageHeader, SearchBar, Input, Button, Spinner } from '../../components/uiws/ui' + +interface PivotColumn { key: string; label: string } +interface PivotResponse { fixedColumns: PivotColumn[]; dynamicColumns: PivotColumn[]; rows: Record[] } + +type Mode = 'personal' | 'company' + +export default function StatsPivot() { + const [mode, setMode] = useState('personal') + const [data, setData] = useState(null) + const [loading, setLoading] = useState(false) + const today = new Date().toISOString().slice(0, 10) + const weekAgo = new Date(Date.now() - 6 * 864e5).toISOString().slice(0, 10) + const [fromDate, setFromDate] = useState(weekAgo) + const [toDate, setToDate] = useState(today) + + const load = async () => { + setLoading(true) + try { + const fn = mode === 'personal' ? personalWorkStats : companyWorkStats + const res = await fn({ fromDate, toDate }) + setData(res.data.data) + } finally { + setLoading(false) + } + } + useEffect(() => { load() }, [mode]) + + const cols = data ? [...data.fixedColumns, ...data.dynamicColumns] : [] + + return ( +
+ + + + + +
+ + ~ + + + + + {loading ? : !data || data.rows.length === 0 ? ( +
집계 데이터가 없습니다.
+ ) : ( +
+ + + + {cols.map(c => ( + + ))} + + + + {data.rows.map((row, i) => ( + + {cols.map(c => ( + + ))} + + ))} + +
{c.label}
{String(row[c.key] ?? '')}
+
+ )} +
+ ) +} diff --git a/frontend/src/pages/uiws/WorklogList.tsx b/frontend/src/pages/uiws/WorklogList.tsx new file mode 100644 index 0000000..9b8da02 --- /dev/null +++ b/frontend/src/pages/uiws/WorklogList.tsx @@ -0,0 +1,153 @@ +import { useEffect, useState } from 'react' +import { worklogList, worklogProgress, createWorklog, worklogDetail, deleteWorklog, addWorklogComment } from '../../api/uiws' +import { PageHeader, SearchBar, Input, Button, DataGrid, Pagination, Modal, FormField, Spinner, type Column } from '../../components/uiws/ui' + +interface WorklogRow extends Record { + worklogId: number; title: string; writerNm: string; workDate: string; progressCd: string; commentCount: number +} + +const PROGRESS_LABEL: Record = { ONGOING: '진행중', DONE: '종료' } + +export default function WorklogList() { + const [rows, setRows] = useState([]) + const [page, setPage] = useState(0) + const [totalPages, setTotalPages] = useState(0) + const [progress, setProgress] = useState<{ progressCd: string; progressNm: string; count: number }[]>([]) + const [filterProgress, setFilterProgress] = useState('') + const [keyword, setKeyword] = useState('') + const [loading, setLoading] = useState(false) + const [showForm, setShowForm] = useState(false) + const [detail, setDetail] = useState(null) + + const load = async () => { + setLoading(true) + try { + const res = await worklogList({ page, size: 20, progressCd: filterProgress || undefined }) + const data = res.data.data + setRows(data.content ?? []) + setTotalPages(data.totalPages ?? 0) + const pr = await worklogProgress({}) + setProgress(pr.data.data ?? []) + } finally { + setLoading(false) + } + } + useEffect(() => { load() }, [page, filterProgress]) + + const columns: Column[] = [ + { key: 'workDate', header: '근무일자', width: 120 }, + { key: 'title', header: '제목' }, + { key: 'writerNm', header: '작성자', width: 120 }, + { key: 'progressCd', header: '진행', width: 90, render: r => PROGRESS_LABEL[r.progressCd] ?? r.progressCd }, + { key: 'commentCount', header: '댓글', width: 70, align: 'center' }, + ] + + const openDetail = async (r: WorklogRow) => { + const res = await worklogDetail(r.worklogId) + setDetail(res.data.data) + } + + return ( +
+ setShowForm(true)}>+ 업무일지 작성} /> + +
+ {progress.map(p => ( +
{ setFilterProgress(filterProgress === p.progressCd ? '' : p.progressCd); setPage(0) }} + style={{ cursor: 'pointer', padding: '12px 18px', borderRadius: 10, minWidth: 130, + background: 'var(--uiws-surface)', border: `1px solid ${filterProgress === p.progressCd ? 'var(--uiws-primary)' : 'var(--uiws-border)'}` }}> +
{p.progressNm}
+
{p.count}
+
+ ))} +
+ + + + + {filterProgress && } + + + {loading ? : ( + <> + r.worklogId} onRowClick={openDetail} empty="업무일지가 없습니다." /> + + + )} + + {showForm && setShowForm(false)} onSaved={() => { setShowForm(false); load() }} />} + {detail && setDetail(null)} onChanged={() => { setDetail(null); load() }} />} +
+ ) +} + +function WorklogForm({ onClose, onSaved }: { onClose: () => void; onSaved: () => void }) { + const [title, setTitle] = useState('') + const [writerId, setWriterId] = useState(localStorage.getItem('mes_user') || 'admin') + const [workDate, setWorkDate] = useState(new Date().toISOString().slice(0, 10)) + const [workStatusCd, setWorkStatusCd] = useState('NORMAL') + const [err, setErr] = useState('') + + const save = async () => { + setErr('') + try { + await createWorklog({ title, writerId, workDate, workStatusCd, progressCd: 'ONGOING', details: [] }) + onSaved() + } catch (e: any) { + setErr(e?.response?.data?.message || '저장 실패') + } + } + return ( + }> + + + + + {err &&
{err}
} +
+ ) +} + +function WorklogDetailModal({ detail, onClose, onChanged }: { detail: any; onClose: () => void; onChanged: () => void }) { + const [comment, setComment] = useState('') + const [err, setErr] = useState('') + + const remove = async () => { + await deleteWorklog(detail.worklogId) + onChanged() + } + const addCmt = async () => { + setErr('') + try { + await addWorklogComment(detail.worklogId, comment) + setComment('') + onChanged() + } catch (e: any) { + setErr(e?.response?.data?.message || '댓글 등록 실패') + } + } + return ( + }> +
+ {detail.writerNm} · {detail.workDate} · {detail.progressCd} +
+
시간대별 상세 {detail.details?.length ?? 0}건
+
+
댓글
+ {(detail.comments ?? []).map((c: any) => ( +
+ {c.writerNm} · {c.createdAt}
{c.cmtContent} +
+ ))} +
+ + +
+ {err &&
{err}
} +
+
+ ) +} diff --git a/frontend/src/theme/ThemeContext.tsx b/frontend/src/theme/ThemeContext.tsx new file mode 100644 index 0000000..b0fecbd --- /dev/null +++ b/frontend/src/theme/ThemeContext.tsx @@ -0,0 +1,38 @@ +import { createContext, useContext, useEffect, useState, type ReactNode } from 'react' + +export type ThemeMode = 'dark' | 'light' + +interface ThemeCtx { + theme: ThemeMode + toggle: () => void + setTheme: (t: ThemeMode) => void +} + +const Ctx = createContext({ theme: 'dark', toggle: () => {}, setTheme: () => {} }) + +const STORAGE_KEY = 'mes_theme' + +function applyTheme(t: ThemeMode) { + document.documentElement.setAttribute('data-theme', t) +} + +export function ThemeProvider({ children }: { children: ReactNode }) { + const [theme, setThemeState] = useState(() => { + const saved = localStorage.getItem(STORAGE_KEY) + return saved === 'light' ? 'light' : 'dark' + }) + + useEffect(() => { + applyTheme(theme) + localStorage.setItem(STORAGE_KEY, theme) + }, [theme]) + + const setTheme = (t: ThemeMode) => setThemeState(t) + const toggle = () => setThemeState(prev => (prev === 'dark' ? 'light' : 'dark')) + + return {children} +} + +export function useTheme() { + return useContext(Ctx) +} diff --git a/frontend/src/theme/theme.css b/frontend/src/theme/theme.css new file mode 100644 index 0000000..9a627f6 --- /dev/null +++ b/frontend/src/theme/theme.css @@ -0,0 +1,52 @@ +/* + * GUARDiA MES 테마 토큰 (UIWS 이식 화면 공통). + * 다크/라이트 두 모드 지원. UIWS 화면/컴포넌트는 색상 하드코딩 금지 — 아래 CSS 변수만 사용한다. + * 기존 ERP 화면(인라인 하드코딩 다크)은 영향 없음(이 변수는 UIWS 스코프에서만 참조). + * + * 다크 기본값은 기존 ERP 팔레트(#0f1117/#1a1f2e/#4f8ef7)와 정합. + */ + +:root, +:root[data-theme='dark'] { + --uiws-bg: #0f1117; + --uiws-surface: #1a1f2e; + --uiws-surface-2: #11151f; + --uiws-border: #2d3448; + --uiws-text: #e6edf3; + --uiws-text-muted: #8892b0; + --uiws-text-faint: #4d5568; + --uiws-primary: #4f8ef7; + --uiws-primary-contrast: #ffffff; + --uiws-primary-soft: rgba(79, 142, 247, 0.13); + --uiws-danger: #e74c3c; + --uiws-success: #2ecc71; + --uiws-warning: #f1c40f; + --uiws-row-hover: rgba(255, 255, 255, 0.04); + --uiws-input-bg: #0f1117; + --uiws-shadow: 0 4px 20px rgba(0, 0, 0, 0.35); +} + +:root[data-theme='light'] { + --uiws-bg: #f4f6fb; + --uiws-surface: #ffffff; + --uiws-surface-2: #eef1f7; + --uiws-border: #d8deea; + --uiws-text: #1a1f2e; + --uiws-text-muted: #5b6478; + --uiws-text-faint: #97a0b5; + --uiws-primary: #2f6fe0; + --uiws-primary-contrast: #ffffff; + --uiws-primary-soft: rgba(47, 111, 224, 0.10); + --uiws-danger: #d63b2b; + --uiws-success: #1f9e58; + --uiws-warning: #c79a08; + --uiws-row-hover: rgba(0, 0, 0, 0.035); + --uiws-input-bg: #ffffff; + --uiws-shadow: 0 4px 18px rgba(20, 30, 60, 0.10); +} + +/* UIWS 화면 컨테이너 — 토큰 기반 기본 타이포/배경 */ +.uiws-scope { + color: var(--uiws-text); +} +.uiws-scope a { color: var(--uiws-primary); }