"use client"; import {useEffect, useState} from "react"; import {Check, ChevronLeft, ChevronRight} from "lucide-react"; import {Button} from "@/components/ui/button"; import {Input} from "@/components/ui/input"; import {Checkbox} from "@/components/ui/checkbox"; import {Dialog, DialogContent, DialogHeader, DialogTitle} from "@/components/ui/dialog"; import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover"; import {Tooltip, TooltipContent, TooltipProvider, TooltipTrigger} from "@/components/ui/tooltip"; import {KriMultiSelect} from "@/components/common/KriAutoComplete"; import {StatusPill} from "@/components/kmusical/StatusPill"; import {useAllMonitoringApplyUsersQuery} from "@/query/assign"; import {getDetailValue, includesText} from "@/lib/kmusical/view"; import { buildMonthGrid, chunkIntoWeeks, getPerformanceBadgeInfo, getPerformanceColorSlot, getVisiblePerformances, groupPerformancesByDate, WEEKDAY_LABELS, type PerformanceBadgeInfo, } from "@/lib/kmusical/assignment-calendar"; import { REVIEW_TYPE, type MonitoringApplyUser, type PerformanceFull, type PerformanceReviewSlot, type ReviewType, type UserCompact, type UserFull, } from "@/types/kmusical"; type DetailTab = "application" | "monitoring" | "consulting"; const DETAIL_TABS: ReadonlyArray<{id: DetailTab; label: string}> = [ {id: "application", label: "신청"}, {id: "monitoring", label: "현장 모니터링"}, {id: "consulting", label: "컨설팅"}, ]; const MAX_BADGES_PER_DAY = 3; const PERFORMANCE_BADGE_COLOR_CLASSES = [ "border-[var(--series-1)] bg-[var(--series-1-bg)] text-[var(--series-1-fg)]", "border-[var(--series-2)] bg-[var(--series-2-bg)] text-[var(--series-2-fg)]", "border-[var(--series-3)] bg-[var(--series-3-bg)] text-[var(--series-3-fg)]", "border-[var(--series-4)] bg-[var(--series-4-bg)] text-[var(--series-4-fg)]", "border-[var(--series-5)] bg-[var(--series-5-bg)] text-[var(--series-5-fg)]", "border-[var(--series-6)] bg-[var(--series-6-bg)] text-[var(--series-6-fg)]", "border-[var(--series-7)] bg-[var(--series-7-bg)] text-[var(--series-7-fg)]", "border-[var(--series-8)] bg-[var(--series-8-bg)] text-[var(--series-8-fg)]", ] as const; const PERFORMANCE_DOT_COLOR_CLASSES = [ "bg-[var(--series-1)]", "bg-[var(--series-2)]", "bg-[var(--series-3)]", "bg-[var(--series-4)]", "bg-[var(--series-5)]", "bg-[var(--series-6)]", "bg-[var(--series-7)]", "bg-[var(--series-8)]", ] as const; const getWeekdayTextClassName = (dayOfWeek: number) => { if (dayOfWeek === 0) return "text-[#e34948] dark:text-[#e66767]"; if (dayOfWeek === 6) return "text-[#2a78d6] dark:text-[#3987e5]"; return ""; }; const getAssignedUserNames = ( performance: PerformanceFull, reviewSlots: PerformanceReviewSlot[], reviewType: ReviewType, userById: Map ): string[] => { const slotNumbers = new Set(reviewSlots.filter((slot) => slot.reviewType === reviewType).map((slot) => slot.reviewSlot)); return performance.performanceAssignList .filter((assign) => slotNumbers.has(assign.reviewSlot)) .map((assign) => userById.get(assign.assignUser)?.userName || assign.assignUser); }; export function AssignCalendarDialog({ open, onOpenChange, performances, applyCountMap, reviewSlots, reviewers, }: Readonly<{ open: boolean; onOpenChange: (open: boolean) => void; performances: PerformanceFull[]; applyCountMap: Map; reviewSlots: PerformanceReviewSlot[]; reviewers: UserFull[]; }>) { const [visibleMonth, setVisibleMonth] = useState(() => new Date()); const [performanceSearch, setPerformanceSearch] = useState(""); const [selectedPerformanceIds, setSelectedPerformanceIds] = useState>(new Set()); const [selectedReviewerIds, setSelectedReviewerIds] = useState([]); const [selectedDetailPerformanceId, setSelectedDetailPerformanceId] = useState(null); const [activeDetailTab, setActiveDetailTab] = useState("application"); const [expandedDayKey, setExpandedDayKey] = useState(null); useEffect(() => { if (!open) return; setPerformanceSearch(""); setSelectedReviewerIds([]); setSelectedDetailPerformanceId(null); setActiveDetailTab("application"); setVisibleMonth(new Date()); setSelectedPerformanceIds(new Set(performances.map((performance) => performance.performanceId))); // 다이얼로그를 다시 열 때마다 필터를 초기화한다. open 시점의 공연 목록만 반영하면 되므로 performances는 의도적으로 의존성에서 제외한다. // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]); useEffect(() => { if (!open) return; setSelectedPerformanceIds((current) => { const validIds = new Set(performances.map((performance) => performance.performanceId)); const next = new Set(Array.from(current).filter((id) => validIds.has(id))); return next.size === current.size ? current : next; }); }, [open, performances]); const visiblePerformances = getVisiblePerformances(performances, selectedPerformanceIds, selectedReviewerIds); useEffect(() => { if (selectedDetailPerformanceId == null) return; const stillVisible = visiblePerformances.some((performance) => performance.performanceId === selectedDetailPerformanceId); if (!stillVisible) setSelectedDetailPerformanceId(null); }, [visiblePerformances, selectedDetailPerformanceId]); const performancesByDate = groupPerformancesByDate(visiblePerformances); const monthDays = buildMonthGrid(visibleMonth); const detailPerformance = performances.find((performance) => performance.performanceId === selectedDetailPerformanceId) ?? null; const { data: allApplyUsers = [], isLoading: isAllApplyLoading, isError: isAllApplyError, refetch: refetchAllApplyUsers, } = useAllMonitoringApplyUsersQuery(open); const applyUsersByPerformanceId = new Map(); for (const applyUser of allApplyUsers) { const list = applyUsersByPerformanceId.get(applyUser.performanceId) ?? []; list.push(applyUser); applyUsersByPerformanceId.set(applyUser.performanceId, list); } const detailApplyUsers = detailPerformance ? applyUsersByPerformanceId.get(detailPerformance.performanceId) ?? [] : []; const orderedPerformanceIds = performances.map((performance) => performance.performanceId); const searchedPerformances = performances.filter((performance) => includesText(performance.performanceName, performanceSearch)); const allSelected = performances.length > 0 && selectedPerformanceIds.size === performances.length; const togglePerformance = (performanceId: string) => { setSelectedPerformanceIds((current) => { const next = new Set(current); if (next.has(performanceId)) next.delete(performanceId); else next.add(performanceId); return next; }); }; const toggleSelectAll = () => { setSelectedPerformanceIds(allSelected ? new Set() : new Set(performances.map((performance) => performance.performanceId))); }; const changeMonth = (offset: number) => { setVisibleMonth((current) => new Date(current.getFullYear(), current.getMonth() + offset, 1)); }; const closeDetail = () => setSelectedDetailPerformanceId(null); const userById = new Map([ ...reviewers.map((user) => [user.userId, user] as const), ...detailApplyUsers.map((item) => [item.userId, item.user] as const), ]); const assignedUserIds = new Set((detailPerformance?.performanceAssignList ?? []).map((assign) => assign.assignUser)); return ( 배정 현황 캘린더
setPerformanceSearch(event.target.value)} placeholder="작품명 검색" />
{searchedPerformances.length === 0 ? (
검색 결과가 없습니다.
) : searchedPerformances.map((performance) => ( ))}
{visibleMonth.getFullYear()}년 {visibleMonth.getMonth() + 1}월
{visiblePerformances.length === 0 && (
{selectedPerformanceIds.size === 0 ? "선택된 작품이 없습니다." : "조건에 맞는 배정 일정이 없습니다."}
)} items={reviewers} value={selectedReviewerIds} onChange={setSelectedReviewerIds} getValue={(user) => user.userId} getLabel={(user) => user.userName || user.userId} placeholder="전체 평가위원" widthClassName="w-64" />
{WEEKDAY_LABELS.map((label, index) => (
{label}
))}
{chunkIntoWeeks(monthDays).map((week) => (
{week.map((day) => { const dayPerformances = performancesByDate.get(day.dateKey) ?? []; const visibleBadges = dayPerformances.slice(0, MAX_BADGES_PER_DAY); const overflowCount = dayPerformances.length - visibleBadges.length; const weekdayClassName = getWeekdayTextClassName(day.date.getDay()); return (
{day.date.getDate()}
{visibleBadges.map((performance) => ( setSelectedDetailPerformanceId(performance.performanceId)} /> ))} {overflowCount > 0 && ( setExpandedDayKey(next ? day.dateKey : null)} > {dayPerformances.map((performance) => ( { setExpandedDayKey(null); setSelectedDetailPerformanceId(performance.performanceId); }} /> ))} )}
); })}
))}
{detailPerformance && (
{detailPerformance.performanceName}
{detailPerformance.performanceMonitoringSchedule?.monitoringDate || "-"}
{DETAIL_TABS.map((tab) => ( ))}
{activeDetailTab === "application" && ( isAllApplyLoading ? (
조회 중입니다.
) : isAllApplyError ? (
신청자 정보를 불러오지 못했습니다.
) : detailApplyUsers.length === 0 ? (
신청자가 없습니다.
) : (
{detailApplyUsers.map((applyUser) => (
{applyUser.user.userName || applyUser.userId}
{applyUser.userId}
{getDetailValue(applyUser.user.userDetail, "userArea", "-")} · {getDetailValue(applyUser.user.userDetail, "userTel", "-")}
{assignedUserIds.has(applyUser.userId) ? ( 확정 ) : ( 신청 )}
))}
) )} {(activeDetailTab === "monitoring" || activeDetailTab === "consulting") && ( )}
)}
); } function PerformanceBadge({ performance, badgeInfo, colorClassName, reviewSlots, userById, applyUsers, onClick, }: Readonly<{ performance: PerformanceFull; badgeInfo: PerformanceBadgeInfo; colorClassName: string; reviewSlots: PerformanceReviewSlot[]; userById: Map; applyUsers: MonitoringApplyUser[]; onClick: () => void; }>) { const accessibleLabel = badgeInfo.isMatchingComplete ? `${performance.performanceName}, 매칭 완료, 상세 보기` : `${performance.performanceName}, ${badgeInfo.applyCount}명 신청, ${badgeInfo.assignCount}명 배정, 상세 보기`; const monitoringNames = getAssignedUserNames(performance, reviewSlots, REVIEW_TYPE.MONITORING, userById); const consultingNames = getAssignedUserNames(performance, reviewSlots, REVIEW_TYPE.CONSULTING, userById); const applicantNames = applyUsers.map((applyUser) => applyUser.user.userName || applyUser.userId); return (
{performance.performanceName}
신청자
{applicantNames.length > 0 ? applicantNames.join(", ") : "없음"}
현장 모니터링 배정
{monitoringNames.length > 0 ? monitoringNames.join(", ") : "없음"}
컨설팅 배정
{consultingNames.length > 0 ? consultingNames.join(", ") : "없음"}
); } function ReviewSlotList({ reviewType, reviewSlots, performance, userById, }: Readonly<{ reviewType: ReviewType; reviewSlots: PerformanceReviewSlot[]; performance: PerformanceFull; userById: Map; }>) { const slots = reviewSlots.filter((slot) => slot.reviewType === reviewType).sort((a, b) => a.reviewSlot - b.reviewSlot); if (slots.length === 0) { return
등록된 평가 슬롯이 없습니다.
; } return (
{slots.map((slot) => { const assign = performance.performanceAssignList.find((item) => item.reviewSlot === slot.reviewSlot); const user = assign ? userById.get(assign.assignUser) : undefined; return (
{slot.reviewLabel} {assign ? 배정 : 미배정}
{assign && (
{user?.userName || assign.assignUser} ({assign.assignUser})
{getDetailValue(user?.userDetail, "userTel", "-")}
)}
{performance.performanceMonitoringSchedule?.monitoringDate || "-"} {performance.performanceMonitoringSchedule?.monitoringTimeInfo || ""}
{performance.performanceMonitoringSchedule?.monitoringAddress || "-"}
); })}
); }