From b33337c6ee6c8acb92757e060726669e0f428e13 Mon Sep 17 00:00:00 2001 From: "DESKTOP-TKLFCPR\\ython" Date: Sat, 20 Jun 2026 20:27:13 +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 + .../com/zioinfo/mall/ai/OllamaClient.java | 2 +- .../com/zioinfo/mall/auth/AuthController.java | 21 +- .../com/zioinfo/mall/auth/AuthService.java | 67 ++- .../java/com/zioinfo/mall/auth/JwtFilter.java | 5 +- .../java/com/zioinfo/mall/auth/JwtUtil.java | 41 ++ .../java/com/zioinfo/mall/auth/MallUser.java | 17 +- .../zioinfo/mall/auth/mapper/UserMapper.java | 40 ++ .../mall/uiws/auth/LoginVerifyMapper.java | 26 + .../mall/uiws/auth/TwoFactorService.java | 161 ++++++ .../mall/uiws/auth/UiwsLoginVerify.java | 19 + .../mall/uiws/common/UiwsApiException.java | 24 + .../mall/uiws/common/UiwsCurrentUser.java | 48 ++ .../mall/uiws/common/UiwsDataScope.java | 29 + .../mall/uiws/common/UiwsErrorCode.java | 48 ++ .../mall/uiws/common/mail/LogMailSender.java | 23 + .../mall/uiws/common/mail/MailSender.java | 10 + .../mall/uiws/config/UiwsProperties.java | 41 ++ .../message/controller/MessageController.java | 86 +++ .../mall/uiws/message/dto/MessageDtos.java | 100 ++++ .../uiws/message/mapper/MessageMapper.java | 78 +++ .../mall/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 +++ .../mall/uiws/schedule/dto/ScheduleDtos.java | 109 ++++ .../uiws/schedule/mapper/ScheduleMapper.java | 93 ++++ .../mall/uiws/schedule/model/UiwsAttach.java | 19 + .../mall/uiws/schedule/model/UiwsDiary.java | 20 + .../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 ++ .../mall/uiws/stats/dto/StatsDtos.java | 25 + .../mall/uiws/stats/mapper/StatsMapper.java | 36 ++ .../mall/uiws/stats/service/StatsService.java | 165 ++++++ .../worklog/controller/WorklogController.java | 108 ++++ .../mall/uiws/worklog/dto/WorklogDtos.java | 118 ++++ .../uiws/worklog/mapper/WorklogMapper.java | 96 ++++ .../mall/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 | 13 +- .../src/main/resources/db/91_uiws_port.sql | 246 +++++++++ .../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-DorNsgV9.js | 514 ++++++++++++++++++ .../static/assets/index-SvOPAsG4.css | 1 + backend/src/main/resources/static/index.html | 4 +- frontend/src/App.tsx | 12 + frontend/src/admin/AdminLayout.tsx | 13 + frontend/src/admin/AdminLogin.tsx | 107 +++- frontend/src/api/uiws.ts | 68 +++ frontend/src/components/uiws/ThemeToggle.tsx | 16 + frontend/src/components/uiws/ui.tsx | 171 ++++++ 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/UiwsLayout.tsx | 22 + frontend/src/pages/uiws/WorklogList.tsx | 153 ++++++ frontend/src/theme/ThemeContext.tsx | 43 ++ frontend/src/theme/theme.css | 53 ++ 72 files changed, 5645 insertions(+), 41 deletions(-) create mode 100644 .gitignore create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/auth/LoginVerifyMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/auth/TwoFactorService.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/auth/UiwsLoginVerify.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsApiException.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsCurrentUser.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsDataScope.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsErrorCode.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/common/mail/LogMailSender.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/common/mail/MailSender.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/config/UiwsProperties.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/message/controller/MessageController.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/message/dto/MessageDtos.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/message/mapper/MessageMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/message/model/UiwsMessage.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/message/model/UiwsMessageRcv.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/message/service/MessageService.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/AttachmentController.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/DiaryController.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/ScheduleController.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/dto/ScheduleDtos.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/mapper/ScheduleMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsAttach.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsDiary.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsSchedule.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/AttachmentService.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/DiaryService.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/FileStorageService.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/ScheduleService.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/stats/controller/StatsController.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/stats/dto/StatsDtos.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/stats/mapper/StatsMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/stats/service/StatsService.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/worklog/controller/WorklogController.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/worklog/dto/WorklogDtos.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/worklog/mapper/WorklogMapper.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklog.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklogCmt.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklogDtl.java create mode 100644 backend/src/main/java/com/zioinfo/mall/uiws/worklog/service/WorklogNotifier.java create mode 100644 backend/src/main/java/com/zioinfo/mall/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 create mode 100644 backend/src/main/resources/static/assets/index-DorNsgV9.js create mode 100644 backend/src/main/resources/static/assets/index-SvOPAsG4.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/UiwsLayout.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/mall/ai/OllamaClient.java b/backend/src/main/java/com/zioinfo/mall/ai/OllamaClient.java index aa7a671..c2d14a7 100644 --- a/backend/src/main/java/com/zioinfo/mall/ai/OllamaClient.java +++ b/backend/src/main/java/com/zioinfo/mall/ai/OllamaClient.java @@ -37,7 +37,7 @@ public class OllamaClient { Map res = builder.baseUrl(ollamaUrl).build() .post().uri("/api/generate").bodyValue(body) .retrieve().bodyToMono(Map.class) - .timeout(Duration.ofSeconds(30)) + .timeout(Duration.ofSeconds(120)) .map(m -> (Map) m).block(); if (res == null) return ""; Object r = res.get("response"); diff --git a/backend/src/main/java/com/zioinfo/mall/auth/AuthController.java b/backend/src/main/java/com/zioinfo/mall/auth/AuthController.java index 7f9b501..19058da 100644 --- a/backend/src/main/java/com/zioinfo/mall/auth/AuthController.java +++ b/backend/src/main/java/com/zioinfo/mall/auth/AuthController.java @@ -1,28 +1,40 @@ package com.zioinfo.mall.auth; import com.zioinfo.mall.common.ApiResponse; +import com.zioinfo.mall.uiws.auth.TwoFactorService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import java.util.Map; +/** + * GUARDiA Mall 인증 컨트롤러. + * - /login: 고객(USER)·2FA off → { token }. 운영(ADMIN/MANAGER)+2FA on → { twofa:"true", verifyToken, step, maskedEmail }. + * - /verify: (UIWS 2FA 이식) verify-token + 인증코드 → access 발급. 운영 로그인 2단계 완료용. + * 기존 고객 클라이언트(token 응답)는 형태 보존 → 쇼핑 로그인 회귀 0. + */ @RestController @RequestMapping("/api/mall/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())); } @PostMapping("/register") public ApiResponse> register(@RequestBody RegisterRequest req) { - String token = authService.register(req.username(), req.password(), req.displayName()); - return ApiResponse.ok(Map.of("token", token, "type", "Bearer")); + return ApiResponse.ok(authService.register(req.username(), req.password(), req.displayName())); + } + + /** UIWS 2FA 이식: 운영 로그인 2차 인증 코드 검증 → access 발급. */ + @PostMapping("/verify") + public ApiResponse> verify(@RequestBody VerifyRequest req) { + return ApiResponse.ok(twoFactorService.verify(req.verifyToken(), req.code())); } @GetMapping("/me") @@ -33,4 +45,5 @@ public class AuthController { record LoginRequest(String username, String password) {} record RegisterRequest(String username, String password, String displayName) {} + record VerifyRequest(String verifyToken, String code) {} } diff --git a/backend/src/main/java/com/zioinfo/mall/auth/AuthService.java b/backend/src/main/java/com/zioinfo/mall/auth/AuthService.java index 6ff2d28..b81bc43 100644 --- a/backend/src/main/java/com/zioinfo/mall/auth/AuthService.java +++ b/backend/src/main/java/com/zioinfo/mall/auth/AuthService.java @@ -1,12 +1,25 @@ package com.zioinfo.mall.auth; import com.zioinfo.mall.auth.mapper.UserMapper; +import com.zioinfo.mall.uiws.auth.TwoFactorService; +import com.zioinfo.mall.uiws.common.UiwsApiException; +import com.zioinfo.mall.uiws.common.UiwsErrorCode; import lombok.RequiredArgsConstructor; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Map; +/** + * GUARDiA Mall 인증 서비스. + * + *

★ 고객/운영 분리: Mall 은 {@code mall_account} 단일 테이블/단일 로그인이지만 역할로 구분된다. + *

    + *
  • 고객(USER) — 쇼핑 로그인: 2FA 미적용(기존 단일 JWT 흐름 그대로, 회귀 0).
  • + *
  • 운영(ADMIN/MANAGER) — 관리자/매장 로그인: UIWS 2FA 레이어 적용(verify-token + 이메일코드 + 실패잠금).
  • + *
+ * 2FA 전역 토글({@code mall.uiws.auth.twofa-enabled})이 off 면 운영 로그인도 단일 JWT(회귀 0). + */ @Service @RequiredArgsConstructor public class AuthService { @@ -14,20 +27,63 @@ 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) { + /** 운영(2FA 대상) 역할 여부 — 고객(USER)은 제외. */ + private static boolean isOperationsRole(String role) { + return "ADMIN".equalsIgnoreCase(role) || "MANAGER".equalsIgnoreCase(role); + } + + /** + * 1차 로그인. + * @return 고객 또는 2FA off: { token, type, twofa:"false" } + * 운영 + 2FA on : { twofa:"true", verifyToken, step:"EMAIL", maskedEmail } + */ + public Map login(String username, String password) { MallUser user = userMapper.findByUsername(username); + + // 잠금 우선 차단(존재하는 운영 계정에 한해 — 존재 여부 누설 최소화) + if (user != null && isOperationsRole(user.getRole()) && twoFactorService.isLocked(user)) { + throw new UiwsApiException(UiwsErrorCode.ACCOUNT_LOCKED); + } if (user == null || !user.isActive()) { throw new RuntimeException("ERR-AUTH-001: 존재하지 않거나 비활성 계정"); } + + boolean twofaTarget = twoFactorService.isEnabled() && isOperationsRole(user.getRole()); + if (!passwordEncoder.matches(password, user.getPasswordHash())) { + // 운영 + 2FA 활성 시 실패 누적/잠금. 고객/비활성 시 기존 동작(메시지만) 유지. + if (twofaTarget) { + twoFactorService.recordLoginFailure(username); + MallUser 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 (twofaTarget) { + Map step1 = twoFactorService.beginTwoFactor(user); + return Map.of( + "twofa", "true", + "verifyToken", step1.get("verifyToken"), + "step", step1.get("step"), + "maskedEmail", step1.getOrDefault("maskedEmail", "")); + } + + // 고객(USER) 또는 2FA 비활성 — 기존 단일 로그인 흐름(회귀 0) + if (isOperationsRole(user.getRole())) { + userMapper.resetLoginFail(username); + } + String token = jwtUtil.generate(username, user.getRole()); + return Map.of("twofa", "false", "token", token, "type", "Bearer"); } - /** 고객 셀프 회원가입 — 항상 USER 역할로 생성. */ - public String register(String username, String password, String displayName) { + /** 고객 셀프 회원가입 — 항상 USER 역할로 생성(2FA 미적용 대상). */ + public Map register(String username, String password, String displayName) { if (username == null || username.isBlank() || password == null || password.isBlank()) { throw new IllegalArgumentException("ERR-AUTH-400: username/password 필수"); } @@ -41,7 +97,8 @@ public class AuthService { user.setDisplayName(displayName == null || displayName.isBlank() ? username : displayName); user.setActive(true); userMapper.insert(user); - return jwtUtil.generate(username, "USER"); + String token = jwtUtil.generate(username, "USER"); + return Map.of("twofa", "false", "token", token, "type", "Bearer"); } public Map me(String token) { diff --git a/backend/src/main/java/com/zioinfo/mall/auth/JwtFilter.java b/backend/src/main/java/com/zioinfo/mall/auth/JwtFilter.java index 5e80909..9efbf4d 100644 --- a/backend/src/main/java/com/zioinfo/mall/auth/JwtFilter.java +++ b/backend/src/main/java/com/zioinfo/mall/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/mall/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/mall/auth/JwtUtil.java b/backend/src/main/java/com/zioinfo/mall/auth/JwtUtil.java index 24e5d94..205c635 100644 --- a/backend/src/main/java/com/zioinfo/mall/auth/JwtUtil.java +++ b/backend/src/main/java/com/zioinfo/mall/auth/JwtUtil.java @@ -34,6 +34,47 @@ 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 을 걸러내는 데 사용. + * verify-token 은 access 와 동일 서명키라 isValid() 는 통과 → 반드시 별도 차단(2FA 우회 방지). + */ + 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/mall/auth/MallUser.java b/backend/src/main/java/com/zioinfo/mall/auth/MallUser.java index 1ee29f5..523f15f 100644 --- a/backend/src/main/java/com/zioinfo/mall/auth/MallUser.java +++ b/backend/src/main/java/com/zioinfo/mall/auth/MallUser.java @@ -3,7 +3,7 @@ package com.zioinfo.mall.auth; import lombok.Data; import java.time.LocalDateTime; -/** 계정 (mall_account). 역할: ADMIN/MANAGER/USER(고객). */ +/** 계정 (mall_account). 역할: ADMIN/MANAGER(운영) · USER(고객). */ @Data public class MallUser { private Long id; @@ -13,4 +13,19 @@ public class MallUser { private String displayName; private boolean active; private LocalDateTime createdAt; + + // ── UIWS 2FA 이식 컬럼 (mall_account ALTER, db/91_uiws_port.sql) ─────────────── + // 2FA는 운영(ADMIN/MANAGER) 로그인에만 적용 — 고객(USER) 쇼핑 로그인은 회귀 0. + /** 2FA 발송 대상 이메일(원본 mall_account 미보유 → 91_uiws_port.sql 에서 추가). */ + 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/mall/auth/mapper/UserMapper.java b/backend/src/main/java/com/zioinfo/mall/auth/mapper/UserMapper.java index c21ae8a..aa20e63 100644 --- a/backend/src/main/java/com/zioinfo/mall/auth/mapper/UserMapper.java +++ b/backend/src/main/java/com/zioinfo/mall/auth/mapper/UserMapper.java @@ -3,7 +3,14 @@ package com.zioinfo.mall.auth.mapper; import com.zioinfo.mall.auth.MallUser; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Update; +import java.time.LocalDateTime; + +/** + * 계정 매퍼. findByUsername/insert/countByUsername 는 UserMapper.xml 에 정의(2FA 컬럼 포함 resultMap). + * UIWS 2FA 이식 UPDATE 5종은 어노테이션으로 추가 — XML 중복 정의 없음(빈 등록 충돌 회피). + */ @Mapper public interface UserMapper { @@ -12,4 +19,37 @@ public interface UserMapper { int insert(MallUser user); int countByUsername(@Param("username") String username); + + // ── UIWS 2FA 이식: 실패 카운트/잠금/인증코드 갱신 (멱등 UPDATE) ─────────────── + + /** 로그인 성공 시 실패 카운트 초기화. */ + @Update("UPDATE mall_account SET login_fail_count = 0 WHERE username = #{username}") + int resetLoginFail(@Param("username") String username); + + /** 로그인 실패 누적(+1) 및 임계 도달 시 잠금. */ + @Update(""" + UPDATE mall_account + 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 mall_account + 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 mall_account SET email_verify_code = NULL, email_verify_expire = NULL WHERE username = #{username}") + int clearEmailCode(@Param("username") String username); + + /** 관리자 잠금 해제(실패 카운트/잠금 초기화). */ + @Update("UPDATE mall_account 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/mall/uiws/auth/LoginVerifyMapper.java b/backend/src/main/java/com/zioinfo/mall/uiws/auth/LoginVerifyMapper.java new file mode 100644 index 0000000..b856caa --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/auth/LoginVerifyMapper.java @@ -0,0 +1,26 @@ +package com.zioinfo.mall.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/mall/uiws/auth/TwoFactorService.java b/backend/src/main/java/com/zioinfo/mall/uiws/auth/TwoFactorService.java new file mode 100644 index 0000000..e9aa0de --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/auth/TwoFactorService.java @@ -0,0 +1,161 @@ +package com.zioinfo.mall.uiws.auth; + +import com.zioinfo.mall.auth.JwtUtil; +import com.zioinfo.mall.auth.mapper.UserMapper; +import com.zioinfo.mall.auth.MallUser; +import com.zioinfo.mall.uiws.common.UiwsApiException; +import com.zioinfo.mall.uiws.common.UiwsErrorCode; +import com.zioinfo.mall.uiws.common.mail.MailSender; +import com.zioinfo.mall.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(MallUser user) { + return Boolean.TRUE.equals(user.getLocked()); + } + + /** + * 1차 로그인 성공 후 2차 인증 시작: verify-token 발급 + 이메일코드 발송 + 감사 기록 + 실패카운트 초기화. + * @return { verifyToken, step:"EMAIL", maskedEmail } + */ + @Transactional + public Map beginTwoFactor(MallUser 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 Mall] 로그인 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); + } + MallUser 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/mall/uiws/auth/UiwsLoginVerify.java b/backend/src/main/java/com/zioinfo/mall/uiws/auth/UiwsLoginVerify.java new file mode 100644 index 0000000..b6a0d89 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/auth/UiwsLoginVerify.java @@ -0,0 +1,19 @@ +package com.zioinfo.mall.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/mall/uiws/common/UiwsApiException.java b/backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsApiException.java new file mode 100644 index 0000000..ece4961 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsApiException.java @@ -0,0 +1,24 @@ +package com.zioinfo.mall.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/mall/uiws/common/UiwsCurrentUser.java b/backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsCurrentUser.java new file mode 100644 index 0000000..feb05b3 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsCurrentUser.java @@ -0,0 +1,48 @@ +package com.zioinfo.mall.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/mall/uiws/common/UiwsDataScope.java b/backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsDataScope.java new file mode 100644 index 0000000..75591ee --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsDataScope.java @@ -0,0 +1,29 @@ +package com.zioinfo.mall.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/mall/uiws/common/UiwsErrorCode.java b/backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsErrorCode.java new file mode 100644 index 0000000..37fd44a --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/common/UiwsErrorCode.java @@ -0,0 +1,48 @@ +package com.zioinfo.mall.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/mall/uiws/common/mail/LogMailSender.java b/backend/src/main/java/com/zioinfo/mall/uiws/common/mail/LogMailSender.java new file mode 100644 index 0000000..e734e4b --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/common/mail/LogMailSender.java @@ -0,0 +1,23 @@ +package com.zioinfo.mall.uiws.common.mail; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** + * 로컬/개발/미설정용 메일 발송 폴백. 실제 전송 없이 로그로만 기록한다(외부 호출 0). + * mall.uiws.mail.mode=log (기본) 일 때 활성. SMTP 운영 시 mode=smtp 로 별도 구현 빈 활성화. + * + * 보안: 본문에 인증코드/임시비밀번호가 포함되므로 로그 레벨은 운영에서 조정. + * (인증코드는 API 응답으로는 절대 반환하지 않는다 — 메일/로그 채널로만 전달.) + */ +@Slf4j +@Component +@ConditionalOnProperty(name = "mall.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/mall/uiws/common/mail/MailSender.java b/backend/src/main/java/com/zioinfo/mall/uiws/common/mail/MailSender.java new file mode 100644 index 0000000..a342d16 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/common/mail/MailSender.java @@ -0,0 +1,10 @@ +package com.zioinfo.mall.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/mall/uiws/config/UiwsProperties.java b/backend/src/main/java/com/zioinfo/mall/uiws/config/UiwsProperties.java new file mode 100644 index 0000000..19f24d4 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/config/UiwsProperties.java @@ -0,0 +1,41 @@ +package com.zioinfo.mall.uiws.config; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * UIWS 이식 모듈 설정. application.yml 의 mall.uiws.* 바인딩. + * 계획서 2FA 설정키(verify-token-validity / max-login-fail / email-code-validity) + + * 첨부 업로드 디렉터리. 모두 안전 기본값 보유(미설정이어도 동작). + */ +@Getter +@Setter +@Component +@ConfigurationProperties(prefix = "mall.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/mall/uiws/message/controller/MessageController.java b/backend/src/main/java/com/zioinfo/mall/uiws/message/controller/MessageController.java new file mode 100644 index 0000000..e85be96 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/message/controller/MessageController.java @@ -0,0 +1,86 @@ +package com.zioinfo.mall.uiws.message.controller; + +import com.zioinfo.mall.common.ApiResponse; +import com.zioinfo.mall.uiws.message.dto.MessageDtos.*; +import com.zioinfo.mall.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/mall/uiws/message/dto/MessageDtos.java b/backend/src/main/java/com/zioinfo/mall/uiws/message/dto/MessageDtos.java new file mode 100644 index 0000000..a664518 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/message/dto/MessageDtos.java @@ -0,0 +1,100 @@ +package com.zioinfo.mall.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/mall/uiws/message/mapper/MessageMapper.java b/backend/src/main/java/com/zioinfo/mall/uiws/message/mapper/MessageMapper.java new file mode 100644 index 0000000..64344d4 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/message/mapper/MessageMapper.java @@ -0,0 +1,78 @@ +package com.zioinfo.mall.uiws.message.mapper; + +import com.zioinfo.mall.uiws.message.model.UiwsMessage; +import com.zioinfo.mall.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 변환 이식. + * 사용자명은 mall_account(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/mall/uiws/message/model/UiwsMessage.java b/backend/src/main/java/com/zioinfo/mall/uiws/message/model/UiwsMessage.java new file mode 100644 index 0000000..a4d7e25 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/message/model/UiwsMessage.java @@ -0,0 +1,24 @@ +package com.zioinfo.mall.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/mall/uiws/message/model/UiwsMessageRcv.java b/backend/src/main/java/com/zioinfo/mall/uiws/message/model/UiwsMessageRcv.java new file mode 100644 index 0000000..25bd804 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/message/model/UiwsMessageRcv.java @@ -0,0 +1,22 @@ +package com.zioinfo.mall.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/mall/uiws/message/service/MessageService.java b/backend/src/main/java/com/zioinfo/mall/uiws/message/service/MessageService.java new file mode 100644 index 0000000..8417ee8 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/message/service/MessageService.java @@ -0,0 +1,271 @@ +package com.zioinfo.mall.uiws.message.service; + +import com.zioinfo.mall.uiws.common.UiwsApiException; +import com.zioinfo.mall.uiws.common.UiwsCurrentUser; +import com.zioinfo.mall.uiws.common.UiwsErrorCode; +import com.zioinfo.mall.uiws.message.dto.MessageDtos.*; +import com.zioinfo.mall.uiws.message.mapper.MessageMapper; +import com.zioinfo.mall.uiws.message.model.UiwsMessage; +import com.zioinfo.mall.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/mall/uiws/schedule/controller/AttachmentController.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/AttachmentController.java new file mode 100644 index 0000000..c012c29 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/AttachmentController.java @@ -0,0 +1,74 @@ +package com.zioinfo.mall.uiws.schedule.controller; + +import com.zioinfo.mall.common.ApiResponse; +import com.zioinfo.mall.uiws.schedule.dto.ScheduleDtos.AttachmentDto; +import com.zioinfo.mall.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/mall/uiws/schedule/controller/DiaryController.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/DiaryController.java new file mode 100644 index 0000000..237500d --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/DiaryController.java @@ -0,0 +1,60 @@ +package com.zioinfo.mall.uiws.schedule.controller; + +import com.zioinfo.mall.common.ApiResponse; +import com.zioinfo.mall.uiws.schedule.dto.ScheduleDtos.*; +import com.zioinfo.mall.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/mall/uiws/schedule/controller/ScheduleController.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/ScheduleController.java new file mode 100644 index 0000000..3ce0690 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/controller/ScheduleController.java @@ -0,0 +1,78 @@ +package com.zioinfo.mall.uiws.schedule.controller; + +import com.zioinfo.mall.common.ApiResponse; +import com.zioinfo.mall.uiws.schedule.dto.ScheduleDtos.*; +import com.zioinfo.mall.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/mall/uiws/schedule/dto/ScheduleDtos.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/dto/ScheduleDtos.java new file mode 100644 index 0000000..3e7f479 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/dto/ScheduleDtos.java @@ -0,0 +1,109 @@ +package com.zioinfo.mall.uiws.schedule.dto; + +import com.zioinfo.mall.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/mall/uiws/schedule/mapper/ScheduleMapper.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/mapper/ScheduleMapper.java new file mode 100644 index 0000000..859faf7 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/mapper/ScheduleMapper.java @@ -0,0 +1,93 @@ +package com.zioinfo.mall.uiws.schedule.mapper; + +import com.zioinfo.mall.uiws.schedule.model.UiwsAttach; +import com.zioinfo.mall.uiws.schedule.model.UiwsDiary; +import com.zioinfo.mall.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/mall/uiws/schedule/model/UiwsAttach.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsAttach.java new file mode 100644 index 0000000..adc8e39 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsAttach.java @@ -0,0 +1,19 @@ +package com.zioinfo.mall.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/mall/uiws/schedule/model/UiwsDiary.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsDiary.java new file mode 100644 index 0000000..bb42e5c --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsDiary.java @@ -0,0 +1,20 @@ +package com.zioinfo.mall.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/mall/uiws/schedule/model/UiwsSchedule.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsSchedule.java new file mode 100644 index 0000000..cfa1004 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/model/UiwsSchedule.java @@ -0,0 +1,24 @@ +package com.zioinfo.mall.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/mall/uiws/schedule/service/AttachmentService.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/AttachmentService.java new file mode 100644 index 0000000..a897c2c --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/AttachmentService.java @@ -0,0 +1,121 @@ +package com.zioinfo.mall.uiws.schedule.service; + +import com.zioinfo.mall.uiws.common.UiwsApiException; +import com.zioinfo.mall.uiws.common.UiwsCurrentUser; +import com.zioinfo.mall.uiws.common.UiwsErrorCode; +import com.zioinfo.mall.uiws.schedule.dto.ScheduleDtos.AttachmentDto; +import com.zioinfo.mall.uiws.schedule.mapper.ScheduleMapper; +import com.zioinfo.mall.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/mall/uiws/schedule/service/DiaryService.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/DiaryService.java new file mode 100644 index 0000000..aed766f --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/DiaryService.java @@ -0,0 +1,133 @@ +package com.zioinfo.mall.uiws.schedule.service; + +import com.zioinfo.mall.uiws.common.UiwsApiException; +import com.zioinfo.mall.uiws.common.UiwsCurrentUser; +import com.zioinfo.mall.uiws.common.UiwsErrorCode; +import com.zioinfo.mall.uiws.schedule.dto.ScheduleDtos.*; +import com.zioinfo.mall.uiws.schedule.mapper.ScheduleMapper; +import com.zioinfo.mall.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/mall/uiws/schedule/service/FileStorageService.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/FileStorageService.java new file mode 100644 index 0000000..339e001 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/FileStorageService.java @@ -0,0 +1,93 @@ +package com.zioinfo.mall.uiws.schedule.service; + +import com.zioinfo.mall.uiws.common.UiwsApiException; +import com.zioinfo.mall.uiws.common.UiwsErrorCode; +import com.zioinfo.mall.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/mall/uiws/schedule/service/ScheduleService.java b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/ScheduleService.java new file mode 100644 index 0000000..8ecfa4d --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/schedule/service/ScheduleService.java @@ -0,0 +1,216 @@ +package com.zioinfo.mall.uiws.schedule.service; + +import com.zioinfo.mall.uiws.common.UiwsApiException; +import com.zioinfo.mall.uiws.common.UiwsCurrentUser; +import com.zioinfo.mall.uiws.common.UiwsDataScope; +import com.zioinfo.mall.uiws.common.UiwsErrorCode; +import com.zioinfo.mall.uiws.schedule.dto.ScheduleDtos.*; +import com.zioinfo.mall.uiws.schedule.mapper.ScheduleMapper; +import com.zioinfo.mall.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/mall/uiws/stats/controller/StatsController.java b/backend/src/main/java/com/zioinfo/mall/uiws/stats/controller/StatsController.java new file mode 100644 index 0000000..0926f8e --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/stats/controller/StatsController.java @@ -0,0 +1,48 @@ +package com.zioinfo.mall.uiws.stats.controller; + +import com.zioinfo.mall.common.ApiResponse; +import com.zioinfo.mall.uiws.stats.dto.StatsDtos.PivotResponse; +import com.zioinfo.mall.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/mall/uiws/stats/dto/StatsDtos.java b/backend/src/main/java/com/zioinfo/mall/uiws/stats/dto/StatsDtos.java new file mode 100644 index 0000000..162d2ec --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/stats/dto/StatsDtos.java @@ -0,0 +1,25 @@ +package com.zioinfo.mall.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/mall/uiws/stats/mapper/StatsMapper.java b/backend/src/main/java/com/zioinfo/mall/uiws/stats/mapper/StatsMapper.java new file mode 100644 index 0000000..5e3c8e1 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/stats/mapper/StatsMapper.java @@ -0,0 +1,36 @@ +package com.zioinfo.mall.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 미이식): + * - 근무자 라벨: mall_account.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/mall/uiws/stats/service/StatsService.java b/backend/src/main/java/com/zioinfo/mall/uiws/stats/service/StatsService.java new file mode 100644 index 0000000..f7bf9bf --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/stats/service/StatsService.java @@ -0,0 +1,165 @@ +package com.zioinfo.mall.uiws.stats.service; + +import com.zioinfo.mall.uiws.common.UiwsDataScope; +import com.zioinfo.mall.uiws.stats.dto.StatsDtos.PivotColumn; +import com.zioinfo.mall.uiws.stats.dto.StatsDtos.PivotResponse; +import com.zioinfo.mall.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/mall/uiws/worklog/controller/WorklogController.java b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/controller/WorklogController.java new file mode 100644 index 0000000..f541051 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/controller/WorklogController.java @@ -0,0 +1,108 @@ +package com.zioinfo.mall.uiws.worklog.controller; + +import com.zioinfo.mall.common.ApiResponse; +import com.zioinfo.mall.uiws.worklog.dto.WorklogDtos.*; +import com.zioinfo.mall.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/mall/uiws/worklog/dto/WorklogDtos.java b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/dto/WorklogDtos.java new file mode 100644 index 0000000..9c5ad49 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/dto/WorklogDtos.java @@ -0,0 +1,118 @@ +package com.zioinfo.mall.uiws.worklog.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.zioinfo.mall.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/mall/uiws/worklog/mapper/WorklogMapper.java b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/mapper/WorklogMapper.java new file mode 100644 index 0000000..7547ae4 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/mapper/WorklogMapper.java @@ -0,0 +1,96 @@ +package com.zioinfo.mall.uiws.worklog.mapper; + +import com.zioinfo.mall.uiws.worklog.model.UiwsWorklog; +import com.zioinfo.mall.uiws.worklog.model.UiwsWorklogCmt; +import com.zioinfo.mall.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/mall/uiws/worklog/model/UiwsWorklog.java b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklog.java new file mode 100644 index 0000000..fd72fc9 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklog.java @@ -0,0 +1,23 @@ +package com.zioinfo.mall.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/mall/uiws/worklog/model/UiwsWorklogCmt.java b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklogCmt.java new file mode 100644 index 0000000..c150f39 --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklogCmt.java @@ -0,0 +1,19 @@ +package com.zioinfo.mall.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/mall/uiws/worklog/model/UiwsWorklogDtl.java b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklogDtl.java new file mode 100644 index 0000000..d50eaed --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/model/UiwsWorklogDtl.java @@ -0,0 +1,22 @@ +package com.zioinfo.mall.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/mall/uiws/worklog/service/WorklogNotifier.java b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/service/WorklogNotifier.java new file mode 100644 index 0000000..c52a16c --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/service/WorklogNotifier.java @@ -0,0 +1,31 @@ +package com.zioinfo.mall.uiws.worklog.service; + +import com.zioinfo.mall.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/mall/uiws/worklog/service/WorklogService.java b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/service/WorklogService.java new file mode 100644 index 0000000..bc4dc9c --- /dev/null +++ b/backend/src/main/java/com/zioinfo/mall/uiws/worklog/service/WorklogService.java @@ -0,0 +1,438 @@ +package com.zioinfo.mall.uiws.worklog.service; + +import com.zioinfo.mall.uiws.common.UiwsApiException; +import com.zioinfo.mall.uiws.common.UiwsCurrentUser; +import com.zioinfo.mall.uiws.common.UiwsDataScope; +import com.zioinfo.mall.uiws.common.UiwsErrorCode; +import com.zioinfo.mall.uiws.worklog.dto.WorklogDtos.*; +import com.zioinfo.mall.uiws.worklog.mapper.WorklogMapper; +import com.zioinfo.mall.uiws.worklog.model.UiwsWorklog; +import com.zioinfo.mall.uiws.worklog.model.UiwsWorklogCmt; +import com.zioinfo.mall.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 f11a46f..658e0f7 100644 --- a/backend/src/main/resources/application.yml +++ b/backend/src/main/resources/application.yml @@ -13,7 +13,7 @@ spring: max-file-size: 20MB max-request-size: 20MB mybatis: - mapper-locations: classpath:mapper/*.xml + mapper-locations: classpath:mapper/**/*.xml # ** : 하위 mapper/uiws/*.xml(UIWS 이식) 포함 configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl @@ -34,6 +34,17 @@ mall: provider: ${MALL_SMS_PROVIDER:mock} # mock | twilio email: provider: ${MALL_EMAIL_PROVIDER:mock} # mock | sendgrid + # ── UIWS 이식: 2FA(운영 로그인) + 첨부 업로드 설정 (mall.uiws.*) ────────────── + uiws: + auth: + twofa-enabled: ${UIWS_2FA:true} # off=운영 로그인도 단일 JWT(회귀 0). 고객(USER)은 항상 미적용. + 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: itsm-url: ${ITSM_URL:http://localhost:9001} erp-url: ${ERP_URL:http://localhost:8003} 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..7e3a234 --- /dev/null +++ b/backend/src/main/resources/db/91_uiws_port.sql @@ -0,0 +1,246 @@ +-- ============================================================================ +-- UIWS 업무 테이블 이식 (Mall) — 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 키 / Mall mall_account 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, -- Mall mall_accountname 논리참조 + 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 테이블(mall_account) 컬럼 보강 (DROP/재정의 금지 — ADD COLUMN IF NOT EXISTS 멱등) +-- ★ Mall 차이: mall_account 원본은 email 컬럼 미보유 → 2FA 코드 발송 대상 확보 위해 email 도 추가. +-- 이메일 인증코드·만료시각, 실패 카운트(기본 0), 잠금(기본 false), OTP 시크릿. +-- ※ 2FA 는 운영(ADMIN/MANAGER) 로그인에만 적용 — 고객(USER) 쇼핑 로그인 회귀 0. +-- ─────────────────────────────────────────────────────────────────────────── +ALTER TABLE mall_account ADD COLUMN IF NOT EXISTS email VARCHAR(255); +ALTER TABLE mall_account ADD COLUMN IF NOT EXISTS email_verify_code VARCHAR(10); +ALTER TABLE mall_account ADD COLUMN IF NOT EXISTS email_verify_expire TIMESTAMP; +ALTER TABLE mall_account ADD COLUMN IF NOT EXISTS login_fail_count INT DEFAULT 0; +ALTER TABLE mall_account ADD COLUMN IF NOT EXISTS locked BOOLEAN DEFAULT false; +ALTER TABLE mall_account ADD COLUMN IF NOT EXISTS otp_secret VARCHAR(255); + +-- end 91_uiws_port.sql diff --git a/backend/src/main/resources/mapper/UserMapper.xml b/backend/src/main/resources/mapper/UserMapper.xml index a9d98da..3e0bf65 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..ebffee7 --- /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..44abfed --- /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..f01bdc9 --- /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..8a11f77 --- /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..736a1ef --- /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-DorNsgV9.js b/backend/src/main/resources/static/assets/index-DorNsgV9.js new file mode 100644 index 0000000..820eea6 --- /dev/null +++ b/backend/src/main/resources/static/assets/index-DorNsgV9.js @@ -0,0 +1,514 @@ +var MA=e=>{throw TypeError(e)};var iv=(e,t,n)=>t.has(e)||MA("Cannot "+n);var R=(e,t,n)=>(iv(e,t,"read from private field"),n?n.call(e):t.get(e)),ce=(e,t,n)=>t.has(e)?MA("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),ee=(e,t,n,r)=>(iv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Oe=(e,t,n)=>(iv(e,t,"access private method"),n);var oh=(e,t,n,r)=>({set _(a){ee(e,t,a,n)},get _(){return R(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 s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).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 lh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ie(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var KP={exports:{}},Ey={};/** + * @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 Sz=Symbol.for("react.transitional.element"),wz=Symbol.for("react.fragment");function GP(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:Sz,type:e,key:r,ref:t!==void 0?t:null,props:n}}Ey.Fragment=wz;Ey.jsx=GP;Ey.jsxs=GP;KP.exports=Ey;var u=KP.exports,YP={exports:{}},xe={};/** + * @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 dS=Symbol.for("react.transitional.element"),jz=Symbol.for("react.portal"),Az=Symbol.for("react.fragment"),Oz=Symbol.for("react.strict_mode"),Ez=Symbol.for("react.profiler"),Tz=Symbol.for("react.consumer"),Nz=Symbol.for("react.context"),Cz=Symbol.for("react.forward_ref"),_z=Symbol.for("react.suspense"),Pz=Symbol.for("react.memo"),WP=Symbol.for("react.lazy"),Mz=Symbol.for("react.activity"),RA=Symbol.iterator;function Rz(e){return e===null||typeof e!="object"?null:(e=RA&&e[RA]||e["@@iterator"],typeof e=="function"?e:null)}var XP={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},QP=Object.assign,ZP={};function Nc(e,t,n){this.props=e,this.context=t,this.refs=ZP,this.updater=n||XP}Nc.prototype.isReactComponent={};Nc.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")};Nc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function JP(){}JP.prototype=Nc.prototype;function hS(e,t,n){this.props=e,this.context=t,this.refs=ZP,this.updater=n||XP}var pS=hS.prototype=new JP;pS.constructor=hS;QP(pS,Nc.prototype);pS.isPureReactComponent=!0;var DA=Array.isArray;function Qb(){}var it={H:null,A:null,T:null,S:null},eM=Object.prototype.hasOwnProperty;function mS(e,t,n){var r=n.ref;return{$$typeof:dS,type:e,key:t,ref:r!==void 0?r:null,props:n}}function Dz(e,t){return mS(e.type,t,e.props)}function yS(e){return typeof e=="object"&&e!==null&&e.$$typeof===dS}function kz(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var kA=/\/+/g;function sv(e,t){return typeof e=="object"&&e!==null&&e.key!=null?kz(""+e.key):t.toString(36)}function $z(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(Qb,Qb):(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 Vo(e,t,n,r,a){var i=typeof e;(i==="undefined"||i==="boolean")&&(e=null);var s=!1;if(e===null)s=!0;else switch(i){case"bigint":case"string":case"number":s=!0;break;case"object":switch(e.$$typeof){case dS:case jz:s=!0;break;case WP:return s=e._init,Vo(s(e._payload),t,n,r,a)}}if(s)return a=a(e),s=r===""?"."+sv(e,0):r,DA(a)?(n="",s!=null&&(n=s.replace(kA,"$&/")+"/"),Vo(a,t,n,"",function(c){return c})):a!=null&&(yS(a)&&(a=Dz(a,n+(a.key==null||e&&e.key===a.key?"":(""+a.key).replace(kA,"$&/")+"/")+s)),t.push(a)),1;s=0;var o=r===""?".":r+":";if(DA(e))for(var l=0;l>>1,H=P[F];if(0>>1;Fa(te,I))Za(ye,te)?(P[F]=ye,P[Z]=I,F=Z):(P[F]=te,P[K]=I,F=K);else if(Za(ye,I))P[F]=ye,P[Z]=I,F=Z;else break e}}return $}function a(P,$){var I=P.sortIndex-$.sortIndex;return I!==0?I:P.id-$.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 s=Date,o=s.now();e.unstable_now=function(){return s.now()-o}}var l=[],c=[],d=1,f=null,h=3,p=!1,m=!1,g=!1,v=!1,y=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;function w(P){for(var $=n(c);$!==null;){if($.callback===null)r(c);else if($.startTime<=P)r(c),$.sortIndex=$.expirationTime,t(l,$);else break;$=n(c)}}function S(P){if(g=!1,w(P),!m)if(n(l)!==null)m=!0,j||(j=!0,C());else{var $=n(c);$!==null&&k(S,$.startTime-P)}}var j=!1,O=-1,E=5,T=-1;function N(){return v?!0:!(e.unstable_now()-TP&&N());){var F=f.callback;if(typeof F=="function"){f.callback=null,h=f.priorityLevel;var H=F(f.expirationTime<=P);if(P=e.unstable_now(),typeof H=="function"){f.callback=H,w(P),$=!0;break t}f===n(l)&&r(l),w(P)}else r(l);f=n(l)}if(f!==null)$=!0;else{var W=n(c);W!==null&&k(S,W.startTime-P),$=!1}}break e}finally{f=null,h=I,p=!1}$=void 0}}finally{$?C():j=!1}}}var C;if(typeof x=="function")C=function(){x(M)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,D=L.port2;L.port1.onmessage=M,C=function(){D.postMessage(null)}}else C=function(){y(M,0)};function k(P,$){O=y(function(){P(e.unstable_now())},$)}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(P){P.callback=null},e.unstable_forceFrameRate=function(P){0>P||125F?(P.sortIndex=I,t(c,P),n(l)===null&&P===n(c)&&(g?(b(O),O=-1):g=!0,k(S,I-F))):(P.sortIndex=H,t(l,P),m||p||(m=!0,j||(j=!0,C()))),P},e.unstable_shouldYield=N,e.unstable_wrapCallback=function(P){var $=h;return function(){var I=h;h=$;try{return P.apply(this,arguments)}finally{h=I}}}})(rM);nM.exports=rM;var Iz=nM.exports,aM={exports:{}},xn={};/** + * @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 Bz=A;function iM(e){var t="https://react.dev/errors/"+e;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(sM)}catch(e){console.error(e)}}sM(),aM.exports=xn;var Vz=aM.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 Lt=Iz,oM=A,Hz=Vz;function U(e){var t="https://react.dev/errors/"+e;if(1Go||(e.current=r0[Go],r0[Go]=null,Go--)}function Je(e,t){Go++,r0[Go]=e.current,e.current=t}var ia=ha(null),hf=ha(null),Ii=ha(null),Np=ha(null);function Cp(e,t){switch(Je(Ii,t),Je(hf,e),Je(ia,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?H2(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=H2(t),e=RD(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Kt(ia),Je(ia,e)}function Il(){Kt(ia),Kt(hf),Kt(Ii)}function a0(e){e.memoizedState!==null&&Je(Np,e);var t=ia.current,n=RD(t,e.type);t!==n&&(Je(hf,e),Je(ia,n))}function _p(e){hf.current===e&&(Kt(ia),Kt(hf)),Np.current===e&&(Kt(Np),Af._currentValue=qs)}var ov,IA;function gs(e){if(ov===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);ov=t&&t[1]||"",IA=-1)":-1a||l[r]!==c[a]){var d=` +`+l[r].replace(" at new "," at ");return e.displayName&&d.includes("")&&(d=d.replace("",e.displayName)),d}while(1<=r&&0<=a);break}}}finally{lv=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?gs(n):""}function Wz(e,t){switch(e.tag){case 26:case 27:case 5:return gs(e.type);case 16:return gs("Lazy");case 13:return e.child!==t&&t!==null?gs("Suspense Fallback"):gs("Suspense");case 19:return gs("SuspenseList");case 0:case 15:return cv(e.type,!1);case 11:return cv(e.type.render,!1);case 1:return cv(e.type,!0);case 31:return gs("Activity");default:return""}}function BA(e){try{var t="",n=null;do t+=Wz(e,n),n=e,e=e.return;while(e);return t}catch(r){return` +Error generating stack: `+r.message+` +`+r.stack}}var i0=Object.prototype.hasOwnProperty,bS=Lt.unstable_scheduleCallback,uv=Lt.unstable_cancelCallback,Xz=Lt.unstable_shouldYield,Qz=Lt.unstable_requestPaint,Gn=Lt.unstable_now,Zz=Lt.unstable_getCurrentPriorityLevel,pM=Lt.unstable_ImmediatePriority,mM=Lt.unstable_UserBlockingPriority,Pp=Lt.unstable_NormalPriority,Jz=Lt.unstable_LowPriority,yM=Lt.unstable_IdlePriority,eI=Lt.log,tI=Lt.unstable_setDisableYieldValue,Ed=null,Yn=null;function Mi(e){if(typeof eI=="function"&&tI(e),Yn&&typeof Yn.setStrictMode=="function")try{Yn.setStrictMode(Ed,e)}catch{}}var Wn=Math.clz32?Math.clz32:aI,nI=Math.log,rI=Math.LN2;function aI(e){return e>>>=0,e===0?32:31-(nI(e)/rI|0)|0}var fh=256,dh=262144,hh=4194304;function vs(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 Cy(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var a=0,i=e.suspendedLanes,s=e.pingedLanes;e=e.warmLanes;var o=r&134217727;return o!==0?(r=o&~i,r!==0?a=vs(r):(s&=o,s!==0?a=vs(s):n||(n=o&~e,n!==0&&(a=vs(n))))):(o=r&~i,o!==0?a=vs(o):s!==0?a=vs(s):n||(n=r&~e,n!==0&&(a=vs(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 Td(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function iI(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 gM(){var e=hh;return hh<<=1,!(hh&62914560)&&(hh=4194304),e}function fv(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Nd(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function sI(e,t,n,r,a,i){var s=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 o=e.entanglements,l=e.expirationTimes,c=e.hiddenUpdates;for(n=s&~n;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var dI=/[\n"\\]/g;function hr(e){return e.replace(dI,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function l0(e,t,n,r,a,i,s,o){e.name="",s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"?e.type=s:e.removeAttribute("type"),t!=null?s==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+ur(t)):e.value!==""+ur(t)&&(e.value=""+ur(t)):s!=="submit"&&s!=="reset"||e.removeAttribute("value"),t!=null?c0(e,s,ur(t)):n!=null?c0(e,s,ur(n)):r!=null&&e.removeAttribute("value"),a==null&&i!=null&&(e.defaultChecked=!!i),a!=null&&(e.checked=a&&typeof a!="function"&&typeof a!="symbol"),o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"?e.name=""+ur(o):e.removeAttribute("name")}function EM(e,t,n,r,a,i,s,o){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)){o0(e);return}n=n!=null?""+ur(n):"",t=t!=null?""+ur(t):n,o||t===e.value||(e.value=t),e.defaultValue=t}r=r??a,r=typeof r!="function"&&typeof r!="symbol"&&!!r,e.checked=o?e.checked:!!r,e.defaultChecked=!!r,s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"&&(e.name=s),o0(e)}function c0(e,t,n){t==="number"&&Mp(e.ownerDocument)===e||e.defaultValue===""+n||(e.defaultValue=""+n)}function ml(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"),f0=!1;if(Ga)try{var au={};Object.defineProperty(au,"passive",{get:function(){f0=!0}}),window.addEventListener("test",au,au),window.removeEventListener("test",au,au)}catch{f0=!1}var Ri=null,OS=null,np=null;function PM(){if(np)return np;var e,t=OS,n=t.length,r,a="value"in Ri?Ri.value:Ri.textContent,i=a.length;for(e=0;e=zu),QA=" ",ZA=!1;function RM(e,t){switch(e){case"keyup":return BI.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function DM(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Xo=!1;function FI(e,t){switch(e){case"compositionend":return DM(t);case"keypress":return t.which!==32?null:(ZA=!0,QA);case"textInput":return e=t.data,e===QA&&ZA?null:e;default:return null}}function VI(e,t){if(Xo)return e==="compositionend"||!TS&&RM(e,t)?(e=PM(),np=OS=Ri=null,Xo=!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=r2(n)}}function zM(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?zM(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function IM(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Mp(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=Mp(e.document)}return t}function NS(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 QI=Ga&&"documentMode"in document&&11>=document.documentMode,Qo=null,d0=null,Bu=null,h0=!1;function i2(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;h0||Qo==null||Qo!==Mp(r)||(r=Qo,"selectionStart"in r&&NS(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}),Bu&&yf(Bu,r)||(Bu=r,r=Xp(d0,"onSelect"),0>=s,a-=s,Qr=1<<32-Wn(t)+a|n<E?(T=O,O=null):T=O.sibling;var N=h(y,O,x[E],w);if(N===null){O===null&&(O=T);break}e&&O&&N.alternate===null&&t(y,O),b=i(N,b,E),j===null?S=N:j.sibling=N,j=N,O=T}if(E===x.length)return n(y,O),Ce&&Na(y,E),S;if(O===null){for(;EE?(T=O,O=null):T=O.sibling;var M=h(y,O,N.value,w);if(M===null){O===null&&(O=T);break}e&&O&&M.alternate===null&&t(y,O),b=i(M,b,E),j===null?S=M:j.sibling=M,j=M,O=T}if(N.done)return n(y,O),Ce&&Na(y,E),S;if(O===null){for(;!N.done;E++,N=x.next())N=f(y,N.value,w),N!==null&&(b=i(N,b,E),j===null?S=N:j.sibling=N,j=N);return Ce&&Na(y,E),S}for(O=r(O);!N.done;E++,N=x.next())N=p(O,y,E,N.value,w),N!==null&&(e&&N.alternate!==null&&O.delete(N.key===null?E:N.key),b=i(N,b,E),j===null?S=N:j.sibling=N,j=N);return e&&O.forEach(function(C){return t(y,C)}),Ce&&Na(y,E),S}function v(y,b,x,w){if(typeof x=="object"&&x!==null&&x.type===Ko&&x.key===null&&(x=x.props.children),typeof x=="object"&&x!==null){switch(x.$$typeof){case uh:e:{for(var S=x.key;b!==null;){if(b.key===S){if(S=x.type,S===Ko){if(b.tag===7){n(y,b.sibling),w=a(b,x.props.children),w.return=y,y=w;break e}}else if(b.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===yi&&bs(S)===b.type){n(y,b.sibling),w=a(b,x.props),su(w,x),w.return=y,y=w;break e}n(y,b);break}else t(y,b);b=b.sibling}x.type===Ko?(w=Ks(x.props.children,y.mode,w,x.key),w.return=y,y=w):(w=ap(x.type,x.key,x.props,null,y.mode,w),su(w,x),w.return=y,y=w)}return s(y);case Eu:e:{for(S=x.key;b!==null;){if(b.key===S)if(b.tag===4&&b.stateNode.containerInfo===x.containerInfo&&b.stateNode.implementation===x.implementation){n(y,b.sibling),w=a(b,x.children||[]),w.return=y,y=w;break e}else{n(y,b);break}else t(y,b);b=b.sibling}w=xv(x,y.mode,w),w.return=y,y=w}return s(y);case yi:return x=bs(x),v(y,b,x,w)}if(Tu(x))return m(y,b,x,w);if(ru(x)){if(S=ru(x),typeof S!="function")throw Error(U(150));return x=S.call(x),g(y,b,x,w)}if(typeof x.then=="function")return v(y,b,gh(x),w);if(x.$$typeof===Ma)return v(y,b,yh(y,x),w);vh(y,x)}return typeof x=="string"&&x!==""||typeof x=="number"||typeof x=="bigint"?(x=""+x,b!==null&&b.tag===6?(n(y,b.sibling),w=a(b,x),w.return=y,y=w):(n(y,b),w=bv(x,y.mode,w),w.return=y,y=w),s(y)):n(y,b)}return function(y,b,x,w){try{bf=0;var S=v(y,b,x,w);return vl=null,S}catch(O){if(O===Mc||O===ky)throw O;var j=Hn(29,O,null,y.mode);return j.lanes=w,j.return=y,j}finally{}}}var ro=eR(!0),tR=eR(!1),gi=!1;function LS(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function x0(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 Ui(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Fi(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Me&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,t=Dp(e),KM(e,null,n),t}return Dy(e,r,t,n),Dp(e)}function Fu(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,bM(e,n)}}function wv(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 s={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};i===null?a=i=s:i=i.next=s,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 S0=!1;function Vu(){if(S0){var e=gl;if(e!==null)throw e}}function Hu(e,t,n,r){S0=!1;var a=e.updateQueue;gi=!1;var i=a.firstBaseUpdate,s=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var l=o,c=l.next;l.next=null,s===null?i=c:s.next=c,s=l;var d=e.alternate;d!==null&&(d=d.updateQueue,o=d.lastBaseUpdate,o!==s&&(o===null?d.firstBaseUpdate=c:o.next=c,d.lastBaseUpdate=l))}if(i!==null){var f=a.baseState;s=0,d=c=l=null,o=i;do{var h=o.lane&-536870913,p=h!==o.lane;if(p?(Te&h)===h:(r&h)===h){h!==0&&h===Fl&&(S0=!0),d!==null&&(d=d.next={lane:0,tag:o.tag,payload:o.payload,callback:null,next:null});e:{var m=e,g=o;h=t;var v=n;switch(g.tag){case 1:if(m=g.payload,typeof m=="function"){f=m.call(v,f,h);break e}f=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,h=typeof m=="function"?m.call(v,f,h):m,h==null)break e;f=st({},f,h);break e;case 2:gi=!0}}h=o.callback,h!==null&&(e.flags|=64,p&&(e.flags|=8192),p=a.callbacks,p===null?a.callbacks=[h]:p.push(h))}else p={lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},d===null?(c=d=p,l=f):d=d.next=p,s|=h;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;p=o,o=p.next,p.next=null,a.lastBaseUpdate=p,a.shared.pending=null}}while(!0);d===null&&(l=f),a.baseState=l,a.firstBaseUpdate=c,a.lastBaseUpdate=d,i===null&&(a.shared.lanes=0),ts|=s,e.lanes=s,e.memoizedState=f}}function nR(e,t){if(typeof e!="function")throw Error(U(191,e));e.call(t)}function rR(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ei?i:8;var s=he.T,o={};he.T=o,XS(e,!1,t,n);try{var l=a(),c=he.S;if(c!==null&&c(o,l),l!==null&&typeof l=="object"&&typeof l.then=="function"){var d=s8(l,r);qu(e,t,d,Xn(e))}else qu(e,t,r,Xn(e))}catch(f){qu(e,t,{then:function(){},status:"rejected",reason:f},Xn())}finally{De.p=i,s!==null&&o.types!==null&&(s.types=o.types),he.T=s}}function d8(){}function E0(e,t,n,r){if(e.tag!==5)throw Error(U(476));var a=NR(e).queue;TR(e,a,t,qs,n===null?d8:function(){return CR(e),n(r)})}function NR(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:qs,baseState:qs,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wa,lastRenderedState:qs},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wa,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function CR(e){var t=NR(e);t.next===null&&(t=e.alternate.memoizedState),qu(e,t.next.queue,{},Xn())}function WS(){return tn(Af)}function _R(){return jt().memoizedState}function PR(){return jt().memoizedState}function h8(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=Xn();e=Ui(n);var r=Fi(t,e,n);r!==null&&(_n(r,t,n),Fu(r,t,n)),t={cache:DS()},e.payload=t;return}t=t.return}}function p8(e,t,n){var r=Xn();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Iy(e)?RR(t,n):(n=_S(e,t,n,r),n!==null&&(_n(n,e,r),DR(n,t,r)))}function MR(e,t,n){var r=Xn();qu(e,t,n,r)}function qu(e,t,n,r){var a={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Iy(e))RR(t,a);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,o=i(s,n);if(a.hasEagerState=!0,a.eagerState=o,Jn(o,s))return Dy(e,t,a,0),We===null&&Ry(),!1}catch{}finally{}if(n=_S(e,t,a,r),n!==null)return _n(n,e,r),DR(n,t,r),!0}return!1}function XS(e,t,n,r){if(r={lane:2,revertLane:iw(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Iy(e)){if(t)throw Error(U(479))}else t=_S(e,n,r,2),t!==null&&_n(t,e,2)}function Iy(e){var t=e.alternate;return e===Se||t!==null&&t===Se}function RR(e,t){bl=Bp=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function DR(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,bM(e,n)}}var Sf={readContext:tn,use:Ly,useCallback:mt,useContext:mt,useEffect:mt,useImperativeHandle:mt,useLayoutEffect:mt,useInsertionEffect:mt,useMemo:mt,useReducer:mt,useRef:mt,useState:mt,useDebugValue:mt,useDeferredValue:mt,useTransition:mt,useSyncExternalStore:mt,useId:mt,useHostTransitionStatus:mt,useFormState:mt,useActionState:mt,useOptimistic:mt,useMemoCache:mt,useCacheRefresh:mt};Sf.useEffectEvent=mt;var kR={readContext:tn,use:Ly,useCallback:function(e,t){return hn().memoizedState=[e,t===void 0?null:t],e},useContext:tn,useEffect:x2,useImperativeHandle:function(e,t,n){n=n!=null?n.concat([e]):null,op(4194308,4,wR.bind(null,t,e),n)},useLayoutEffect:function(e,t){return op(4194308,4,e,t)},useInsertionEffect:function(e,t){op(4,2,e,t)},useMemo:function(e,t){var n=hn();t=t===void 0?null:t;var r=e();if(ao){Mi(!0);try{e()}finally{Mi(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=hn();if(n!==void 0){var a=n(t);if(ao){Mi(!0);try{n(t)}finally{Mi(!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=p8.bind(null,Se,e),[r.memoizedState,e]},useRef:function(e){var t=hn();return e={current:e},t.memoizedState=e},useState:function(e){e=A0(e);var t=e.queue,n=MR.bind(null,Se,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:GS,useDeferredValue:function(e,t){var n=hn();return YS(n,e,t)},useTransition:function(){var e=A0(!1);return e=TR.bind(null,Se,e.queue,!0,!1),hn().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=Se,a=hn();if(Ce){if(n===void 0)throw Error(U(407));n=n()}else{if(n=t(),We===null)throw Error(U(349));Te&127||lR(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,x2(uR.bind(null,r,i,e),[e]),r.flags|=2048,Hl(9,{destroy:void 0},cR.bind(null,r,i,n,t),null),n},useId:function(){var e=hn(),t=We.identifierPrefix;if(Ce){var n=Zr,r=Qr;n=(r&~(1<<32-Wn(r)-1)).toString(32)+n,t="_"+t+"R_"+n,n=Up++,0<\/script>",i=i.removeChild(i.firstChild);break;case"select":i=typeof r.is=="string"?s.createElement("select",{is:r.is}):s.createElement("select"),r.multiple?i.multiple=!0:r.size&&(i.size=r.size);break;default:i=typeof r.is=="string"?s.createElement(a,{is:r.is}):s.createElement(a)}}i[Zt]=t,i[Mn]=r;e:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)i.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break e;for(;s.sibling===null;){if(s.return===null||s.return===t)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=i;e:switch(nn(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&&xa(t)}}return tt(t),_v(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&xa(t);else{if(typeof r!="string"&&t.stateNode===null)throw Error(U(166));if(e=Ii.current,Ro(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Jt,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[Zt]=t,e=!!(e.nodeValue===n||r!==null&&r.suppressHydrationWarning===!0||MD(e.nodeValue,n)),e||Ji(t,!0)}else e=Qp(e).createTextNode(r),e[Zt]=t,t.stateNode=e}return tt(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Ro(t),n!==null){if(e===null){if(!r)throw Error(U(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(U(557));e[Zt]=t}else to(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;tt(t),e=!1}else n=Sv(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Vn(t),t):(Vn(t),null);if(t.flags&128)throw Error(U(558))}return tt(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Ro(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(U(318));if(a=t.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(U(317));a[Zt]=t}else to(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;tt(t),a=!1}else a=Sv(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(Vn(t),t):(Vn(t),null)}return Vn(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),bh(t,t.updateQueue),tt(t),null);case 4:return Il(),e===null&&sw(t.stateNode.containerInfo),tt(t),null;case 10:return Ba(t.type),tt(t),null;case 19:if(Kt(St),r=t.memoizedState,r===null)return tt(t),null;if(a=(t.flags&128)!==0,i=r.rendering,i===null)if(a)ou(r,!1);else{if(bt!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(i=Ip(e),i!==null){for(t.flags|=128,ou(r,!1),e=i.updateQueue,t.updateQueue=e,bh(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)GM(n,e),n=n.sibling;return Je(St,St.current&1|2),Ce&&Na(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Gn()>qp&&(t.flags|=128,a=!0,ou(r,!1),t.lanes=4194304)}else{if(!a)if(e=Ip(i),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,bh(t,e),ou(r,!0),r.tail===null&&r.tailMode==="hidden"&&!i.alternate&&!Ce)return tt(t),null}else 2*Gn()-r.renderingStartTime>qp&&n!==536870912&&(t.flags|=128,a=!0,ou(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=Gn(),e.sibling=null,n=St.current,Je(St,a?n&1|2:n&1),Ce&&Na(t,r.treeForkCount),e):(tt(t),null);case 22:case 23:return Vn(t),zS(),r=t.memoizedState!==null,e!==null?e.memoizedState!==null!==r&&(t.flags|=8192):r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(tt(t),t.subtreeFlags&6&&(t.flags|=8192)):tt(t),n=t.updateQueue,n!==null&&bh(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&&Kt(Gs),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ba(Nt),tt(t),null;case 25:return null;case 30:return null}throw Error(U(156,t.tag))}function b8(e,t){switch(RS(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ba(Nt),Il(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return _p(t),null;case 31:if(t.memoizedState!==null){if(Vn(t),t.alternate===null)throw Error(U(340));to()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Vn(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(U(340));to()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Kt(St),null;case 4:return Il(),null;case 10:return Ba(t.type),null;case 22:case 23:return Vn(t),zS(),e!==null&&Kt(Gs),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ba(Nt),null;case 25:return null;default:return null}}function GR(e,t){switch(RS(t),t.tag){case 3:Ba(Nt),Il();break;case 26:case 27:case 5:_p(t);break;case 4:Il();break;case 31:t.memoizedState!==null&&Vn(t);break;case 13:Vn(t);break;case 19:Kt(St);break;case 10:Ba(t.type);break;case 22:case 23:Vn(t),zS(),e!==null&&Kt(Gs);break;case 24:Ba(Nt)}}function Rd(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,s=n.inst;r=i(),s.destroy=r}n=n.next}while(n!==a)}}catch(o){Ue(t,t.return,o)}}function es(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 s=r.inst,o=s.destroy;if(o!==void 0){s.destroy=void 0,a=t;var l=n,c=o;try{c()}catch(d){Ue(a,l,d)}}}r=r.next}while(r!==i)}}catch(d){Ue(t,t.return,d)}}function YR(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{rR(t,n)}catch(r){Ue(e,e.return,r)}}}function WR(e,t,n){n.props=io(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(r){Ue(e,t,r)}}function Ku(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){Ue(e,t,a)}}function Jr(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r=="function")try{r()}catch(a){Ue(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){Ue(e,t,a)}else n.current=null}function XR(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){Ue(e,e.return,a)}}function Pv(e,t,n){try{var r=e.stateNode;U8(r,e.type,n,t),r[Mn]=t}catch(a){Ue(e,e.return,a)}}function QR(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&as(e.type)||e.tag===4}function Mv(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||QR(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&&as(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 P0(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=Ra));else if(r!==4&&(r===27&&as(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(P0(e,t,n),e=e.sibling;e!==null;)P0(e,t,n),e=e.sibling}function Hp(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&&as(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Hp(e,t,n),e=e.sibling;e!==null;)Hp(e,t,n),e=e.sibling}function ZR(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,a=t.attributes;a.length;)t.removeAttributeNode(a[0]);nn(t,r,n),t[Zt]=e,t[Mn]=n}catch(i){Ue(e,e.return,i)}}var Pa=!1,Tt=!1,Rv=!1,R2=typeof WeakSet=="function"?WeakSet:Set,Vt=null;function x8(e,t){if(e=e.containerInfo,z0=tm,e=IM(e),NS(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 s=0,o=-1,l=-1,c=0,d=0,f=e,h=null;t:for(;;){for(var p;f!==n||a!==0&&f.nodeType!==3||(o=s+a),f!==i||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(p=f.firstChild)!==null;)h=f,f=p;for(;;){if(f===e)break t;if(h===n&&++c===a&&(o=s),h===i&&++d===r&&(l=s),(p=f.nextSibling)!==null)break;f=h,h=f.parentNode}f=p}n=o===-1||l===-1?null:{start:o,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(I0={focusedElem:e,selectionRange:n},tm=!1,Vt=t;Vt!==null;)if(t=Vt,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Vt=e;else for(;Vt!==null;){switch(t=Vt,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"))),nn(i,r,n),i[Zt]=e,Ht(i),r=i;break e;case"link":var s=J2("link","href",a).get(r+(n.href||""));if(s){for(var o=0;ov&&(s=v,v=g,g=s);var y=a2(o,g),b=a2(o,v);if(y&&b&&(p.rangeCount!==1||p.anchorNode!==y.node||p.anchorOffset!==y.offset||p.focusNode!==b.node||p.focusOffset!==b.offset)){var x=f.createRange();x.setStart(y.node,y.offset),p.removeAllRanges(),g>v?(p.addRange(x),p.extend(b.node,b.offset)):(x.setEnd(b.node,b.offset),p.addRange(x))}}}}for(f=[],p=o;p=p.parentNode;)p.nodeType===1&&f.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;on?32:n,he.T=null,n=D0,D0=null;var i=Hi,s=Ua;if(kt=0,Kl=Hi=null,Ua=0,Me&6)throw Error(U(331));var o=Me;if(Me|=4,cD(i.current),sD(i,i.current,s,n),Me=o,Dd(0,!1),Yn&&typeof Yn.onPostCommitFiberRoot=="function")try{Yn.onPostCommitFiberRoot(Ed,i)}catch{}return!0}finally{De.p=a,he.T=r,AD(e,t)}}function L2(e,t,n){t=pr(n,t),t=N0(e.stateNode,t,2),e=Fi(e,t,2),e!==null&&(Nd(e,2),pa(e))}function Ue(e,t,n){if(e.tag===3)L2(e,e,n);else for(;t!==null;){if(t.tag===3){L2(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(Vi===null||!Vi.has(r))){e=pr(n,e),n=BR(2),r=Fi(t,n,2),r!==null&&(UR(n,r,t,e),Nd(r,2),pa(r));break}}t=t.return}}function kv(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new j8;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)||(nw=!0,a.add(n),e=N8.bind(null,e,t,n),t.then(e,e))}function N8(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,We===e&&(Te&n)===n&&(bt===4||bt===3&&(Te&62914560)===Te&&300>Gn()-By?!(Me&2)&&Gl(e,0):rw|=n,ql===Te&&(ql=0)),pa(e)}function ED(e,t){t===0&&(t=gM()),e=So(e,t),e!==null&&(Nd(e,t),pa(e))}function C8(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ED(e,n)}function _8(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(U(314))}r!==null&&r.delete(t),ED(e,n)}function P8(e,t){return bS(e,t)}var Yp=null,qo=null,$0=!1,Wp=!1,$v=!1,$i=0;function pa(e){e!==qo&&e.next===null&&(qo===null?Yp=qo=e:qo=qo.next=e),Wp=!0,$0||($0=!0,R8())}function Dd(e,t){if(!$v&&Wp){$v=!0;do for(var n=!1,r=Yp;r!==null;){if(e!==0){var a=r.pendingLanes;if(a===0)var i=0;else{var s=r.suspendedLanes,o=r.pingedLanes;i=(1<<31-Wn(42|e)+1)-1,i&=a&~(s&~o),i=i&201326741?i&201326741|1:i?i|2:0}i!==0&&(n=!0,z2(r,i))}else i=Te,i=Cy(r,r===We?i:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(i&3)||Td(r,i)||(n=!0,z2(r,i));r=r.next}while(n);$v=!1}}function M8(){TD()}function TD(){Wp=$0=!1;var e=0;$i!==0&&V8()&&(e=$i);for(var t=Gn(),n=null,r=Yp;r!==null;){var a=r.next,i=ND(r,t);i===0?(r.next=null,n===null?Yp=a:n.next=a,a===null&&(qo=n)):(n=r,(e!==0||i&3)&&(Wp=!0)),r=a}kt!==0&&kt!==5||Dd(e),$i!==0&&($i=0)}function ND(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,a=e.expirationTimes,i=e.pendingLanes&-62914561;0o)break;var d=l.transferSize,f=l.initiatorType;d&&V2(f)&&(l=l.responseEnd,s+=d*(l"u"?null:document;function LD(e,t,n){var r=Dc;if(r&&typeof t=="string"&&t){var a=hr(t);a='link[rel="'+e+'"][href="'+a+'"]',typeof n=="string"&&(a+='[crossorigin="'+n+'"]'),X2.has(a)||(X2.add(a),e={rel:e,crossOrigin:n,href:t},r.querySelector(a)===null&&(t=r.createElement("link"),nn(t,"link",e),Ht(t),r.head.appendChild(t)))}}function Z8(e){ri.D(e),LD("dns-prefetch",e,null)}function J8(e,t){ri.C(e,t),LD("preconnect",e,t)}function eB(e,t,n){ri.L(e,t,n);var r=Dc;if(r&&e&&t){var a='link[rel="preload"][as="'+hr(t)+'"]';t==="image"&&n&&n.imageSrcSet?(a+='[imagesrcset="'+hr(n.imageSrcSet)+'"]',typeof n.imageSizes=="string"&&(a+='[imagesizes="'+hr(n.imageSizes)+'"]')):a+='[href="'+hr(e)+'"]';var i=a;switch(t){case"style":i=Yl(e);break;case"script":i=kc(e)}xr.has(i)||(e=st({rel:"preload",href:t==="image"&&n&&n.imageSrcSet?void 0:e,as:t},n),xr.set(i,e),r.querySelector(a)!==null||t==="style"&&r.querySelector(kd(i))||t==="script"&&r.querySelector($d(i))||(t=r.createElement("link"),nn(t,"link",e),Ht(t),r.head.appendChild(t)))}}function tB(e,t){ri.m(e,t);var n=Dc;if(n&&e){var r=t&&typeof t.as=="string"?t.as:"script",a='link[rel="modulepreload"][as="'+hr(r)+'"][href="'+hr(e)+'"]',i=a;switch(r){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=kc(e)}if(!xr.has(i)&&(e=st({rel:"modulepreload",href:e},t),xr.set(i,e),n.querySelector(a)===null)){switch(r){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(n.querySelector($d(i)))return}r=n.createElement("link"),nn(r,"link",e),Ht(r),n.head.appendChild(r)}}}function nB(e,t,n){ri.S(e,t,n);var r=Dc;if(r&&e){var a=pl(r).hoistableStyles,i=Yl(e);t=t||"default";var s=a.get(i);if(!s){var o={loading:0,preload:null};if(s=r.querySelector(kd(i)))o.loading=5;else{e=st({rel:"stylesheet",href:e,"data-precedence":t},n),(n=xr.get(i))&&ow(e,n);var l=s=r.createElement("link");Ht(l),nn(l,"link",e),l._p=new Promise(function(c,d){l.onload=c,l.onerror=d}),l.addEventListener("load",function(){o.loading|=1}),l.addEventListener("error",function(){o.loading|=2}),o.loading|=4,fp(s,t,r)}s={type:"stylesheet",instance:s,count:1,state:o},a.set(i,s)}}}function rB(e,t){ri.X(e,t);var n=Dc;if(n&&e){var r=pl(n).hoistableScripts,a=kc(e),i=r.get(a);i||(i=n.querySelector($d(a)),i||(e=st({src:e,async:!0},t),(t=xr.get(a))&&lw(e,t),i=n.createElement("script"),Ht(i),nn(i,"link",e),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},r.set(a,i))}}function aB(e,t){ri.M(e,t);var n=Dc;if(n&&e){var r=pl(n).hoistableScripts,a=kc(e),i=r.get(a);i||(i=n.querySelector($d(a)),i||(e=st({src:e,async:!0,type:"module"},t),(t=xr.get(a))&&lw(e,t),i=n.createElement("script"),Ht(i),nn(i,"link",e),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},r.set(a,i))}}function Q2(e,t,n,r){var a=(a=Ii.current)?Zp(a):null;if(!a)throw Error(U(446));switch(e){case"meta":case"title":return null;case"style":return typeof n.precedence=="string"&&typeof n.href=="string"?(t=Yl(n.href),n=pl(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=Yl(n.href);var i=pl(a).hoistableStyles,s=i.get(e);if(s||(a=a.ownerDocument||a,s={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(e,s),(i=a.querySelector(kd(e)))&&!i._p&&(s.instance=i,s.state.loading=5),xr.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},xr.set(e,n),i||iB(a,e,n,s.state))),t&&r===null)throw Error(U(528,""));return s}if(t&&r!==null)throw Error(U(529,""));return null;case"script":return t=n.async,n=n.src,typeof n=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=kc(n),n=pl(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(U(444,e))}}function Yl(e){return'href="'+hr(e)+'"'}function kd(e){return'link[rel="stylesheet"]['+e+"]"}function zD(e){return st({},e,{"data-precedence":e.precedence,precedence:null})}function iB(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}),nn(t,"link",n),Ht(t),e.head.appendChild(t))}function kc(e){return'[src="'+hr(e)+'"]'}function $d(e){return"script[async]"+e}function Z2(e,t,n){if(t.count++,t.instance===null)switch(t.type){case"style":var r=e.querySelector('style[data-href~="'+hr(n.href)+'"]');if(r)return t.instance=r,Ht(r),r;var a=st({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement("style"),Ht(r),nn(r,"style",a),fp(r,n.precedence,e),t.instance=r;case"stylesheet":a=Yl(n.href);var i=e.querySelector(kd(a));if(i)return t.state.loading|=4,t.instance=i,Ht(i),i;r=zD(n),(a=xr.get(a))&&ow(r,a),i=(e.ownerDocument||e).createElement("link"),Ht(i);var s=i;return s._p=new Promise(function(o,l){s.onload=o,s.onerror=l}),nn(i,"link",r),t.state.loading|=4,fp(i,n.precedence,e),t.instance=i;case"script":return i=kc(n.src),(a=e.querySelector($d(i)))?(t.instance=a,Ht(a),a):(r=n,(a=xr.get(i))&&(r=st({},n),lw(r,a)),e=e.ownerDocument||e,a=e.createElement("script"),Ht(a),nn(a,"link",r),e.head.appendChild(a),t.instance=a);case"void":return null;default:throw Error(U(443,t.type))}else t.type==="stylesheet"&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,fp(r,n.precedence,e));return t.instance}function fp(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,s=0;s title"):null)}function sB(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 ID(e){return!(e.type==="stylesheet"&&!(e.state.loading&3))}function oB(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=Yl(r.href),i=t.querySelector(kd(a));if(i){t=i._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Jp.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=i,Ht(i);return}i=t.ownerDocument||t,r=zD(r),(a=xr.get(a))&&ow(r,a),i=i.createElement("link"),Ht(i);var s=i;s._p=new Promise(function(o,l){s.onload=o,s.onerror=l}),nn(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=Jp.bind(e),t.addEventListener("load",n),t.addEventListener("error",n))}}var Fv=0;function lB(e,t){return e.stylesheets&&e.count===0&&hp(e,e.stylesheets),0Fv?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(a)}}:null}function Jp(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)hp(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var em=null;function hp(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,em=new Map,t.forEach(cB,e),em=null,Jp.call(e))}function cB(e,t){if(!(t.state.loading&4)){var n=em.get(e);if(n)var r=n.get(null);else{n=new Map,em.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(GD)}catch(e){console.error(e)}}GD(),tM.exports=Ty;var gB=tM.exports;const vB=Ie(gB);var Ld=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},$s,Ai,El,$P,bB=($P=class extends Ld{constructor(){super();ce(this,$s);ce(this,Ai);ce(this,El);ee(this,El,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){R(this,Ai)||this.setEventListener(R(this,El))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,Ai))==null||t.call(this),ee(this,Ai,void 0))}setEventListener(t){var n;ee(this,El,t),(n=R(this,Ai))==null||n.call(this),ee(this,Ai,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){R(this,$s)!==t&&(ee(this,$s,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof R(this,$s)=="boolean"?R(this,$s):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},$s=new WeakMap,Ai=new WeakMap,El=new WeakMap,$P),hw=new bB,xB={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Oi,fS,LP,SB=(LP=class{constructor(){ce(this,Oi,xB);ce(this,fS,!1)}setTimeoutProvider(e){ee(this,Oi,e)}setTimeout(e,t){return R(this,Oi).setTimeout(e,t)}clearTimeout(e){R(this,Oi).clearTimeout(e)}setInterval(e,t){return R(this,Oi).setInterval(e,t)}clearInterval(e){R(this,Oi).clearInterval(e)}},Oi=new WeakMap,fS=new WeakMap,LP),Ts=new SB;function wB(e){setTimeout(e,0)}var jB=typeof window>"u"||"Deno"in globalThis;function Nn(){}function AB(e,t){return typeof e=="function"?e(t):e}function G0(e){return typeof e=="number"&&e>=0&&e!==1/0}function YD(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Yi(e,t){return typeof e=="function"?e(t):e}function Un(e,t){return typeof e=="function"?e(t):e}function oO(e,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:s,stale:o}=e;if(s){if(r){if(t.queryHash!==pw(s,t.options))return!1}else if(!Nf(t.queryKey,s))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function lO(e,t){const{exact:n,status:r,predicate:a,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Tf(t.options.mutationKey)!==Tf(i))return!1}else if(!Nf(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function pw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Tf)(e)}function Tf(e){return JSON.stringify(e,(t,n)=>W0(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function Nf(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Nf(e[n],t[n])):!1}var OB=Object.prototype.hasOwnProperty;function WD(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cO(e)&&cO(t);if(!r&&!(W0(e)&&W0(t)))return t;const i=(r?e:Object.keys(e)).length,s=r?t:Object.keys(t),o=s.length,l=r?new Array(o):{};let c=0;for(let d=0;d{Ts.setTimeout(t,e)})}function X0(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?WD(e,t):t}function TB(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function NB(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var mw=Symbol();function XD(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===mw?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function QD(e,t){return typeof e=="function"?e(...t):!!e}function CB(e,t,n){let r=!1,a;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(a??(a=t()),r||(r=!0,a.aborted?n():a.addEventListener("abort",n,{once:!0})),a)}),e}var Cf=(()=>{let e=()=>jB;return{isServer(){return e()},setIsServer(t){e=t}}})();function Q0(){let e,t;const n=new Promise((a,i)=>{e=a,t=i});n.status="pending",n.catch(()=>{});function r(a){Object.assign(n,a),delete n.resolve,delete n.reject}return n.resolve=a=>{r({status:"fulfilled",value:a}),e(a)},n.reject=a=>{r({status:"rejected",reason:a}),t(a)},n}var _B=wB;function PB(){let e=[],t=0,n=o=>{o()},r=o=>{o()},a=_B;const i=o=>{t?e.push(o):a(()=>{n(o)})},s=()=>{const o=e;e=[],o.length&&a(()=>{r(()=>{o.forEach(l=>{n(l)})})})};return{batch:o=>{let l;t++;try{l=o()}finally{t--,t||s()}return l},batchCalls:o=>(...l)=>{i(()=>{o(...l)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{a=o}}}var Qt=PB(),Tl,Ei,Nl,zP,MB=(zP=class extends Ld{constructor(){super();ce(this,Tl,!0);ce(this,Ei);ce(this,Nl);ee(this,Nl,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){R(this,Ei)||this.setEventListener(R(this,Nl))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,Ei))==null||t.call(this),ee(this,Ei,void 0))}setEventListener(t){var n;ee(this,Nl,t),(n=R(this,Ei))==null||n.call(this),ee(this,Ei,t(this.setOnline.bind(this)))}setOnline(t){R(this,Tl)!==t&&(ee(this,Tl,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return R(this,Tl)}},Tl=new WeakMap,Ei=new WeakMap,Nl=new WeakMap,zP),rm=new MB;function RB(e){return Math.min(1e3*2**e,3e4)}function ZD(e){return(e??"online")==="online"?rm.isOnline():!0}var Z0=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function JD(e){let t=!1,n=0,r;const a=Q0(),i=()=>a.status!=="pending",s=g=>{var v;if(!i()){const y=new Z0(g);h(y),(v=e.onCancel)==null||v.call(e,y)}},o=()=>{t=!0},l=()=>{t=!1},c=()=>hw.isFocused()&&(e.networkMode==="always"||rm.isOnline())&&e.canRun(),d=()=>ZD(e.networkMode)&&e.canRun(),f=g=>{i()||(r==null||r(),a.resolve(g))},h=g=>{i()||(r==null||r(),a.reject(g))},p=()=>new Promise(g=>{var v;r=y=>{(i()||c())&&g(y)},(v=e.onPause)==null||v.call(e)}).then(()=>{var g;r=void 0,i()||(g=e.onContinue)==null||g.call(e)}),m=()=>{if(i())return;let g;const v=n===0?e.initialPromise:void 0;try{g=v??e.fn()}catch(y){g=Promise.reject(y)}Promise.resolve(g).then(f).catch(y=>{var j;if(i())return;const b=e.retry??(Cf.isServer()?0:3),x=e.retryDelay??RB,w=typeof x=="function"?x(n,y):x,S=b===!0||typeof b=="number"&&nc()?void 0:p()).then(()=>{t?h(y):m()})})};return{promise:a,status:()=>a.status,cancel:s,continue:()=>(r==null||r(),a),cancelRetry:o,continueRetry:l,canStart:d,start:()=>(d()?m():p().then(m),a)}}var Ls,IP,ek=(IP=class{constructor(){ce(this,Ls)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),G0(this.gcTime)&&ee(this,Ls,Ts.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Cf.isServer()?1/0:5*60*1e3))}clearGcTimeout(){R(this,Ls)!==void 0&&(Ts.clearTimeout(R(this,Ls)),ee(this,Ls,void 0))}},Ls=new WeakMap,IP);function DB(e){return{onFetch:(t,n)=>{var d,f,h,p,m;const r=t.options,a=(h=(f=(d=t.fetchOptions)==null?void 0:d.meta)==null?void 0:f.fetchMore)==null?void 0:h.direction,i=((p=t.state.data)==null?void 0:p.pages)||[],s=((m=t.state.data)==null?void 0:m.pageParams)||[];let o={pages:[],pageParams:[]},l=0;const c=async()=>{let g=!1;const v=x=>{CB(x,()=>t.signal,()=>g=!0)},y=XD(t.options,t.fetchOptions),b=async(x,w,S)=>{if(g)return Promise.reject(t.signal.reason);if(w==null&&x.pages.length)return Promise.resolve(x);const O=(()=>{const M={client:t.client,queryKey:t.queryKey,pageParam:w,direction:S?"backward":"forward",meta:t.options.meta};return v(M),M})(),E=await y(O),{maxPages:T}=t.options,N=S?NB:TB;return{pages:N(x.pages,E,T),pageParams:N(x.pageParams,w,T)}};if(a&&i.length){const x=a==="backward",w=x?kB:fO,S={pages:i,pageParams:s},j=w(r,S);o=await b(S,j,x)}else{const x=e??i.length;do{const w=l===0?s[0]??r.initialPageParam:fO(r,o);if(l>0&&w==null)break;o=await b(o,w),l++}while(l{var g,v;return(v=(g=t.options).persister)==null?void 0:v.call(g,c,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=c}}}function fO(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function kB(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var Cl,zs,_l,lr,Is,Bt,xd,Bs,Bn,tk,Ea,BP,$B=(BP=class extends ek{constructor(t){super();ce(this,Bn);ce(this,Cl);ce(this,zs);ce(this,_l);ce(this,lr);ce(this,Is);ce(this,Bt);ce(this,xd);ce(this,Bs);ee(this,Bs,!1),ee(this,xd,t.defaultOptions),this.setOptions(t.options),this.observers=[],ee(this,Is,t.client),ee(this,lr,R(this,Is).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ee(this,zs,hO(this.options)),this.state=t.state??R(this,zs),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return R(this,Cl)}get promise(){var t;return(t=R(this,Bt))==null?void 0:t.promise}setOptions(t){if(this.options={...R(this,xd),...t},t!=null&&t._type&&ee(this,Cl,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=hO(this.options);n.data!==void 0&&(this.setState(dO(n.data,n.dataUpdatedAt)),ee(this,zs,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&R(this,lr).remove(this)}setData(t,n){const r=X0(this.state.data,t,this.options);return Oe(this,Bn,Ea).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){Oe(this,Bn,Ea).call(this,{type:"setState",state:t})}cancel(t){var r,a;const n=(r=R(this,Bt))==null?void 0:r.promise;return(a=R(this,Bt))==null||a.cancel(t),n?n.then(Nn).catch(Nn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return R(this,zs)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Un(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===mw||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Yi(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!YD(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,Bt))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,Bt))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),R(this,lr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(R(this,Bt)&&(R(this,Bs)||Oe(this,Bn,tk).call(this)?R(this,Bt).cancel({revert:!0}):R(this,Bt).cancelRetry()),this.scheduleGc()),R(this,lr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Oe(this,Bn,Ea).call(this,{type:"invalidate"})}async fetch(t,n){var c,d,f,h,p,m,g,v,y,b,x;if(this.state.fetchStatus!=="idle"&&((c=R(this,Bt))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(R(this,Bt))return R(this,Bt).continueRetry(),R(this,Bt).promise}if(t&&this.setOptions(t),!this.options.queryFn){const w=this.observers.find(S=>S.options.queryFn);w&&this.setOptions(w.options)}const r=new AbortController,a=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(ee(this,Bs,!0),r.signal)})},i=()=>{const w=XD(this.options,n),j=(()=>{const O={client:R(this,Is),queryKey:this.queryKey,meta:this.meta};return a(O),O})();return ee(this,Bs,!1),this.options.persister?this.options.persister(w,j,this):w(j)},o=(()=>{const w={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:R(this,Is),state:this.state,fetchFn:i};return a(w),w})(),l=R(this,Cl)==="infinite"?DB(this.options.pages):this.options.behavior;l==null||l.onFetch(o,this),ee(this,_l,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=o.fetchOptions)==null?void 0:d.meta))&&Oe(this,Bn,Ea).call(this,{type:"fetch",meta:(f=o.fetchOptions)==null?void 0:f.meta}),ee(this,Bt,JD({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:w=>{w instanceof Z0&&w.revert&&this.setState({...R(this,_l),fetchStatus:"idle"}),r.abort()},onFail:(w,S)=>{Oe(this,Bn,Ea).call(this,{type:"failed",failureCount:w,error:S})},onPause:()=>{Oe(this,Bn,Ea).call(this,{type:"pause"})},onContinue:()=>{Oe(this,Bn,Ea).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const w=await R(this,Bt).start();if(w===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(w),(p=(h=R(this,lr).config).onSuccess)==null||p.call(h,w,this),(g=(m=R(this,lr).config).onSettled)==null||g.call(m,w,this.state.error,this),w}catch(w){if(w instanceof Z0){if(w.silent)return R(this,Bt).promise;if(w.revert){if(this.state.data===void 0)throw w;return this.state.data}}throw Oe(this,Bn,Ea).call(this,{type:"error",error:w}),(y=(v=R(this,lr).config).onError)==null||y.call(v,w,this),(x=(b=R(this,lr).config).onSettled)==null||x.call(b,this.state.data,w,this),w}finally{this.scheduleGc()}}},Cl=new WeakMap,zs=new WeakMap,_l=new WeakMap,lr=new WeakMap,Is=new WeakMap,Bt=new WeakMap,xd=new WeakMap,Bs=new WeakMap,Bn=new WeakSet,tk=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ea=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...nk(r.data,this.options),fetchMeta:t.meta??null};case"success":const a={...r,...dO(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return ee(this,_l,t.manual?a:void 0),a;case"error":const i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Qt.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),R(this,lr).notify({query:this,type:"updated",action:t})})},BP);function nk(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ZD(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function dO(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function hO(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var On,Ne,Sd,dn,Us,Pl,Ca,Ti,wd,Ml,Rl,Fs,Vs,Ni,Dl,ze,Pu,J0,ex,tx,nx,rx,ax,ix,rk,UP,LB=(UP=class extends Ld{constructor(t,n){super();ce(this,ze);ce(this,On);ce(this,Ne);ce(this,Sd);ce(this,dn);ce(this,Us);ce(this,Pl);ce(this,Ca);ce(this,Ti);ce(this,wd);ce(this,Ml);ce(this,Rl);ce(this,Fs);ce(this,Vs);ce(this,Ni);ce(this,Dl,new Set);this.options=n,ee(this,On,t),ee(this,Ti,null),ee(this,Ca,Q0()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(R(this,Ne).addObserver(this),pO(R(this,Ne),this.options)?Oe(this,ze,Pu).call(this):this.updateResult(),Oe(this,ze,nx).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return sx(R(this,Ne),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return sx(R(this,Ne),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Oe(this,ze,rx).call(this),Oe(this,ze,ax).call(this),R(this,Ne).removeObserver(this)}setOptions(t){const n=this.options,r=R(this,Ne);if(this.options=R(this,On).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Un(this.options.enabled,R(this,Ne))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Oe(this,ze,ix).call(this),R(this,Ne).setOptions(this.options),n._defaulted&&!Y0(this.options,n)&&R(this,On).getQueryCache().notify({type:"observerOptionsUpdated",query:R(this,Ne),observer:this});const a=this.hasListeners();a&&mO(R(this,Ne),r,this.options,n)&&Oe(this,ze,Pu).call(this),this.updateResult(),a&&(R(this,Ne)!==r||Un(this.options.enabled,R(this,Ne))!==Un(n.enabled,R(this,Ne))||Yi(this.options.staleTime,R(this,Ne))!==Yi(n.staleTime,R(this,Ne)))&&Oe(this,ze,J0).call(this);const i=Oe(this,ze,ex).call(this);a&&(R(this,Ne)!==r||Un(this.options.enabled,R(this,Ne))!==Un(n.enabled,R(this,Ne))||i!==R(this,Ni))&&Oe(this,ze,tx).call(this,i)}getOptimisticResult(t){const n=R(this,On).getQueryCache().build(R(this,On),t),r=this.createResult(n,t);return IB(this,r)&&(ee(this,dn,r),ee(this,Pl,this.options),ee(this,Us,R(this,Ne).state)),r}getCurrentResult(){return R(this,dn)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),a==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&R(this,Ca).status==="pending"&&R(this,Ca).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,a))})}trackProp(t){R(this,Dl).add(t)}getCurrentQuery(){return R(this,Ne)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=R(this,On).defaultQueryOptions(t),r=R(this,On).getQueryCache().build(R(this,On),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Oe(this,ze,Pu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),R(this,dn)))}createResult(t,n){var T;const r=R(this,Ne),a=this.options,i=R(this,dn),s=R(this,Us),o=R(this,Pl),c=t!==r?t.state:R(this,Sd),{state:d}=t;let f={...d},h=!1,p;if(n._optimisticResults){const N=this.hasListeners(),M=!N&&pO(t,n),C=N&&mO(t,r,n,a);(M||C)&&(f={...f,...nk(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:m,errorUpdatedAt:g,status:v}=f;p=f.data;let y=!1;if(n.placeholderData!==void 0&&p===void 0&&v==="pending"){let N;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(N=i.data,y=!0):N=typeof n.placeholderData=="function"?n.placeholderData((T=R(this,Rl))==null?void 0:T.state.data,R(this,Rl)):n.placeholderData,N!==void 0&&(v="success",p=X0(i==null?void 0:i.data,N,n),h=!0)}if(n.select&&p!==void 0&&!y)if(i&&p===(s==null?void 0:s.data)&&n.select===R(this,wd))p=R(this,Ml);else try{ee(this,wd,n.select),p=n.select(p),p=X0(i==null?void 0:i.data,p,n),ee(this,Ml,p),ee(this,Ti,null)}catch(N){ee(this,Ti,N)}R(this,Ti)&&(m=R(this,Ti),p=R(this,Ml),g=Date.now(),v="error");const b=f.fetchStatus==="fetching",x=v==="pending",w=v==="error",S=x&&b,j=p!==void 0,E={status:v,fetchStatus:f.fetchStatus,isPending:x,isSuccess:v==="success",isError:w,isInitialLoading:S,isLoading:S,data:p,dataUpdatedAt:f.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:f.dataUpdateCount>c.dataUpdateCount||f.errorUpdateCount>c.errorUpdateCount,isFetching:b,isRefetching:b&&!x,isLoadingError:w&&!j,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:w&&j,isStale:yw(t,n),refetch:this.refetch,promise:R(this,Ca),isEnabled:Un(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const N=E.data!==void 0,M=E.status==="error"&&!N,C=k=>{M?k.reject(E.error):N&&k.resolve(E.data)},L=()=>{const k=ee(this,Ca,E.promise=Q0());C(k)},D=R(this,Ca);switch(D.status){case"pending":t.queryHash===r.queryHash&&C(D);break;case"fulfilled":(M||E.data!==D.value)&&L();break;case"rejected":(!M||E.error!==D.reason)&&L();break}}return E}updateResult(){const t=R(this,dn),n=this.createResult(R(this,Ne),this.options);if(ee(this,Us,R(this,Ne).state),ee(this,Pl,this.options),R(this,Us).data!==void 0&&ee(this,Rl,R(this,Ne)),Y0(n,t))return;ee(this,dn,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!R(this,Dl).size)return!0;const s=new Set(i??R(this,Dl));return this.options.throwOnError&&s.add("error"),Object.keys(R(this,dn)).some(o=>{const l=o;return R(this,dn)[l]!==t[l]&&s.has(l)})};Oe(this,ze,rk).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Oe(this,ze,nx).call(this)}},On=new WeakMap,Ne=new WeakMap,Sd=new WeakMap,dn=new WeakMap,Us=new WeakMap,Pl=new WeakMap,Ca=new WeakMap,Ti=new WeakMap,wd=new WeakMap,Ml=new WeakMap,Rl=new WeakMap,Fs=new WeakMap,Vs=new WeakMap,Ni=new WeakMap,Dl=new WeakMap,ze=new WeakSet,Pu=function(t){Oe(this,ze,ix).call(this);let n=R(this,Ne).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Nn)),n},J0=function(){Oe(this,ze,rx).call(this);const t=Yi(this.options.staleTime,R(this,Ne));if(Cf.isServer()||R(this,dn).isStale||!G0(t))return;const r=YD(R(this,dn).dataUpdatedAt,t)+1;ee(this,Fs,Ts.setTimeout(()=>{R(this,dn).isStale||this.updateResult()},r))},ex=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(R(this,Ne)):this.options.refetchInterval)??!1},tx=function(t){Oe(this,ze,ax).call(this),ee(this,Ni,t),!(Cf.isServer()||Un(this.options.enabled,R(this,Ne))===!1||!G0(R(this,Ni))||R(this,Ni)===0)&&ee(this,Vs,Ts.setInterval(()=>{(this.options.refetchIntervalInBackground||hw.isFocused())&&Oe(this,ze,Pu).call(this)},R(this,Ni)))},nx=function(){Oe(this,ze,J0).call(this),Oe(this,ze,tx).call(this,Oe(this,ze,ex).call(this))},rx=function(){R(this,Fs)!==void 0&&(Ts.clearTimeout(R(this,Fs)),ee(this,Fs,void 0))},ax=function(){R(this,Vs)!==void 0&&(Ts.clearInterval(R(this,Vs)),ee(this,Vs,void 0))},ix=function(){const t=R(this,On).getQueryCache().build(R(this,On),this.options);if(t===R(this,Ne))return;const n=R(this,Ne);ee(this,Ne,t),ee(this,Sd,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},rk=function(t){Qt.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(R(this,dn))}),R(this,On).getQueryCache().notify({query:R(this,Ne),type:"observerResultsUpdated"})})},UP);function zB(e,t){return Un(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&Un(t.retryOnMount,e)===!1)}function pO(e,t){return zB(e,t)||e.state.data!==void 0&&sx(e,t,t.refetchOnMount)}function sx(e,t,n){if(Un(t.enabled,e)!==!1&&Yi(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&yw(e,t)}return!1}function mO(e,t,n,r){return(e!==t||Un(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&yw(e,n)}function yw(e,t){return Un(t.enabled,e)!==!1&&e.isStaleByTime(Yi(t.staleTime,e))}function IB(e,t){return!Y0(e.getCurrentResult(),t)}var jd,Gr,sn,Hs,Yr,di,FP,BB=(FP=class extends ek{constructor(t){super();ce(this,Yr);ce(this,jd);ce(this,Gr);ce(this,sn);ce(this,Hs);ee(this,jd,t.client),this.mutationId=t.mutationId,ee(this,sn,t.mutationCache),ee(this,Gr,[]),this.state=t.state||UB(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){R(this,Gr).includes(t)||(R(this,Gr).push(t),this.clearGcTimeout(),R(this,sn).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ee(this,Gr,R(this,Gr).filter(n=>n!==t)),this.scheduleGc(),R(this,sn).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){R(this,Gr).length||(this.state.status==="pending"?this.scheduleGc():R(this,sn).remove(this))}continue(){var t;return((t=R(this,Hs))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var s,o,l,c,d,f,h,p,m,g,v,y,b,x,w,S,j,O;const n=()=>{Oe(this,Yr,di).call(this,{type:"continue"})},r={client:R(this,jd),meta:this.options.meta,mutationKey:this.options.mutationKey};ee(this,Hs,JD({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(E,T)=>{Oe(this,Yr,di).call(this,{type:"failed",failureCount:E,error:T})},onPause:()=>{Oe(this,Yr,di).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>R(this,sn).canRun(this)}));const a=this.state.status==="pending",i=!R(this,Hs).canStart();try{if(a)n();else{Oe(this,Yr,di).call(this,{type:"pending",variables:t,isPaused:i}),R(this,sn).config.onMutate&&await R(this,sn).config.onMutate(t,this,r);const T=await((o=(s=this.options).onMutate)==null?void 0:o.call(s,t,r));T!==this.state.context&&Oe(this,Yr,di).call(this,{type:"pending",context:T,variables:t,isPaused:i})}const E=await R(this,Hs).start();return await((c=(l=R(this,sn).config).onSuccess)==null?void 0:c.call(l,E,t,this.state.context,this,r)),await((f=(d=this.options).onSuccess)==null?void 0:f.call(d,E,t,this.state.context,r)),await((p=(h=R(this,sn).config).onSettled)==null?void 0:p.call(h,E,null,this.state.variables,this.state.context,this,r)),await((g=(m=this.options).onSettled)==null?void 0:g.call(m,E,null,t,this.state.context,r)),Oe(this,Yr,di).call(this,{type:"success",data:E}),E}catch(E){try{await((y=(v=R(this,sn).config).onError)==null?void 0:y.call(v,E,t,this.state.context,this,r))}catch(T){Promise.reject(T)}try{await((x=(b=this.options).onError)==null?void 0:x.call(b,E,t,this.state.context,r))}catch(T){Promise.reject(T)}try{await((S=(w=R(this,sn).config).onSettled)==null?void 0:S.call(w,void 0,E,this.state.variables,this.state.context,this,r))}catch(T){Promise.reject(T)}try{await((O=(j=this.options).onSettled)==null?void 0:O.call(j,void 0,E,t,this.state.context,r))}catch(T){Promise.reject(T)}throw Oe(this,Yr,di).call(this,{type:"error",error:E}),E}finally{R(this,sn).runNext(this)}}},jd=new WeakMap,Gr=new WeakMap,sn=new WeakMap,Hs=new WeakMap,Yr=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Qt.batch(()=>{R(this,Gr).forEach(r=>{r.onMutationUpdate(t)}),R(this,sn).notify({mutation:this,type:"updated",action:t})})},FP);function UB(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var _a,Mr,Ad,VP,FB=(VP=class extends Ld{constructor(t={}){super();ce(this,_a);ce(this,Mr);ce(this,Ad);this.config=t,ee(this,_a,new Set),ee(this,Mr,new Map),ee(this,Ad,0)}build(t,n,r){const a=new BB({client:t,mutationCache:this,mutationId:++oh(this,Ad)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){R(this,_a).add(t);const n=Oh(t);if(typeof n=="string"){const r=R(this,Mr).get(n);r?r.push(t):R(this,Mr).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(R(this,_a).delete(t)){const n=Oh(t);if(typeof n=="string"){const r=R(this,Mr).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&R(this,Mr).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Oh(t);if(typeof n=="string"){const r=R(this,Mr).get(n),a=r==null?void 0:r.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var r;const n=Oh(t);if(typeof n=="string"){const a=(r=R(this,Mr).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Qt.batch(()=>{R(this,_a).forEach(t=>{this.notify({type:"removed",mutation:t})}),R(this,_a).clear(),R(this,Mr).clear()})}getAll(){return Array.from(R(this,_a))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>lO(n,r))}findAll(t={}){return this.getAll().filter(n=>lO(t,n))}notify(t){Qt.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Qt.batch(()=>Promise.all(t.map(n=>n.continue().catch(Nn))))}},_a=new WeakMap,Mr=new WeakMap,Ad=new WeakMap,VP);function Oh(e){var t;return(t=e.options.scope)==null?void 0:t.id}var Wr,HP,VB=(HP=class extends Ld{constructor(t={}){super();ce(this,Wr);this.config=t,ee(this,Wr,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??pw(a,n);let s=this.get(i);return s||(s=new $B({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(s)),s}add(t){R(this,Wr).has(t.queryHash)||(R(this,Wr).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=R(this,Wr).get(t.queryHash);n&&(t.destroy(),n===t&&R(this,Wr).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Qt.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return R(this,Wr).get(t)}getAll(){return[...R(this,Wr).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>oO(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>oO(t,r)):n}notify(t){Qt.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Qt.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Qt.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Wr=new WeakMap,HP),yt,Ci,_i,kl,$l,Pi,Ll,zl,qP,HB=(qP=class{constructor(e={}){ce(this,yt);ce(this,Ci);ce(this,_i);ce(this,kl);ce(this,$l);ce(this,Pi);ce(this,Ll);ce(this,zl);ee(this,yt,e.queryCache||new VB),ee(this,Ci,e.mutationCache||new FB),ee(this,_i,e.defaultOptions||{}),ee(this,kl,new Map),ee(this,$l,new Map),ee(this,Pi,0)}mount(){oh(this,Pi)._++,R(this,Pi)===1&&(ee(this,Ll,hw.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,yt).onFocus())})),ee(this,zl,rm.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,yt).onOnline())})))}unmount(){var e,t;oh(this,Pi)._--,R(this,Pi)===0&&((e=R(this,Ll))==null||e.call(this),ee(this,Ll,void 0),(t=R(this,zl))==null||t.call(this),ee(this,zl,void 0))}isFetching(e){return R(this,yt).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return R(this,Ci).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,yt).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=R(this,yt).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Yi(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return R(this,yt).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),a=R(this,yt).get(r.queryHash),i=a==null?void 0:a.state.data,s=AB(t,i);if(s!==void 0)return R(this,yt).build(this,r).setData(s,{...n,manual:!0})}setQueriesData(e,t,n){return Qt.batch(()=>R(this,yt).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,yt).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=R(this,yt);Qt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=R(this,yt);return Qt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Qt.batch(()=>R(this,yt).findAll(e).map(a=>a.cancel(n)));return Promise.all(r).then(Nn).catch(Nn)}invalidateQueries(e,t={}){return Qt.batch(()=>(R(this,yt).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Qt.batch(()=>R(this,yt).findAll(e).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(Nn)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Nn)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=R(this,yt).build(this,t);return n.isStaleByTime(Yi(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Nn).catch(Nn)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Nn).catch(Nn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return rm.isOnline()?R(this,Ci).resumePausedMutations():Promise.resolve()}getQueryCache(){return R(this,yt)}getMutationCache(){return R(this,Ci)}getDefaultOptions(){return R(this,_i)}setDefaultOptions(e){ee(this,_i,e)}setQueryDefaults(e,t){R(this,kl).set(Tf(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...R(this,kl).values()],n={};return t.forEach(r=>{Nf(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){R(this,$l).set(Tf(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...R(this,$l).values()],n={};return t.forEach(r=>{Nf(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...R(this,_i).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=pw(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===mw&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...R(this,_i).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){R(this,yt).clear(),R(this,Ci).clear()}},yt=new WeakMap,Ci=new WeakMap,_i=new WeakMap,kl=new WeakMap,$l=new WeakMap,Pi=new WeakMap,Ll=new WeakMap,zl=new WeakMap,qP),ak=A.createContext(void 0),rn=e=>{const t=A.useContext(ak);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},qB=({client:e,children:t})=>(A.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),u.jsx(ak.Provider,{value:e,children:t})),ik=A.createContext(!1),KB=()=>A.useContext(ik);ik.Provider;function GB(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var YB=A.createContext(GB()),WB=()=>A.useContext(YB),XB=(e,t,n)=>{const r=n!=null&&n.state.error&&typeof e.throwOnError=="function"?QD(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},QB=e=>{A.useEffect(()=>{e.clearReset()},[e])},ZB=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(a&&e.data===void 0||QD(n,[e.error,r])),JB=e=>{if(e.suspense){const n=a=>a==="static"?a:Math.max(a??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...a)=>n(r(...a)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},eU=(e,t)=>e.isLoading&&e.isFetching&&!t,tU=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,yO=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function nU(e,t,n){var p,m,g,v;const r=KB(),a=WB(),i=rn(),s=i.defaultQueryOptions(e);(m=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_beforeQuery)==null||m.call(p,s);const o=i.getQueryCache().get(s.queryHash),l=e.subscribed!==!1;s._optimisticResults=r?"isRestoring":l?"optimistic":void 0,JB(s),XB(s,a,o),QB(a);const c=!i.getQueryCache().get(s.queryHash),[d]=A.useState(()=>new t(i,s)),f=d.getOptimisticResult(s),h=!r&&l;if(A.useSyncExternalStore(A.useCallback(y=>{const b=h?d.subscribe(Qt.batchCalls(y)):Nn;return d.updateResult(),b},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),A.useEffect(()=>{d.setOptions(s)},[s,d]),tU(s,f))throw yO(s,d,a);if(ZB({result:f,errorResetBoundary:a,throwOnError:s.throwOnError,query:o,suspense:s.suspense}))throw f.error;if((v=(g=i.getDefaultOptions().queries)==null?void 0:g._experimental_afterQuery)==null||v.call(g,s,f),s.experimental_prefetchInRender&&!Cf.isServer()&&eU(f,r)){const y=c?yO(s,d,a):o==null?void 0:o.promise;y==null||y.catch(Nn).finally(()=>{d.updateResult()})}return s.notifyOnChangeProps?f:d.trackResult(f)}function se(e,t){return nU(e,LB)}/** + * 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 gO="popstate";function vO(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function rU(e={}){function t(r,a){var c;let i=(c=a.state)==null?void 0:c.masked,{pathname:s,search:o,hash:l}=i||r.location;return ox("",{pathname:s,search:o,hash:l},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:_f(a)}return iU(t,n,null,e)}function ft(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Sr(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function aU(){return Math.random().toString(36).substring(2,10)}function bO(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 ox(e,t,n=null,r,a){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?$c(t):t,state:n,key:t&&t.key||r||aU(),mask:a}}function _f({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 $c(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 iU(e,t,n,r={}){let{window:a=document.defaultView,v5Compat:i=!1}=r,s=a.history,o="POP",l=null,c=d();c==null&&(c=0,s.replaceState({...s.state,idx:c},""));function d(){return(s.state||{idx:null}).idx}function f(){o="POP";let v=d(),y=v==null?null:v-c;c=v,l&&l({action:o,location:g.location,delta:y})}function h(v,y){o="PUSH";let b=vO(v)?v:ox(g.location,v,y);c=d()+1;let x=bO(b,c),w=g.createHref(b.mask||b);try{s.pushState(x,"",w)}catch(S){if(S instanceof DOMException&&S.name==="DataCloneError")throw S;a.location.assign(w)}i&&l&&l({action:o,location:g.location,delta:1})}function p(v,y){o="REPLACE";let b=vO(v)?v:ox(g.location,v,y);c=d();let x=bO(b,c),w=g.createHref(b.mask||b);s.replaceState(x,"",w),i&&l&&l({action:o,location:g.location,delta:0})}function m(v){return sU(a,v)}let g={get action(){return o},get location(){return e(a,s)},listen(v){if(l)throw new Error("A history only accepts one active listener");return a.addEventListener(gO,f),l=v,()=>{a.removeEventListener(gO,f),l=null}},createHref(v){return t(a,v)},createURL:m,encodeLocation(v){let y=m(v);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:h,replace:p,go(v){return s.go(v)}};return g}function sU(e,t,n=!1){let r="http://localhost";e&&(r=e.location.origin!=="null"?e.location.origin:e.location.href),ft(r,"No window.location.(origin|href) available to create URL");let a=typeof t=="string"?t:_f(t);return a=a.replace(/ $/,"%20"),!n&&a.startsWith("//")&&(a=r+a),new URL(a,r)}function sk(e,t,n="/"){return oU(e,t,n,!1)}function oU(e,t,n,r,a){let i=typeof t=="string"?$c(t):t,s=Za(i.pathname||"/",n);if(s==null)return null;let o=lU(e),l=null,c=xU(s);for(let d=0;l==null&&d{let d={relativePath:c===void 0?s.path||"":c,caseSensitive:s.caseSensitive===!0,childrenIndex:o,route:s};if(d.relativePath.startsWith("/")){if(!d.relativePath.startsWith(r)&&l)return;ft(d.relativePath.startsWith(r),`Absolute route path "${d.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),d.relativePath=d.relativePath.slice(r.length)}let f=zr([r,d.relativePath]),h=n.concat(d);s.children&&s.children.length>0&&(ft(s.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${f}".`),ok(s.children,t,h,f,l)),!(s.path==null&&!s.index)&&t.push({path:f,score:yU(f,s.index),routesMeta:h})};return e.forEach((s,o)=>{var l;if(s.path===""||!((l=s.path)!=null&&l.includes("?")))i(s,o);else for(let c of lk(s.path))i(s,o,!0,c)}),t}function lk(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 s=lk(r.join("/")),o=[];return o.push(...s.map(l=>l===""?i:[i,l].join("/"))),a&&o.push(...s),o.map(l=>e.startsWith("/")&&l===""?"/":l)}function cU(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:gU(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var uU=/^:[\w-]+$/,fU=3,dU=2,hU=1,pU=10,mU=-2,xO=e=>e==="*";function yU(e,t){let n=e.split("/"),r=n.length;return n.some(xO)&&(r+=mU),t&&(r+=dU),n.filter(a=>!xO(a)).reduce((a,i)=>a+(uU.test(i)?fU:i===""?hU:pU),r)}function gU(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 vU(e,t,n=!1){let{routesMeta:r}=e,a={},i="/",s=[];for(let o=0;o{if(d==="*"){let m=o[h]||"";s=i.slice(0,i.length-m.length).replace(/(.)\/+$/,"$1")}const p=o[h];return f&&!p?c[d]=void 0:c[d]=(p||"").replace(/%2F/g,"/"),c},{}),pathname:i,pathnameBase:s,pattern:e}}function bU(e,t=!1,n=!0){Sr(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,(s,o,l,c,d)=>{if(r.push({paramName:o,isOptional:l!=null}),l){let f=d.charAt(c+s.length);return f&&f!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}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 xU(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Sr(!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 Za(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 SU=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function wU(e,t="/"){let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?$c(e):e,i;return n?(n=ck(n),n.startsWith("/")?i=SO(n.substring(1),"/"):i=SO(n,t)):i=t,{pathname:i,search:OU(r),hash:EU(a)}}function SO(e,t){let n=im(t).split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function Vv(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 jU(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function gw(e){let t=jU(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function qy(e,t,n,r=!1){let a;typeof e=="string"?a=$c(e):(a={...e},ft(!a.pathname||!a.pathname.includes("?"),Vv("?","pathname","search",a)),ft(!a.pathname||!a.pathname.includes("#"),Vv("#","pathname","hash",a)),ft(!a.search||!a.search.includes("#"),Vv("#","search","hash",a)));let i=e===""||a.pathname==="",s=i?"/":a.pathname,o;if(s==null)o=n;else{let f=t.length-1;if(!r&&s.startsWith("..")){let h=s.split("/");for(;h[0]==="..";)h.shift(),f-=1;a.pathname=h.join("/")}o=f>=0?t[f]:"/"}let l=wU(a,o),c=s&&s!=="/"&&s.endsWith("/"),d=(i||s===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(c||d)&&(l.pathname+="/"),l}var ck=e=>e.replace(/\/\/+/g,"/"),zr=e=>ck(e.join("/")),im=e=>e.replace(/\/+$/,""),AU=e=>im(e).replace(/^\/*/,"/"),OU=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,EU=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,TU=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 NU(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function CU(e){let t=e.map(n=>n.route.path).filter(Boolean);return zr(t)||"/"}var uk=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function fk(e,t){let n=e;if(typeof n!="string"||!SU.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,a=!1;if(uk)try{let i=new URL(window.location.href),s=n.startsWith("//")?new URL(i.protocol+n):new URL(n),o=Za(s.pathname,t);s.origin===i.origin&&o!=null?n=o+s.search+s.hash:a=!0}catch{Sr(!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 dk=["POST","PUT","PATCH","DELETE"];new Set(dk);var _U=["GET",...dk];new Set(_U);var Lc=A.createContext(null);Lc.displayName="DataRouter";var Ky=A.createContext(null);Ky.displayName="DataRouterState";var hk=A.createContext(!1);function PU(){return A.useContext(hk)}var pk=A.createContext({isTransitioning:!1});pk.displayName="ViewTransition";var MU=A.createContext(new Map);MU.displayName="Fetchers";var RU=A.createContext(null);RU.displayName="Await";var nr=A.createContext(null);nr.displayName="Navigation";var zd=A.createContext(null);zd.displayName="Location";var Ar=A.createContext({outlet:null,matches:[],isDataRoute:!1});Ar.displayName="Route";var vw=A.createContext(null);vw.displayName="RouteError";var mk="REACT_ROUTER_ERROR",DU="REDIRECT",kU="ROUTE_ERROR_RESPONSE";function $U(e){if(e.startsWith(`${mk}:${DU}:{`))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 LU(e){if(e.startsWith(`${mk}:${kU}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new TU(t.status,t.statusText,t.data)}catch{}}function zU(e,{relative:t}={}){ft(zc(),"useHref() may be used only in the context of a component.");let{basename:n,navigator:r}=A.useContext(nr),{hash:a,pathname:i,search:s}=Id(e,{relative:t}),o=i;return n!=="/"&&(o=i==="/"?n:zr([n,i])),r.createHref({pathname:o,search:s,hash:a})}function zc(){return A.useContext(zd)!=null}function Or(){return ft(zc(),"useLocation() may be used only in the context of a component."),A.useContext(zd).location}var yk="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function gk(e){A.useContext(nr).static||A.useLayoutEffect(e)}function Gt(){let{isDataRoute:e}=A.useContext(Ar);return e?JU():IU()}function IU(){ft(zc(),"useNavigate() may be used only in the context of a component.");let e=A.useContext(Lc),{basename:t,navigator:n}=A.useContext(nr),{matches:r}=A.useContext(Ar),{pathname:a}=Or(),i=JSON.stringify(gw(r)),s=A.useRef(!1);return gk(()=>{s.current=!0}),A.useCallback((l,c={})=>{if(Sr(s.current,yk),!s.current)return;if(typeof l=="number"){n.go(l);return}let d=qy(l,JSON.parse(i),a,c.relative==="path");e==null&&t!=="/"&&(d.pathname=d.pathname==="/"?t:zr([t,d.pathname])),(c.replace?n.replace:n.push)(d,c.state,c)},[t,n,i,a,e])}var BU=A.createContext(null);function UU(e){let t=A.useContext(Ar).outlet;return A.useMemo(()=>t&&A.createElement(BU.Provider,{value:e},t),[t,e])}function vk(){let{matches:e}=A.useContext(Ar),t=e[e.length-1];return(t==null?void 0:t.params)??{}}function Id(e,{relative:t}={}){let{matches:n}=A.useContext(Ar),{pathname:r}=Or(),a=JSON.stringify(gw(n));return A.useMemo(()=>qy(e,JSON.parse(a),r,t==="path"),[e,a,r,t])}function FU(e,t){return bk(e,t)}function bk(e,t,n){var v;ft(zc(),"useRoutes() may be used only in the context of a component.");let{navigator:r}=A.useContext(nr),{matches:a}=A.useContext(Ar),i=a[a.length-1],s=i?i.params:{},o=i?i.pathname:"/",l=i?i.pathnameBase:"/",c=i&&i.route;{let y=c&&c.path||"";Sk(o,!c||y.endsWith("*")||y.endsWith("*?"),`You rendered descendant (or called \`useRoutes()\`) at "${o}" (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 d=Or(),f;if(t){let y=typeof t=="string"?$c(t):t;ft(l==="/"||((v=y.pathname)==null?void 0:v.startsWith(l)),`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 "${l}" but pathname "${y.pathname}" was given in the \`location\` prop.`),f=y}else f=d;let h=f.pathname||"/",p=h;if(l!=="/"){let y=l.replace(/^\//,"").split("/");p="/"+h.replace(/^\//,"").split("/").slice(y.length).join("/")}let m=n&&n.state.matches.length?n.state.matches.map(y=>Object.assign(y,{route:n.manifest[y.route.id]||y.route})):sk(e,{pathname:p});Sr(c||m!=null,`No routes matched location "${f.pathname}${f.search}${f.hash}" `),Sr(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${f.pathname}${f.search}${f.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 g=GU(m&&m.map(y=>Object.assign({},y,{params:Object.assign({},s,y.params),pathname:zr([l,r.encodeLocation?r.encodeLocation(y.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?l:zr([l,r.encodeLocation?r.encodeLocation(y.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:y.pathnameBase])})),a,n);return t&&g?A.createElement(zd.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",mask:void 0,...f},navigationType:"POP"}},g):g}function VU(){let e=ZU(),t=NU(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},s=null;return console.error("Error handled by React Router default ErrorBoundary:",e),s=A.createElement(A.Fragment,null,A.createElement("p",null,"💿 Hey developer 👋"),A.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",A.createElement("code",{style:i},"ErrorBoundary")," or"," ",A.createElement("code",{style:i},"errorElement")," prop on your route.")),A.createElement(A.Fragment,null,A.createElement("h2",null,"Unexpected Application Error!"),A.createElement("h3",{style:{fontStyle:"italic"}},t),n?A.createElement("pre",{style:a},n):null,s)}var HU=A.createElement(VU,null),xk=class extends A.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=LU(e.digest);n&&(e=n)}let t=e!==void 0?A.createElement(Ar.Provider,{value:this.props.routeContext},A.createElement(vw.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?A.createElement(qU,{error:e},t):t}};xk.contextType=hk;var Hv=new WeakMap;function qU({children:e,error:t}){let{basename:n}=A.useContext(nr);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=$U(t.digest);if(r){let a=Hv.get(t);if(a)throw a;let i=fk(r.location,n);if(uk&&!Hv.get(t))if(i.isExternal||r.reloadDocument)window.location.href=i.absoluteURL||i.to;else{const s=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:r.replace}));throw Hv.set(t,s),s}return A.createElement("meta",{httpEquiv:"refresh",content:`0;url=${i.absoluteURL||i.to}`})}}return e}function KU({routeContext:e,match:t,children:n}){let r=A.useContext(Lc);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),A.createElement(Ar.Provider,{value:e},n)}function GU(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 d=a.findIndex(f=>f.route.id&&(i==null?void 0:i[f.route.id])!==void 0);ft(d>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(i).join(",")}`),a=a.slice(0,Math.min(a.length,d+1))}let s=!1,o=-1;if(n&&r){s=r.renderFallback;for(let d=0;d=0?a=a.slice(0,o+1):a=[a[0]];break}}}}let l=n==null?void 0:n.onError,c=r&&l?(d,f)=>{var h,p;l(d,{location:r.location,params:((p=(h=r.matches)==null?void 0:h[0])==null?void 0:p.params)??{},pattern:CU(r.matches),errorInfo:f})}:void 0;return a.reduceRight((d,f,h)=>{let p,m=!1,g=null,v=null;r&&(p=i&&f.route.id?i[f.route.id]:void 0,g=f.route.errorElement||HU,s&&(o<0&&h===0?(Sk("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),m=!0,v=null):o===h&&(m=!0,v=f.route.hydrateFallbackElement||null)));let y=t.concat(a.slice(0,h+1)),b=()=>{let x;return p?x=g:m?x=v:f.route.Component?x=A.createElement(f.route.Component,null):f.route.element?x=f.route.element:x=d,A.createElement(KU,{match:f,routeContext:{outlet:d,matches:y,isDataRoute:r!=null},children:x})};return r&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?A.createElement(xk,{location:r.location,revalidation:r.revalidation,component:g,error:p,children:b(),routeContext:{outlet:null,matches:y,isDataRoute:!0},onError:c}):b()},null)}function bw(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function YU(e){let t=A.useContext(Lc);return ft(t,bw(e)),t}function WU(e){let t=A.useContext(Ky);return ft(t,bw(e)),t}function XU(e){let t=A.useContext(Ar);return ft(t,bw(e)),t}function xw(e){let t=XU(e),n=t.matches[t.matches.length-1];return ft(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function QU(){return xw("useRouteId")}function ZU(){var r;let e=A.useContext(vw),t=WU("useRouteError"),n=xw("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function JU(){let{router:e}=YU("useNavigate"),t=xw("useNavigate"),n=A.useRef(!1);return gk(()=>{n.current=!0}),A.useCallback(async(a,i={})=>{Sr(n.current,yk),n.current&&(typeof a=="number"?await e.navigate(a):await e.navigate(a,{fromRouteId:t,...i}))},[e,t])}var wO={};function Sk(e,t,n){!t&&!wO[e]&&(wO[e]=!0,Sr(!1,n))}A.memo(e7);function e7({routes:e,manifest:t,future:n,state:r,isStatic:a,onError:i}){return bk(e,void 0,{manifest:t,state:r,isStatic:a,onError:i})}function sm({to:e,replace:t,state:n,relative:r}){ft(zc()," may be used only in the context of a component.");let{static:a}=A.useContext(nr);Sr(!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}=A.useContext(Ar),{pathname:s}=Or(),o=Gt(),l=qy(e,gw(i),s,r==="path"),c=JSON.stringify(l);return A.useEffect(()=>{o(JSON.parse(c),{replace:t,state:n,relative:r})},[o,c,r,t,n]),null}function wk(e){return UU(e.context)}function ve(e){ft(!1,"A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .")}function t7({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:a,static:i=!1,useTransitions:s}){ft(!zc(),"You cannot render a inside another . You should never have more than one in your app.");let o=e.replace(/^\/*/,"/"),l=A.useMemo(()=>({basename:o,navigator:a,static:i,useTransitions:s,future:{}}),[o,a,i,s]);typeof n=="string"&&(n=$c(n));let{pathname:c="/",search:d="",hash:f="",state:h=null,key:p="default",mask:m}=n,g=A.useMemo(()=>{let v=Za(c,o);return v==null?null:{location:{pathname:v,search:d,hash:f,state:h,key:p,mask:m},navigationType:r}},[o,c,d,f,h,p,r,m]);return Sr(g!=null,` is not able to match the URL "${c}${d}${f}" because it does not start with the basename, so the won't render anything.`),g==null?null:A.createElement(nr.Provider,{value:l},A.createElement(zd.Provider,{children:t,value:g}))}function n7({children:e,location:t}){return FU(lx(e),t)}function lx(e,t=[]){let n=[];return A.Children.forEach(e,(r,a)=>{if(!A.isValidElement(r))return;let i=[...t,a];if(r.type===A.Fragment){n.push.apply(n,lx(r.props.children,i));return}ft(r.type===ve,`[${typeof r.type=="string"?r.type:r.type.name}] is not a component. All component children of must be a or `),ft(!r.props.index||!r.props.children,"An index route cannot have child routes.");let s={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&&(s.children=lx(r.props.children,i)),n.push(s)}),n}var mp="get",yp="application/x-www-form-urlencoded";function Gy(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function r7(e){return Gy(e)&&e.tagName.toLowerCase()==="button"}function a7(e){return Gy(e)&&e.tagName.toLowerCase()==="form"}function i7(e){return Gy(e)&&e.tagName.toLowerCase()==="input"}function s7(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function o7(e,t){return e.button===0&&(!t||t==="_self")&&!s7(e)}function cx(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function l7(e,t){let n=cx(e);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}var Eh=null;function c7(){if(Eh===null)try{new FormData(document.createElement("form"),0),Eh=!1}catch{Eh=!0}return Eh}var u7=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function qv(e){return e!=null&&!u7.has(e)?(Sr(!1,`"${e}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${yp}"`),null):e}function f7(e,t){let n,r,a,i,s;if(a7(e)){let o=e.getAttribute("action");r=o?Za(o,t):null,n=e.getAttribute("method")||mp,a=qv(e.getAttribute("enctype"))||yp,i=new FormData(e)}else if(r7(e)||i7(e)&&(e.type==="submit"||e.type==="image")){let o=e.form;if(o==null)throw new Error('Cannot submit a -

{t('admin.login.storefrontHere')} {t('admin.login.here')}

- + + {step === 'login' ? ( +
+
+ GUARDiA { (e.target as HTMLImageElement).style.display = 'none' }} /> + {t('admin.login.title')} +
+

{t('admin.login.subtitle')}

+ + 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" /> + {err &&

{err}

} + +

{t('admin.login.storefrontHere')} {t('admin.login.here')}

+
+ ) : ( +
+
+ 2차 인증 / 2FA +
+

운영 계정 보안을 위한 2차 인증입니다.

+

+ 인증 코드를 {maskedEmail || '등록된 이메일'} 로 보냈습니다. +

+ + setCode(e.target.value)} inputMode="numeric" maxLength={6} autoFocus + className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm tracking-[0.4em] text-center focus:border-brand outline-none" /> + {err &&

{err}

} + + +
+ )} ) } diff --git a/frontend/src/api/uiws.ts b/frontend/src/api/uiws.ts new file mode 100644 index 0000000..a3721b0 --- /dev/null +++ b/frontend/src/api/uiws.ts @@ -0,0 +1,68 @@ +import api from './client' + +/** + * UIWS 이식 모듈 API 클라이언트 (GUARDiA Mall). + * 기존 Mall axios 인스턴스(client.ts: baseURL='' same-origin, JWT 인터셉터/토큰키 분리) 재사용. + * Mall client 는 baseURL 가 비어 있으므로 UIWS 경로는 full path(/api/...)로 호출한다. + * 응답 봉투: { success, message, data }. 호출부는 res.data.data 로 페이로드 접근. + * + * 인증: 관리자 영역(/admin)에서 호출되므로 client 인터셉터가 mall_admin_token 을 자동 첨부. + */ + +// ── 2FA (운영 로그인 2차 검증) +export const verify2fa = (verifyToken: string, code: string) => + api.post('/api/mall/auth/verify', { verifyToken, code }) + +// ── 쪽지(message) +export const sendMessage = (body: object) => api.post('/api/messages', body) +export const listSent = (params: Record) => api.get('/api/messages/sent', { params }) +export const sentDetail = (id: number) => api.get(`/api/messages/sent/${id}`) +export const deleteSent = (ids: number[]) => api.delete('/api/messages/sent', { data: { ids } }) +export const listReceived = (params: Record) => api.get('/api/messages/received', { params }) +export const receivedDetail = (id: number) => api.get(`/api/messages/received/${id}`) +export const deleteReceived = (ids: number[]) => api.delete('/api/messages/received', { data: { ids } }) +export const unreadCount = () => api.get('/api/messages/unread-count') + +// ── 일정(schedule) +export const scheduleCalendar = (params: Record) => api.get('/api/schedules', { params }) +export const scheduleAll = (params: Record) => api.get('/api/schedules/all', { params }) +export const scheduleSearch = (keyword: string) => api.get('/api/schedules/search', { params: { keyword } }) +export const createSchedule = (body: object) => api.post('/api/schedules', body) +export const scheduleDetail = (id: number) => api.get(`/api/schedules/${id}`) +export const updateSchedule = (id: number, body: object) => api.put(`/api/schedules/${id}`, body) +export const deleteSchedule = (id: number) => api.delete(`/api/schedules/${id}`) + +// ── 일지(diary) +export const diaryList = (params: Record) => api.get('/api/diaries', { params }) +export const createDiary = (body: object) => api.post('/api/diaries', body) +export const diaryDetail = (id: number) => api.get(`/api/diaries/${id}`) +export const updateDiary = (id: number, body: object) => api.put(`/api/diaries/${id}`, body) +export const deleteDiary = (id: number) => api.delete(`/api/diaries/${id}`) + +// ── 첨부(attachment) +export const uploadAttachment = (refType: string, refId: number, file: File) => { + const fd = new FormData() + fd.append('refType', refType) + fd.append('refId', String(refId)) + fd.append('file', file) + return api.post('/api/attachments', fd, { headers: { 'Content-Type': 'multipart/form-data' } }) +} +export const deleteAttachment = (id: number) => api.delete(`/api/attachments/${id}`) +export const attachmentDownloadUrl = (id: number) => `/api/attachments/${id}/download` + +// ── 업무일지(worklog) +export const worklogList = (params: Record) => api.get('/api/worklogs', { params }) +export const worklogCalendar = (params: Record) => api.get('/api/worklogs/calendar', { params }) +export const worklogSearch = (params: Record) => api.get('/api/worklogs/search', { params }) +export const worklogProgress = (params: Record) => api.get('/api/worklogs/dashboard/progress', { params }) +export const createWorklog = (body: object) => api.post('/api/worklogs', body) +export const worklogDetail = (id: number) => api.get(`/api/worklogs/${id}`) +export const updateWorklog = (id: number, body: object) => api.put(`/api/worklogs/${id}`, body) +export const deleteWorklog = (id: number) => api.delete(`/api/worklogs/${id}`) +export const addWorklogComment = (id: number, cmtContent: string) => + api.post(`/api/worklogs/${id}/comments`, { cmtContent }) +export const confirmWorklogComment = (cmtId: number) => api.post(`/api/worklogs/comments/${cmtId}/confirm`) + +// ── 통계(stats) +export const personalWorkStats = (params: Record) => api.get('/api/stats/personal-work', { params }) +export const companyWorkStats = (params: Record) => api.get('/api/stats/company-work', { params }) diff --git a/frontend/src/components/uiws/ThemeToggle.tsx b/frontend/src/components/uiws/ThemeToggle.tsx new file mode 100644 index 0000000..dbce4bc --- /dev/null +++ b/frontend/src/components/uiws/ThemeToggle.tsx @@ -0,0 +1,16 @@ +import { Moon, Sun } from 'lucide-react' +import { useTheme } from '../../theme/ThemeContext' + +/** 다크/라이트 테마 토글 버튼. 사이드바 하단 등에 배치. */ +export default function ThemeToggle() { + const { theme, toggle } = useTheme() + return ( + + ) +} 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/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/UiwsLayout.tsx b/frontend/src/pages/uiws/UiwsLayout.tsx new file mode 100644 index 0000000..b47db8a --- /dev/null +++ b/frontend/src/pages/uiws/UiwsLayout.tsx @@ -0,0 +1,22 @@ +import { type ReactNode } from 'react' +import { ThemeProvider } from '../../theme/ThemeContext' +import ThemeToggle from '../../components/uiws/ThemeToggle' +import '../../theme/theme.css' + +/** + * UIWS 이식 화면 공통 래퍼. 관리자(/admin) 셸 안에서 렌더되며, + * .uiws-scope + ThemeProvider 로 다크/라이트 토큰을 격리 적용한다(기존 Mall 테마 무영향). + * 우상단 ThemeToggle 로 양 모드 전환(영속 mall_uiws_theme). + */ +export default function UiwsLayout({ children }: { children: ReactNode }) { + return ( + +
+
+
+
+ {children} +
+
+ ) +} diff --git a/frontend/src/pages/uiws/WorklogList.tsx b/frontend/src/pages/uiws/WorklogList.tsx new file mode 100644 index 0000000..ddcbbcd --- /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('erp_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..971051e --- /dev/null +++ b/frontend/src/theme/ThemeContext.tsx @@ -0,0 +1,43 @@ +import { createContext, useContext, useEffect, useState, type ReactNode } from 'react' + +/** + * UIWS 이식 모듈 테마(다크/라이트). 모듈 스코프 — 전역 Mall 테마(관리자 .admin-shell / + * 스토어프론트 Tailwind)는 건드리지 않는다. data-uiws-theme 속성만 토글하여 var(--uiws-*) 스왑. + * 영속: localStorage('mall_uiws_theme'). 기본 dark(관리자 셸 정합). + */ +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 = 'mall_uiws_theme' + +function applyTheme(t: ThemeMode) { + document.documentElement.setAttribute('data-uiws-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..a077202 --- /dev/null +++ b/frontend/src/theme/theme.css @@ -0,0 +1,53 @@ +/* + * GUARDiA Mall — UIWS 이식 화면 테마 토큰 (모듈 스코프). + * 다크/라이트 두 모드 지원. UIWS 화면/컴포넌트는 색상 하드코딩 금지 — 아래 CSS 변수만 사용한다. + * 기존 Mall 화면(관리자 NCloud 다크 .admin-shell / 스토어프론트 Tailwind)은 영향 없음 + * (이 변수는 .uiws-scope 영역에서만 참조). 셀렉터는 data-uiws-theme(Mall 미사용 속성)로 격리. + * + * 다크 기본값은 Mall 관리자 팔레트(ink #0b0f17 / card #1a2234 / brand #00a0c8)와 정합. + */ + +:root, +:root[data-uiws-theme='dark'] { + --uiws-bg: #0b0f17; + --uiws-surface: #131927; + --uiws-surface-2: #1a2234; + --uiws-border: #26304a; + --uiws-text: #e6edf6; + --uiws-text-muted: #9aa7bd; + --uiws-text-faint: #6b7a93; + --uiws-primary: #00a0c8; + --uiws-primary-contrast: #06121a; + --uiws-primary-soft: rgba(0, 160, 200, 0.16); + --uiws-danger: #f87171; + --uiws-success: #3ddc97; + --uiws-warning: #f0b429; + --uiws-row-hover: rgba(255, 255, 255, 0.04); + --uiws-input-bg: #0b0f17; + --uiws-shadow: 0 8px 30px -10px rgba(0, 0, 0, 0.55); +} + +:root[data-uiws-theme='light'] { + --uiws-bg: #f5f7fb; + --uiws-surface: #ffffff; + --uiws-surface-2: #eef2f8; + --uiws-border: #dbe2ee; + --uiws-text: #1c2433; + --uiws-text-muted: #5a6878; + --uiws-text-faint: #8a97a8; + --uiws-primary: #007ea0; + --uiws-primary-contrast: #ffffff; + --uiws-primary-soft: rgba(0, 126, 160, 0.10); + --uiws-danger: #d64545; + --uiws-success: #1f9d6b; + --uiws-warning: #b7791f; + --uiws-row-hover: rgba(0, 0, 0, 0.035); + --uiws-input-bg: #ffffff; + --uiws-shadow: 0 8px 30px -12px rgba(40, 55, 80, 0.18); +} + +/* UIWS 화면 컨테이너 — 토큰 기반 기본 타이포/배경 */ +.uiws-scope { + color: var(--uiws-text); +} +.uiws-scope a { color: var(--uiws-primary); }