Files
kmusical-manage-front/src/components/dialog/AssignCalendarDialog.tsx

508 lines
24 KiB
TypeScript

"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, UserFull | UserCompact>
): 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<string, number>;
reviewSlots: PerformanceReviewSlot[];
reviewers: UserFull[];
}>) {
const [visibleMonth, setVisibleMonth] = useState(() => new Date());
const [performanceSearch, setPerformanceSearch] = useState("");
const [selectedPerformanceIds, setSelectedPerformanceIds] = useState<Set<string>>(new Set());
const [selectedReviewerIds, setSelectedReviewerIds] = useState<string[]>([]);
const [selectedDetailPerformanceId, setSelectedDetailPerformanceId] = useState<string | null>(null);
const [activeDetailTab, setActiveDetailTab] = useState<DetailTab>("application");
const [expandedDayKey, setExpandedDayKey] = useState<string | null>(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<string, MonitoringApplyUser[]>();
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<string, UserFull | UserCompact>([
...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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex h-[min(760px,85vh)] max-h-[85vh] flex-col overflow-hidden sm:max-w-[min(112rem,95vw)]">
<DialogHeader className="shrink-0">
<DialogTitle>배정 현황 캘린더</DialogTitle>
</DialogHeader>
<div className={`grid min-h-0 flex-1 gap-4 overflow-hidden ${detailPerformance ? "lg:grid-cols-[300px_1fr_340px]" : "lg:grid-cols-[300px_1fr]"}`}>
<section className="flex min-h-0 flex-col gap-2 overflow-hidden rounded-md border p-3">
<Input
value={performanceSearch}
onChange={(event) => setPerformanceSearch(event.target.value)}
placeholder="작품명 검색"
/>
<label className="flex items-center gap-2 border-b pb-2 text-sm font-medium">
<Checkbox checked={allSelected} onCheckedChange={toggleSelectAll} />
전체 선택
</label>
<div className="min-h-0 flex-1 space-y-1 overflow-y-auto">
{searchedPerformances.length === 0 ? (
<div className="py-4 text-center text-sm text-muted-foreground">검색 결과가 없습니다.</div>
) : searchedPerformances.map((performance) => (
<label key={performance.performanceId} className="flex items-start gap-2 rounded px-1 py-1 text-sm hover:bg-muted">
<Checkbox
checked={selectedPerformanceIds.has(performance.performanceId)}
onCheckedChange={() => togglePerformance(performance.performanceId)}
/>
<span
className={`mt-1 size-2.5 shrink-0 rounded-full ${PERFORMANCE_DOT_COLOR_CLASSES[getPerformanceColorSlot(performance.performanceId, orderedPerformanceIds)]}`}
aria-hidden="true"
/>
<span className="min-w-0">
<span className="block truncate" title={performance.performanceName}>{performance.performanceName}</span>
<span className="block truncate text-xs text-muted-foreground">{performance.performanceId}</span>
</span>
</label>
))}
</div>
</section>
<section className="flex min-h-0 flex-col overflow-hidden rounded-md border">
<div className="flex shrink-0 items-center justify-between gap-2 border-b p-3">
<div className="flex items-center gap-1">
<Button type="button" variant="outline" size="icon-sm" aria-label="이전 달" onClick={() => changeMonth(-1)}>
<ChevronLeft className="h-4 w-4" />
</Button>
<div className="w-28 text-center font-semibold">{visibleMonth.getFullYear()}년 {visibleMonth.getMonth() + 1}월</div>
<Button type="button" variant="outline" size="icon-sm" aria-label="다음 달" onClick={() => changeMonth(1)}>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
{visiblePerformances.length === 0 && (
<div className="min-w-0 flex-1 truncate text-center text-sm text-muted-foreground">
{selectedPerformanceIds.size === 0 ? "선택된 작품이 없습니다." : "조건에 맞는 배정 일정이 없습니다."}
</div>
)}
<KriMultiSelect<UserFull>
items={reviewers}
value={selectedReviewerIds}
onChange={setSelectedReviewerIds}
getValue={(user) => user.userId}
getLabel={(user) => user.userName || user.userId}
placeholder="전체 평가위원"
widthClassName="w-64"
/>
</div>
<TooltipProvider delayDuration={200}>
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
<div className="flex shrink-0">
{WEEKDAY_LABELS.map((label, index) => (
<div key={label} className={`flex-1 border-b bg-muted px-2 py-1 text-center text-xs font-medium ${getWeekdayTextClassName(index) || "text-muted-foreground"}`}>{label}</div>
))}
</div>
{chunkIntoWeeks(monthDays).map((week) => (
<div key={week[0].dateKey} className="flex">
{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 (
<div
key={day.dateKey}
className={`min-h-24 flex-1 border-b border-r p-1 ${day.isCurrentMonth ? "" : "bg-muted/30 text-muted-foreground"}`}
>
<div className={`mb-1 text-xs ${day.isToday ? "font-bold text-primary" : weekdayClassName}`}>{day.date.getDate()}</div>
<div className="space-y-1">
{visibleBadges.map((performance) => (
<PerformanceBadge
key={performance.performanceId}
performance={performance}
badgeInfo={getPerformanceBadgeInfo(performance, applyCountMap, reviewSlots)}
colorClassName={PERFORMANCE_BADGE_COLOR_CLASSES[getPerformanceColorSlot(performance.performanceId, orderedPerformanceIds)]}
reviewSlots={reviewSlots}
userById={userById}
applyUsers={applyUsersByPerformanceId.get(performance.performanceId) ?? []}
onClick={() => setSelectedDetailPerformanceId(performance.performanceId)}
/>
))}
{overflowCount > 0 && (
<Popover
open={expandedDayKey === day.dateKey}
onOpenChange={(next) => setExpandedDayKey(next ? day.dateKey : null)}
>
<PopoverTrigger asChild>
<button type="button" className="w-full rounded px-1 py-0.5 text-left text-xs text-primary hover:underline">
외 {overflowCount}건
</button>
</PopoverTrigger>
<PopoverContent className="w-64 space-y-1">
{dayPerformances.map((performance) => (
<PerformanceBadge
key={performance.performanceId}
performance={performance}
badgeInfo={getPerformanceBadgeInfo(performance, applyCountMap, reviewSlots)}
colorClassName={PERFORMANCE_BADGE_COLOR_CLASSES[getPerformanceColorSlot(performance.performanceId, orderedPerformanceIds)]}
reviewSlots={reviewSlots}
userById={userById}
applyUsers={applyUsersByPerformanceId.get(performance.performanceId) ?? []}
onClick={() => {
setExpandedDayKey(null);
setSelectedDetailPerformanceId(performance.performanceId);
}}
/>
))}
</PopoverContent>
</Popover>
)}
</div>
</div>
);
})}
</div>
))}
</div>
</TooltipProvider>
</section>
{detailPerformance && (
<section className="flex min-h-0 flex-col overflow-hidden rounded-md border">
<div className="flex shrink-0 items-start justify-between gap-2 border-b p-3">
<div className="min-w-0">
<div className="truncate font-semibold" title={detailPerformance.performanceName}>{detailPerformance.performanceName}</div>
<div className="text-xs text-muted-foreground">
{detailPerformance.performanceMonitoringSchedule?.monitoringDate || "-"}
</div>
</div>
<Button type="button" variant="ghost" size="sm" onClick={closeDetail}>닫기</Button>
</div>
<div role="tablist" aria-label="배정 상세" className="flex shrink-0 gap-1 border-b px-2">
{DETAIL_TABS.map((tab) => (
<button
key={tab.id}
type="button"
role="tab"
aria-selected={activeDetailTab === tab.id}
className={`cursor-pointer border-b-2 px-3 py-2 text-sm font-medium ${activeDetailTab === tab.id ? "border-primary text-foreground" : "border-transparent text-muted-foreground"}`}
onClick={() => setActiveDetailTab(tab.id)}
>
{tab.label}
</button>
))}
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-3">
{activeDetailTab === "application" && (
isAllApplyLoading ? (
<div className="py-6 text-center text-sm text-muted-foreground">조회 중입니다.</div>
) : isAllApplyError ? (
<div className="space-y-2 py-6 text-center text-sm text-muted-foreground">
<div>신청자 정보를 불러오지 못했습니다.</div>
<Button type="button" variant="outline" size="sm" onClick={() => refetchAllApplyUsers()}>다시 시도</Button>
</div>
) : detailApplyUsers.length === 0 ? (
<div className="py-6 text-center text-sm text-muted-foreground">신청자가 없습니다.</div>
) : (
<div className="space-y-2">
{detailApplyUsers.map((applyUser) => (
<div key={applyUser.userId} className="flex items-center justify-between gap-2 rounded border p-2 text-sm">
<div className="min-w-0">
<div className="truncate font-medium">{applyUser.user.userName || applyUser.userId}</div>
<div className="truncate text-xs text-muted-foreground">{applyUser.userId}</div>
<div className="truncate text-xs text-muted-foreground">
{getDetailValue(applyUser.user.userDetail, "userArea", "-")} · {getDetailValue(applyUser.user.userDetail, "userTel", "-")}
</div>
</div>
{assignedUserIds.has(applyUser.userId) ? (
<StatusPill variant="done">확정</StatusPill>
) : (
<StatusPill variant="pending">신청</StatusPill>
)}
</div>
))}
</div>
)
)}
{(activeDetailTab === "monitoring" || activeDetailTab === "consulting") && (
<ReviewSlotList
reviewType={activeDetailTab === "monitoring" ? REVIEW_TYPE.MONITORING : REVIEW_TYPE.CONSULTING}
reviewSlots={reviewSlots}
performance={detailPerformance}
userById={userById}
/>
)}
</div>
</section>
)}
</div>
</DialogContent>
</Dialog>
);
}
function PerformanceBadge({
performance,
badgeInfo,
colorClassName,
reviewSlots,
userById,
applyUsers,
onClick,
}: Readonly<{
performance: PerformanceFull;
badgeInfo: PerformanceBadgeInfo;
colorClassName: string;
reviewSlots: PerformanceReviewSlot[];
userById: Map<string, UserFull | UserCompact>;
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 (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={onClick}
aria-label={accessibleLabel}
className={`w-full rounded border px-1.5 py-1 text-left text-xs leading-tight transition-opacity hover:opacity-80 ${colorClassName}`}
>
<div className="line-clamp-2 font-medium">{performance.performanceName}</div>
<div>
{badgeInfo.isMatchingComplete ? (
<span className="inline-flex items-center gap-1"><Check className="h-3 w-3" />매칭 완료</span>
) : (
`${badgeInfo.applyCount}명 신청 / ${badgeInfo.assignCount}명 배정`
)}
</div>
</button>
</TooltipTrigger>
<TooltipContent side="right" className="w-64 space-y-1.5 text-left">
<div className="font-semibold">{performance.performanceName}</div>
<div>
<div className="font-medium text-muted-foreground">신청자</div>
<div>{applicantNames.length > 0 ? applicantNames.join(", ") : "없음"}</div>
</div>
<div>
<div className="font-medium text-muted-foreground">현장 모니터링 배정</div>
<div>{monitoringNames.length > 0 ? monitoringNames.join(", ") : "없음"}</div>
</div>
<div>
<div className="font-medium text-muted-foreground">컨설팅 배정</div>
<div>{consultingNames.length > 0 ? consultingNames.join(", ") : "없음"}</div>
</div>
</TooltipContent>
</Tooltip>
);
}
function ReviewSlotList({
reviewType,
reviewSlots,
performance,
userById,
}: Readonly<{
reviewType: ReviewType;
reviewSlots: PerformanceReviewSlot[];
performance: PerformanceFull;
userById: Map<string, UserFull | UserCompact>;
}>) {
const slots = reviewSlots.filter((slot) => slot.reviewType === reviewType).sort((a, b) => a.reviewSlot - b.reviewSlot);
if (slots.length === 0) {
return <div className="py-6 text-center text-sm text-muted-foreground">등록된 평가 슬롯이 없습니다.</div>;
}
return (
<div className="space-y-2">
{slots.map((slot) => {
const assign = performance.performanceAssignList.find((item) => item.reviewSlot === slot.reviewSlot);
const user = assign ? userById.get(assign.assignUser) : undefined;
return (
<div key={slot.reviewSlot} className="space-y-1 rounded border p-2 text-sm">
<div className="flex items-center justify-between gap-2">
<span className="font-medium">{slot.reviewLabel}</span>
{assign ? <StatusPill variant="done">배정</StatusPill> : <StatusPill variant="danger">미배정</StatusPill>}
</div>
{assign && (
<div className="text-xs text-muted-foreground">
<div>{user?.userName || assign.assignUser} ({assign.assignUser})</div>
<div>{getDetailValue(user?.userDetail, "userTel", "-")}</div>
</div>
)}
<div className="text-xs text-muted-foreground">
{performance.performanceMonitoringSchedule?.monitoringDate || "-"} {performance.performanceMonitoringSchedule?.monitoringTimeInfo || ""}
</div>
<div className="text-xs text-muted-foreground">{performance.performanceMonitoringSchedule?.monitoringAddress || "-"}</div>
</div>
);
})}
</div>
);
}