260914_01_ENH: 1차 완성

This commit is contained in:
2026-09-14 15:07:40 +09:00
parent a6642c9a00
commit f1d21d3711
67 changed files with 5595 additions and 148 deletions

View File

@@ -0,0 +1,508 @@
"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>
<KriMultiSelect<UserFull>
items={reviewers}
value={selectedReviewerIds}
onChange={setSelectedReviewerIds}
getValue={(user) => user.userId}
getLabel={(user) => user.userName || user.userId}
placeholder="전체 평가위원"
widthClassName="w-64"
/>
</div>
{selectedPerformanceIds.size === 0 ? (
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">선택된 작품이 없습니다.</div>
) : visiblePerformances.length === 0 ? (
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">조건에 맞는 배정 일정이 없습니다.</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>
);
}

View File

@@ -0,0 +1,311 @@
"use client";
import {useEffect, useMemo, useState} from "react";
import {Save, Send} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Checkbox} from "@/components/ui/checkbox";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {DataTable} from "@/components/data-table/DataTable";
import type {DataTableColumn} from "@/components/data-table/DataTable.type";
import {StatusPill} from "@/components/kmusical/StatusPill";
import type {Code, MonitoringApplyUser, PerformanceFull, PerformanceReviewSlot, ReviewType, UserCompact} from "@/types/kmusical";
import type {CodeGroup} from "@/query/code";
import {getCodeLabel, getDetailValue} from "@/lib/kmusical/view";
import {getReviewTypeLabel} from "@/lib/kmusical/performance-status";
import {PERFORMANCE_FIELD_LABELS, USER_FIELD_LABELS} from "@/lib/kmusical/field-labels";
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
type AssignmentUserRow = Pick<MonitoringApplyUser, "userId" | "user">;
export type AssignmentSelection = {
reviewSlot: number;
userId: string;
};
export function AssignMonitoringDialog({
open,
onOpenChange,
selected,
codes,
reviewSlots,
applyUsers,
users,
isSaving = false,
onSaveAssign,
onOpenAssignSms,
onOpenNormalSms,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
selected: PerformanceFull | null;
codes: CodeMap;
reviewSlots: PerformanceReviewSlot[];
applyUsers: MonitoringApplyUser[];
users: UserCompact[];
isSaving?: boolean;
onSaveAssign: (reviewSlotNumbers: number[], assignments: AssignmentSelection[]) => Promise<void>;
onOpenAssignSms: (reviewSlotNumbers: number[], assignments: AssignmentSelection[], smsUserIds: string[]) => void;
onOpenNormalSms: (smsUserIds: string[]) => void;
}>) {
const reviewTypes = useMemo(
() => Array.from(new Set(reviewSlots.map((slot) => slot.reviewType))),
[reviewSlots]
);
const [activeReviewType, setActiveReviewType] = useState<ReviewType | null>(reviewTypes[0] ?? null);
const [slotUsers, setSlotUsers] = useState<Record<number, string>>({});
useEffect(() => {
if (!open) return;
setActiveReviewType(reviewTypes[0] ?? null);
setSlotUsers(Object.fromEntries(
(selected?.performanceAssignList ?? []).map((assign) => [assign.reviewSlot, assign.assignUser])
));
}, [open, reviewTypes, selected]);
const activeSlots = reviewSlots
.filter((slot) => slot.reviewType === activeReviewType)
.sort((a, b) => a.reviewSlot - b.reviewSlot);
const activeSlotNumbers = activeSlots.map((slot) => slot.reviewSlot);
const activeSlotNumberSet = new Set(activeSlotNumbers);
const reviewBySlot = new Map(
Object.values(selected?.performanceReviewMap ?? {}).map((review) => [review.reviewSlot, review])
);
const slotByUserId = new Map(
Object.entries(slotUsers).map(([reviewSlot, userId]) => [userId, Number(reviewSlot)])
);
const checkedUserIds = activeSlots.flatMap((slot) => slotUsers[slot.reviewSlot] ? [slotUsers[slot.reviewSlot]] : []);
const savedUserIds = new Set(
(selected?.performanceAssignList ?? [])
.filter((assign) => activeSlotNumberSet.has(assign.reviewSlot))
.map((assign) => assign.assignUser)
);
const activeAssignments = activeSlots.flatMap((slot) => {
const userId = slotUsers[slot.reviewSlot];
return userId ? [{reviewSlot: slot.reviewSlot, userId}] : [];
});
const applicantIds = new Set(applyUsers.map((item) => item.userId));
const getUserGroup = (userId: string) => savedUserIds.has(userId) ? 0 : applicantIds.has(userId) ? 1 : 2;
const renderUserStatus = (userId: string) => {
if (savedUserIds.has(userId)) return <StatusPill variant="done">확정</StatusPill>;
const assignedSlot = slotByUserId.get(userId);
if (assignedSlot != null && !activeSlotNumberSet.has(assignedSlot)) {
return <StatusPill tooltip="다른 직무에 배정된 사용자입니다.">타직무</StatusPill>;
}
if (applicantIds.has(userId)) return <StatusPill variant="pending">신청</StatusPill>;
return null;
};
const sortedUsers: AssignmentUserRow[] = users
.map((user) => ({userId: user.userId, user}))
.sort((a, b) => getUserGroup(a.userId) - getUserGroup(b.userId)
|| (a.user.userName || a.userId).localeCompare(b.user.userName || b.userId, "ko")
|| a.userId.localeCompare(b.userId, "ko"));
const toggleAssignUser = (applyUser: AssignmentUserRow) => {
if (isSaving || activeReviewType == null) return;
const assignedSlot = slotByUserId.get(applyUser.userId);
if (assignedSlot != null) {
if (!activeSlotNumberSet.has(assignedSlot)) {
alert("동일한 공연에서는 한 신청자를 한 번만 배정할 수 있습니다.");
return;
}
if (reviewBySlot.has(assignedSlot)) {
alert("평가가 등록된 슬롯의 담당자는 해제할 수 없습니다.");
return;
}
setSlotUsers((current) => {
const next = {...current};
delete next[assignedSlot];
return next;
});
return;
}
const emptySlot = activeSlots.find((slot) => !slotUsers[slot.reviewSlot]);
if (!emptySlot) {
alert("선택한 리뷰 타입에 배정 가능한 슬롯이 없습니다.");
return;
}
setSlotUsers((current) => ({...current, [emptySlot.reviewSlot]: applyUser.userId}));
};
const columns = useMemo<DataTableColumn<AssignmentUserRow>[]>(() => [
{
id: "assign",
header: "선택",
size: 50,
enableSorting: false,
cell: ({row}) => {
const userId = row.original.userId;
const assignedSlot = slotByUserId.get(userId);
const checked = assignedSlot != null && activeSlotNumberSet.has(assignedSlot);
const locked = assignedSlot != null && reviewBySlot.has(assignedSlot);
const noEmptySlot = !checked && activeSlots.every((slot) => Boolean(slotUsers[slot.reviewSlot]));
const assignedToAnotherType = assignedSlot != null && !activeSlotNumberSet.has(assignedSlot);
return (
<Checkbox
checked={checked}
disabled={isSaving || locked || noEmptySlot || assignedToAnotherType}
aria-label={`${row.original.user.userName || userId} 선택`}
onCheckedChange={() => toggleAssignUser(row.original)}
onClick={(event) => event.stopPropagation()}
/>
);
},
},
{
id: "user",
header: USER_FIELD_LABELS.userName,
size: 140,
cell: ({row}) => (
<div className="min-w-0 text-center">
<div className="truncate font-semibold">{row.original.user.userName || row.original.userId}</div>
<div className="truncate text-xs text-muted-foreground">{row.original.userId}</div>
</div>
),
},
{
id: "area",
header: USER_FIELD_LABELS.userArea,
size: 80,
cell: ({row}) => (
<div className="truncate">
{getCodeLabel(codes, "area", getDetailValue(row.original.user.userDetail, "userArea")) || "-"}
</div>
),
},
{
id: "tel",
header: USER_FIELD_LABELS.userTel,
size: 130,
cell: ({row}) => <div className="truncate">{getDetailValue(row.original.user.userDetail, "userTel", "-")}</div>,
},
{
id: "status",
header: "상태",
size: 75,
cell: ({row}) => renderUserStatus(row.original.userId),
},
], [
activeSlotNumberSet,
activeSlots,
applicantIds,
codes,
isSaving,
reviewBySlot,
savedUserIds,
slotByUserId,
slotUsers,
]);
const changeReviewType = (reviewType: ReviewType) => {
setActiveReviewType(reviewType);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex h-[min(680px,85vh)] max-h-[85vh] flex-col overflow-hidden sm:max-w-6xl">
<DialogHeader className="shrink-0">
<DialogTitle>평가 담당자 배정</DialogTitle>
</DialogHeader>
<div className="grid min-h-0 flex-1 gap-4 lg:grid-cols-[0.85fr_1.15fr]">
<section className="min-h-0 overflow-y-auto rounded-md border">
<div className="border-b bg-muted px-3 py-2 font-semibold">공연 기본 정보</div>
<table className="w-full table-fixed border-collapse text-sm">
<tbody>
{[
[PERFORMANCE_FIELD_LABELS.performanceId, selected?.performanceId],
[PERFORMANCE_FIELD_LABELS.businessType, getCodeLabel(codes, "business_type", selected?.businessType)],
[PERFORMANCE_FIELD_LABELS.performanceArea, getCodeLabel(codes, "area", selected?.performanceArea)],
[PERFORMANCE_FIELD_LABELS.artistName, selected?.artistName],
[PERFORMANCE_FIELD_LABELS.performanceName, selected?.performanceName],
[PERFORMANCE_FIELD_LABELS.performanceDtInfo, selected?.performanceDtInfo],
[PERFORMANCE_FIELD_LABELS.monitoringDate, selected?.performanceMonitoringSchedule?.monitoringDate],
[PERFORMANCE_FIELD_LABELS.monitoringTimeInfo, selected?.performanceMonitoringSchedule?.monitoringTimeInfo],
[PERFORMANCE_FIELD_LABELS.monitoringAddress, selected?.performanceMonitoringSchedule?.monitoringAddress],
[PERFORMANCE_FIELD_LABELS.ticketReservationStatus, getCodeLabel(codes, "ticket_reservation_status", selected?.ticketReservationStatus)],
[PERFORMANCE_FIELD_LABELS.ticketReservationMemo, selected?.ticketReservationMemo],
].map(([label, value]) => (
<tr key={String(label)}>
<th className="w-32 border-b bg-muted/60 px-3 py-2 text-left align-top font-medium">{label}</th>
<td className="break-words border-b px-3 py-2">{value || "-"}</td>
</tr>
))}
</tbody>
</table>
</section>
<section className="flex min-h-0 min-w-0 flex-col rounded-md border p-3">
<div role="tablist" aria-label="평가 타입" className="flex shrink-0 gap-1 border-b">
{reviewTypes.map((reviewType) => (
<button
key={reviewType}
type="button"
role="tab"
aria-selected={activeReviewType === reviewType}
className={`cursor-pointer border-b-2 px-5 py-2 text-sm font-medium ${activeReviewType === reviewType ? "border-primary text-foreground" : "border-transparent text-muted-foreground"}`}
onClick={() => changeReviewType(reviewType)}
>
{getReviewTypeLabel(reviewType)}
</button>
))}
</div>
{activeSlots.length > 0 ? (
<>
<div className="my-3 grid shrink-0 grid-cols-2 overflow-hidden rounded-xl border text-center text-sm">
<div className="p-2.5">
<div className="text-muted-foreground">신청</div>
<div className="font-semibold">{applyUsers.length}</div>
</div>
<div className="border-l p-2.5">
<div className="text-muted-foreground">확정</div>
<div className="font-semibold">{savedUserIds.size}</div>
</div>
</div>
<div className="min-h-0 flex-1 overflow-hidden">
<DataTable
columns={columns}
data={sortedUsers}
getRowId={(row) => row.userId}
selectMode="click-event"
onRowClick={toggleAssignUser}
className="[&_table]:min-w-0 [&_table]:table-fixed"
headerCellClassName="text-center"
bodyCellClassName="text-center"
bodyRowClassName="[&>td]:py-2"
defaultPageSize={Math.max(sortedUsers.length, 1)}
pageSizeOptions={[Math.max(sortedUsers.length, 1)]}
disablePagination
maxBodyHeight="calc(min(680px,85vh) - 255px)"
emptyText="조회된 사용자가 없습니다."
/>
</div>
</>
) : (
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">등록된 평가 슬롯이 없습니다.</div>
)}
</section>
</div>
<DialogFooter className="shrink-0">
<Button type="button" variant="outline" disabled={!selected || isSaving} onClick={() => onSaveAssign(activeSlotNumbers, activeAssignments)}>
<Save className="h-4 w-4" /> 저장
</Button>
<Button type="button" variant="outline" disabled={checkedUserIds.length === 0 || isSaving} onClick={() => onOpenAssignSms(activeSlotNumbers, activeAssignments, checkedUserIds)}>
<Send className="h-4 w-4" /> 확정 문자 발송
</Button>
<Button type="button" variant="outline" disabled={checkedUserIds.length === 0 || isSaving} onClick={() => onOpenNormalSms(checkedUserIds)}>
<Send className="h-4 w-4" /> 문자 발송
</Button>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,334 @@
"use client";
import {useEffect, useRef, useState} from "react";
import {Edit, Paperclip, RotateCcw, Save, Send, X} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle
} from "@/components/ui/dialog";
import {KriEditor, type KriEditorCommand} from "@/components/kri-editor";
import {useAuth} from "@/hooks/useAuth";
import {buildUserMsgParam} from "@/lib/kmusical/notification";
import {getDetailValue} from "@/lib/kmusical/view";
import {getSendParamLabel} from "@/lib/kmusical/field-labels";
import {downloadBlob} from "@/lib/kmusical/file";
import {SEND_TYPE, type Template} from "@/types/notification";
import type {UserCompact} from "@/types/kmusical";
import {
NOTIFICATION_REQUEST_SERVICE,
useDownloadEmailAttachmentMutation,
useNotificationTemplatesQuery,
useSaveEmailTemplateMutation,
useSendEmailBulkMutation,
useUploadEmailImageMutation,
} from "@/query/notification";
import {cn} from "@/lib/utils";
import {applyLinkPreviewClass} from "@/components/kri-editor/utils/linkPreview";
import {sanitizeEmailHtml} from "@/lib/kmusical/emailHtmlPolicy";
export function EmailSendDialog({
open,
onOpenChange,
title = "이메일 발송",
templateIdx,
newMessageTemplateIdx,
selectedUsers,
addParams = {},
denyParamKeys = [],
onSent,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
title?: string;
templateIdx: number[];
newMessageTemplateIdx?: number;
selectedUsers: UserCompact[];
addParams?: Record<string, string>;
denyParamKeys?: string[];
onSent?: () => void;
}>) {
const {auth} = useAuth();
const templateKey = [...templateIdx, newMessageTemplateIdx ?? 0].join(",");
const ids = Array.from(new Set(templateKey.split(",").map(Number).filter((id) => id > 0)));
const templates = useNotificationTemplatesQuery(ids, open);
const saveMutation = useSaveEmailTemplateMutation();
const sendMutation = useSendEmailBulkMutation();
const imageMutation = useUploadEmailImageMutation();
const downloadMutation = useDownloadEmailAttachmentMutation();
const [activeId, setActiveId] = useState(templateIdx[0] ?? 0);
const [draft, setDraft] = useState<Template | null>(null);
const [editing, setEditing] = useState(false);
const [newMessage, setNewMessage] = useState(false);
const [files, setFiles] = useState<File[]>([]);
const [deletedNames, setDeletedNames] = useState<string[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const lock = useRef(false);
const command = useRef<KriEditorCommand | null>(null);
const fileInput = useRef<HTMLInputElement | null>(null);
const active = templates.data.find((template) => template.tmplatIdx === activeId);
const isBusy = busy || saveMutation.isPending || sendMutation.isPending || imageMutation.isPending;
const canEdit = editing || newMessage;
useEffect(() => {
if (!open) return;
setActiveId(Number(templateKey.split(",")[0]) || 0);
setDraft(null);
setEditing(false);
setNewMessage(false);
setFiles([]);
setDeletedNames([]);
setError("");
}, [open, templateKey]);
useEffect(() => {
if (!open || !active) return;
// 작성 중인 내용은 백그라운드 조회로 덮어쓰지 않는다.
setDraft((current) => current ?? {...active});
}, [open, active]);
const destinations = selectedUsers.flatMap((user) => {
const destEml = getDetailValue(user.userDetail, "userEmail").trim();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(destEml)) return [];
const msgParam = Object.fromEntries(Object.entries({...buildUserMsgParam(user), ...addParams})
.filter(([key, value]) => !denyParamKeys.includes(key) && value.trim()));
return [{sid: user.userId, destNm: user.userName.trim() || user.userId, destEml, msgParam}];
});
const paramKeys = Array.from(new Set(destinations.flatMap((item) => Object.keys(item.msgParam))));
const attachmentNames = draft?.atchFl?.split("|").filter(Boolean) ?? [];
const switchTemplate = (id: number, clear = false) => {
const template = templates.data.find((item) => item.tmplatIdx === id);
setActiveId(id);
setDraft(template ? {...template, ...(clear ? {tmplatTitle: "", tmplatBody: ""} : {})} : null);
setNewMessage(clear);
setEditing(false);
setFiles([]);
setDeletedNames(clear ? template?.atchFl?.split("|").filter(Boolean) ?? [] : []);
setError("");
};
const save = async () => {
if (!draft || draft.tmplatTy !== SEND_TYPE.EMAIL) throw new Error("이메일 템플릿을 확인해 주세요.");
if (!draft.tmplatNm.trim() || !draft.tmplatTitle?.trim() || !draft.tmplatBody.trim()) {
throw new Error("템플릿 이름, 제목과 내용을 입력해 주세요.");
}
const saved = await saveMutation.mutateAsync({
template: draft,
files,
deleteFileNames: deletedNames
});
setDraft(saved);
setFiles([]);
setDeletedNames([]);
setEditing(false);
return saved;
};
const run = async (action: () => Promise<void>) => {
if (lock.current) return;
lock.current = true;
setBusy(true);
setError("");
try {
await action();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "요청을 처리하지 못했습니다. 다시 시도해 주세요.");
} finally {
lock.current = false;
setBusy(false);
}
};
const send = () => run(async () => {
if (!draft || draft.tmplatTy !== SEND_TYPE.EMAIL) throw new Error("이메일 템플릿을 확인해 주세요.");
if (!auth.user?.userCmpn || !auth.user.userId) throw new Error("로그인 사용자 정보를 확인할 수 없습니다.");
if (!destinations.length) throw new Error("발송 가능한 이메일 주소가 없습니다.");
if (destinations.length !== selectedUsers.length && !confirm("이메일 주소가 없거나 형식이 잘못된 사용자를 제외하고 발송하시겠습니까?")) return;
const template = newMessage ? await save() : draft;
const result = await sendMutation.mutateAsync({
templateIdx: template.tmplatIdx,
reqstCmpn: auth.user.userCmpn, reqstUser: auth.user.userId,
reqstSvc: NOTIFICATION_REQUEST_SERVICE, destinations
});
if (result.failCount > 0) {
setError(`이메일 요청 ${result.requestCount}건 중 외부 발송 실패 ${result.failCount}건입니다. 발송 결과를 확인해 주세요.`);
onSent?.();
return;
}
alert(`이메일 발송 요청 ${result.requestCount}건이 접수되었습니다.`);
onSent?.();
onOpenChange(false);
});
return (
<Dialog open={open} onOpenChange={(value) => {
if (!isBusy) onOpenChange(value);
}}>
<DialogContent showCloseButton={false}
className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-5xl">
<DialogHeader className="flex-row flex-wrap items-center justify-between gap-3 space-y-0">
<DialogTitle>{title}</DialogTitle>
<div className="flex items-center gap-2">
<span
className="text-sm text-muted-foreground">선택 인원: {selectedUsers.length}명 · 발송 가능 {destinations.length}명</span>
{newMessageTemplateIdx && <Button variant="outline" size="sm"
disabled={isBusy || templates.isLoading || !active}
onClick={() => switchTemplate(newMessage ? templateIdx[0] : newMessageTemplateIdx, !newMessage)}>
{newMessage ? "기본 템플릿" : "새 메일 보내기"}
</Button>}
<Button variant="ghost" size="icon" disabled={isBusy}
onClick={() => onOpenChange(false)} aria-label="닫기"><X
className="size-4"/></Button>
</div>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
{templates.isLoading && !draft &&
<p className="text-sm text-muted-foreground">템플릿 정보를 불러오는 중입니다.</p>}
{templates.isError &&
<p role="alert" className="text-sm text-destructive">템플릿 정보를 불러오지 못했습니다. 창을 닫고 다시
시도해 주세요.</p>}
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{draft && draft.tmplatTy !== SEND_TYPE.EMAIL &&
<p role="alert" className="text-destructive">이메일용 템플릿이 아닙니다.</p>}
{draft?.tmplatTy === SEND_TYPE.EMAIL && <>
<div className="grid gap-3 sm:grid-cols-2">
<label className="space-y-1 text-sm"><span>템플릿명</span>
<Select value={String(activeId)}
disabled={isBusy || canEdit || templateIdx.length <= 1}
onValueChange={(id) => switchTemplate(Number(id))}>
<SelectTrigger className="w-full"><SelectValue/></SelectTrigger>
<SelectContent>{templates.data.filter((item) => item.tmplatTy === SEND_TYPE.EMAIL && (templateIdx.includes(item.tmplatIdx) || item.tmplatIdx === activeId)).map((item) =>
<SelectItem key={item.tmplatIdx}
value={String(item.tmplatIdx)}>{item.tmplatNm}</SelectItem>)}</SelectContent>
</Select>
</label>
<label className="space-y-1 text-sm"><span>발신 이메일</span><Input
value={draft.sendEml ?? ""} disabled/></label>
</div>
<label className="block space-y-1 text-sm"><span>발신자명</span><Input
value={draft.sendNm} disabled/></label>
<label className="block space-y-1 text-sm"><span>제목</span><Input maxLength={128}
value={draft.tmplatTitle ?? ""}
disabled={!canEdit || isBusy}
onChange={(event) => setDraft({
...draft,
tmplatTitle: event.target.value
})}/></label>
{paramKeys.length > 0 && <div className="space-y-1 text-sm">
<div>사용 가능 변수값</div>
<div
className="flex max-h-32 flex-wrap gap-1.5 overflow-y-auto rounded-md border p-2">
{paramKeys.map((key) => <Button key={key} variant="secondary" size="sm"
disabled={!canEdit || isBusy}
onMouseDown={(event) => event.preventDefault()}
onClick={() => command.current?.insertText(`#{${key}}`)}>{getSendParamLabel(key)}
<code>{`#{${key}}`}</code></Button>)}
</div>
</div>}
<div className="space-y-1 text-sm"><span>내용</span>
{canEdit ? <div inert={isBusy}>
<KriEditor mode="both" showPreview value={draft.tmplatBody} debounceMs={0}
allowBase64={false}
onChange={(html) => setDraft((current) => current ? {
...current,
tmplatBody: html
} : current)}
onCommandReady={(value) => {
command.current = value;
}}
onImageUpload={async (file) => {
if (!draft.itrntPrjctCd) throw new Error("템플릿 프로젝트 정보가 없습니다.");
return imageMutation.mutateAsync({
projectCode: draft.itrntPrjctCd,
file
});
}}
/>
</div> : <div
className={cn('kri-editor-preview rounded-md border bg-muted/30 p-3')}
dangerouslySetInnerHTML={{
__html: applyLinkPreviewClass(
sanitizeEmailHtml(
draft.tmplatBody,
),
),
}}
/>
}
</div>
<div className="space-y-2 text-sm">
<div className="flex items-center justify-between">
<span>첨부파일 ({attachmentNames.filter((name) => !deletedNames.includes(name)).length + files.length})</span>
<Button size="sm" variant="outline" disabled={!canEdit || isBusy}
onClick={() => fileInput.current?.click()}><Paperclip
className="size-4"/> 파일 추가</Button>
</div>
<input ref={fileInput} type="file" multiple hidden onChange={(event) => {
const additions = Array.from(event.target.files ?? []);
event.target.value = "";
const names = new Set([...attachmentNames.filter((name) => !deletedNames.includes(name)), ...files.map((file) => file.name)]);
const accepted = additions.filter((file) => {
if (names.has(file.name) || file.name.includes("|")) {
setError("중복 파일명 또는 | 문자를 포함한 파일명은 사용할 수 없습니다.");
return false;
}
names.add(file.name);
return true;
});
setFiles((current) => [...current, ...accepted]);
}}/>
<ul className="space-y-1">
{attachmentNames.map((name) => <li key={name}
className="flex items-center justify-between gap-2 rounded border p-2">
<Button variant="link"
className={`h-auto min-w-0 truncate p-0 ${deletedNames.includes(name) ? "line-through" : ""}`}
disabled={isBusy || downloadMutation.isPending}
onClick={() => run(async () => downloadBlob(await downloadMutation.mutateAsync({
templateIdx: draft.tmplatIdx,
fileName: name
}), name))}>{name}</Button>
{canEdit && <Button size="sm" variant="ghost" disabled={isBusy}
onClick={() => setDeletedNames((current) => current.includes(name) ? current.filter((item) => item !== name) : [...current, name])}>{deletedNames.includes(name) ? "복원" : "삭제"}</Button>}
</li>)}
{files.map((file) => <li key={file.name}
className="flex items-center justify-between gap-2 rounded border p-2">
<span className="min-w-0 truncate">{file.name} (신규)</span><Button size="sm"
variant="ghost"
disabled={isBusy}
onClick={() => setFiles((current) => current.filter((item) => item !== file))}>제거</Button>
</li>)}
</ul>
</div>
</>}
</div>
<DialogFooter className="shrink-0 border-t pt-4">
{draft?.tmplatTy === SEND_TYPE.EMAIL && !newMessage && (!editing
? <Button variant="outline" disabled={isBusy} onClick={() => setEditing(true)}><Edit
className="size-4"/> 수정</Button>
: <><Button variant="outline" disabled={isBusy} onClick={() => run(async () => {
await save();
})}><Save className="size-4"/> 저장</Button><Button variant="outline"
disabled={isBusy}
onClick={() => switchTemplate(activeId)}><RotateCcw
className="size-4"/> 취소</Button></>)}
<Button
disabled={!draft || draft.tmplatTy !== SEND_TYPE.EMAIL || isBusy || editing || !destinations.length}
onClick={send}><Send className="size-4"/> 발송</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,103 @@
"use client";
import {useEffect, useState} from "react";
import type {ExcelUploadResult} from "@kri/common";
import {downloadFile} from "@kri/common/browser";
import {Download, FileUp} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
const base64ToBlob = (value: string) => {
const bytes = Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
return new Blob([bytes], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
};
export function ExcelRegisterDialog({
open,
onOpenChange,
title,
onDownloadTemplate,
onUpload,
isUploading = false,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
onDownloadTemplate: () => void;
onUpload: (file: File) => Promise<ExcelUploadResult>;
isUploading?: boolean;
}>) {
const [file, setFile] = useState<File | null>(null);
const [uploadResult, setUploadResult] = useState<ExcelUploadResult | null>(null);
useEffect(() => {
if (!open) {
setFile(null);
setUploadResult(null);
}
}, [open]);
const upload = async () => {
if (!file) return;
setUploadResult(await onUpload(file));
};
const downloadErrorFile = () => {
if (!uploadResult?.errorFileBase64) return;
downloadFile(
base64ToBlob(uploadResult.errorFileBase64),
uploadResult.errorFileName || "excel_upload_error.xlsx"
);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<div className="space-y-3">
<Button type="button" variant="outline" className="w-full" onClick={onDownloadTemplate}>
<Download className="h-4 w-4" />
양식 다운로드
</Button>
<label className="flex h-11 cursor-pointer items-center justify-center gap-2 rounded-md border bg-muted text-sm font-medium">
<FileUp className="h-4 w-4" />
{file ? file.name : "파일 선택"}
<input
type="file"
accept=".xlsx,.xls"
className="hidden"
disabled={isUploading}
onChange={(event) => {
setFile(event.target.files?.[0] ?? null);
setUploadResult(null);
}}
/>
</label>
{uploadResult && (
<div className="rounded-md border bg-muted/40 p-3 text-sm">
<div>전체: {uploadResult.totalCount}</div>
<div>성공: {uploadResult.successCount}</div>
<div>실패: {uploadResult.failCount}</div>
{uploadResult.hasErrorFile && (
<Button type="button" variant="outline" size="sm" className="mt-2 w-full" onClick={downloadErrorFile}>
<Download className="h-4 w-4" />
오류 파일 다운로드
</Button>
)}
</div>
)}
</div>
<DialogFooter>
<Button type="button" disabled={!file || isUploading} onClick={upload}>
{isUploading ? "등록 중" : "등록"}
</Button>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
닫기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,352 @@
"use client";
import {ReactNode, useEffect, useRef, useState} from "react";
import {Download, ScanSearch, Upload} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {FilterSelect} from "@/components/kmusical/FilterSelect";
import {StatusPill} from "@/components/kmusical/StatusPill";
import type {
Code,
PerformanceCompact,
PerformanceFull,
PerformanceMonitoringSchedule,
PerformanceReview,
PerformanceReviewSlot,
PerformanceStaff,
} from "@/types/kmusical";
import {PDF_CONVERT_STATUS} from "@/types/kmusical";
import type {CodeGroup} from "@/query/code";
import {
useDownloadReviewOriginalMutation,
useDownloadReviewPdfMutation,
useDownloadReviewTemplateMutation,
useUploadReviewFileMutation,
} from "@/query/review";
import {useUserQuery} from "@/query/user";
import {downloadBlob, downloadFromUrl} from "@/lib/kmusical/file";
import {toLocalDateString} from "@/lib/kmusical/date";
import {getCodeLabel, getDetailValue} from "@/lib/kmusical/view";
import {isReviewComplete} from "@/lib/kmusical/performance-status";
import {REVIEW_TYPE} from "@/types/kmusical";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/kmusical/field-labels";
import {useAuth} from "@/hooks/useAuth";
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
function DetailRow({label, children}: {label: string; children: ReactNode}) {
return (
<div className="grid grid-cols-[140px_1fr] border-b last:border-b-0">
<div className="bg-muted px-3 py-2 text-sm font-semibold">{label}</div>
<div className="min-h-9 px-3 py-2 text-sm">{children || "-"}</div>
</div>
);
}
function ReviewSlotCard({
performanceId,
slot,
assignUser,
review,
onChanged,
}: Readonly<{
performanceId: string;
slot: PerformanceReviewSlot;
assignUser?: string;
review?: PerformanceReview;
onChanged?: () => void;
}>) {
const {auth, isMonitoring} = useAuth();
const {data: assignedUser} = useUserQuery(assignUser ?? "");
const fileInputRef = useRef<HTMLInputElement | null>(null);
const uploadMutation = useUploadReviewFileMutation(performanceId, slot.reviewSlot);
const originalMutation = useDownloadReviewOriginalMutation();
const pdfMutation = useDownloadReviewPdfMutation();
const canUpload = !isMonitoring || Boolean(assignUser && auth.user?.userId === assignUser);
const canPreviewPdf = Boolean(review?.pdfFileName && review.pdfConvert === PDF_CONVERT_STATUS.COMPLETED);
const upload = async (file?: File) => {
try {
if (!file || !canUpload) return;
const formData = new FormData();
formData.append("file", file, file.name);
await uploadMutation.mutateAsync({formData, paramUserId: !isMonitoring ? assignUser : undefined});
alert("평가 파일이 등록되었습니다.");
onChanged?.();
} finally {
if (fileInputRef.current) fileInputRef.current.value = "";
}
};
const downloadOriginal = async () => {
const buffer = await originalMutation.mutateAsync({performanceId, reviewSlot: slot.reviewSlot});
downloadBlob(buffer, review?.uploadFileName || `review-${performanceId}-${slot.reviewSlot}`);
};
const downloadPdf = async () => {
const buffer = await pdfMutation.mutateAsync({performanceId, reviewSlot: slot.reviewSlot});
downloadBlob(buffer, review?.pdfFileName || `review-${performanceId}-${slot.reviewSlot}.pdf`, "application/pdf");
};
const previewPdf = () => {
if (!canPreviewPdf) return;
const params = new URLSearchParams({
src: `/api/review/pdf/${encodeURIComponent(performanceId)}/${slot.reviewSlot}?inline=true`,
title: review?.pdfFileName || `${slot.reviewLabel} 미리보기`,
type: "pdf",
});
window.open(`/file-preview?${params.toString()}`, "_blank", "noopener,noreferrer");
};
const reviewerLabel = slot.reviewType === REVIEW_TYPE.CONSULTING ? "컨설팅 위원" : "평가 위원";
const reviewDateLabel = slot.reviewType === REVIEW_TYPE.CONSULTING ? "컨설팅일" : "평가일";
return (
<div className="space-y-2 border-b p-3 last:border-b-0">
<div className="font-semibold">{slot.reviewLabel}</div>
<div className="grid grid-cols-1 gap-x-4 gap-y-1 rounded-xl border bg-muted/30 p-2 text-xs text-muted-foreground sm:grid-cols-2">
<div className="min-w-0 break-words">{reviewerLabel}: {assignedUser?.userName || assignUser || "-"}</div>
<div className="min-w-0 break-words">
{reviewDateLabel}: {review?.reviewDt ? toLocalDateString(new Date(review.reviewDt)) : "-"}
</div>
<div className="min-w-0 break-words">연락처: {getDetailValue(assignedUser?.userDetail, "userTel", "-")}</div>
<div className="min-w-0 break-words">이메일: {getDetailValue(assignedUser?.userDetail, "userEmail", "-")}</div>
</div>
<div className="flex">
<StatusPill variant={isReviewComplete(review) ? "done" : assignUser ? "pending" : "danger"}>
{isReviewComplete(review) ? "완료" : assignUser ? "미진행" : "미배정"}
</StatusPill>
</div>
<div className="flex flex-wrap gap-1">
{canUpload && (
<>
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={() => fileInputRef.current?.click()} disabled={uploadMutation.isPending}>
<Upload className="size-3" /> 평가 등록
</Button>
</>
)}
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={downloadOriginal} disabled={!review?.uploadFileName || originalMutation.isPending}>
<Download className="size-3" /> 원본
</Button>
<Button
type="button"
size="xs"
variant="outline"
className="rounded-full"
onClick={downloadPdf}
disabled={!canPreviewPdf || pdfMutation.isPending}
>
<Download className="size-3" /> PDF
</Button>
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={previewPdf} disabled={!canPreviewPdf}>
<ScanSearch className="size-3" /> 미리보기
</Button>
</div>
<p className="text-xs text-red-500">* 파일 크기 및 형식에 따라 PDF 변환이 최대 5분까지 소요됩니다.</p>
</div>
);
}
const clonePerformance = (performance: PerformanceCompact): PerformanceCompact => ({
...performance,
performanceDetail: {...performance.performanceDetail},
performanceMonitoringSchedule: {...performance.performanceMonitoringSchedule},
performanceStaff: performance.performanceStaff.map((staff) => ({...staff})),
});
export function PerformanceDetailDialog({
open,
onOpenChange,
performance,
codes,
reviewSlots,
canEdit,
canDelete,
onSave,
onDelete,
onRefresh,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
performance: PerformanceFull | PerformanceCompact | null;
codes: CodeMap;
reviewSlots: PerformanceReviewSlot[];
canEdit: boolean;
canDelete: boolean;
onSave?: (performance: PerformanceCompact) => Promise<void> | void;
onDelete?: (performanceId: string) => Promise<void> | void;
onRefresh?: () => void;
}>) {
const {auth, isMonitoring} = useAuth();
const [draft, setDraft] = useState<PerformanceCompact | null>(null);
const [isEditing, setIsEditing] = useState(false);
useEffect(() => {
setDraft(performance ? clonePerformance(performance) : null);
setIsEditing(false);
}, [performance, open]);
const updateDraft = <K extends keyof PerformanceCompact>(key: K, value: PerformanceCompact[K]) => {
setDraft((current) => current ? {...current, [key]: value} : current);
};
const updateDetail = (key: string, value: string) => {
setDraft((current) => current ? {
...current,
performanceDetail: {...current.performanceDetail, [key]: value},
} : current);
};
const updateSchedule = <K extends keyof PerformanceMonitoringSchedule>(key: K, value: PerformanceMonitoringSchedule[K]) => {
setDraft((current) => current ? {
...current,
performanceMonitoringSchedule: {...current.performanceMonitoringSchedule, [key]: value},
} : current);
};
const updateStaff = (index: number, key: keyof PerformanceStaff, value: string) => {
setDraft((current) => {
if (!current) return current;
const performanceStaff = current.performanceStaff.map((staff, staffIndex) =>
staffIndex === index ? {...staff, [key]: value} : staff
);
return {...current, performanceStaff};
});
};
const save = async () => {
if (!draft) return;
await onSave?.(draft);
setIsEditing(false);
};
const deletePerformance = async () => {
if (!draft || !confirm("삭제된 공연은 복구할 수 없습니다. 삭제하시겠습니까?")) return;
await onDelete?.(draft.performanceId);
};
const fullPerformance = performance && "performanceAssignList" in performance ? performance : undefined;
const visibleReviewSlots = isMonitoring
? reviewSlots.filter((slot) => Boolean(
auth.user?.userId && fullPerformance?.performanceAssignList.some(
(assign) => assign.reviewSlot === slot.reviewSlot && assign.assignUser === auth.user?.userId,
),
))
: reviewSlots;
const visibleReviewTypes = [...new Set(visibleReviewSlots.map((slot) => slot.reviewType))];
const reviewTemplateMutation = useDownloadReviewTemplateMutation();
const downloadReviewTemplate = (reviewType: number) => {
reviewTemplateMutation.mutate(reviewType, {
onSuccess: () => downloadFromUrl(`/api/review/template/download/${reviewType}`),
});
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-6xl">
<DialogHeader><DialogTitle>공연 상세 정보</DialogTitle></DialogHeader>
<div className="min-h-0 flex-1 overflow-y-auto pr-1">
{draft && (
<div className="grid gap-4 lg:grid-cols-[1.05fr_0.95fr]">
<div className="space-y-4">
<section className="rounded-md border">
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceId}>{draft.performanceId}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.businessType}>{getCodeLabel(codes, "business_type", draft.businessType)}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceArea}>
{isEditing ? (
<FilterSelect value={String(draft.performanceArea)} onChange={(value) => updateDraft("performanceArea", Number(value))} options={codes.area ?? []} placeholder="지역" />
) : getCodeLabel(codes, "area", draft.performanceArea)}
</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceAreaDetail}>
{isEditing ? <Input value={draft.performanceDetail.performanceAreaDetail ?? ""} onChange={(event) => updateDetail("performanceAreaDetail", event.target.value)} /> : draft.performanceDetail.performanceAreaDetail}
</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.artistName}>{isEditing ? <Input value={draft.artistName} onChange={(event) => updateDraft("artistName", event.target.value)} /> : draft.artistName}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceName}>{isEditing ? <Input value={draft.performanceName} onChange={(event) => updateDraft("performanceName", event.target.value)} /> : draft.performanceName}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceStartMonth}>{isEditing ? <Input type="number" min={0} max={12} value={draft.performanceStartMonth} onChange={(event) => updateDraft("performanceStartMonth", Number(event.target.value))} /> : `${draft.performanceStartMonth}월`}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceDtInfo}>{isEditing ? <Input value={draft.performanceDtInfo} onChange={(event) => updateDraft("performanceDtInfo", event.target.value)} /> : draft.performanceDtInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceTimeInfo}>{isEditing ? <Input value={draft.performanceTimeInfo} onChange={(event) => updateDraft("performanceTimeInfo", event.target.value)} /> : draft.performanceTimeInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationStatus}>
{isEditing ? <FilterSelect value={String(draft.ticketReservationStatus)} onChange={(value) => updateDraft("ticketReservationStatus", Number(value))} options={codes.ticket_reservation_status ?? []} placeholder="티켓 예약" /> : getCodeLabel(codes, "ticket_reservation_status", draft.ticketReservationStatus)}
</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationMemo}>{isEditing ? <Input value={draft.ticketReservationMemo} onChange={(event) => updateDraft("ticketReservationMemo", event.target.value)} /> : draft.ticketReservationMemo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringDate}>{isEditing ? <Input type="date" value={draft.performanceMonitoringSchedule.monitoringDate ?? ""} onChange={(event) => updateSchedule("monitoringDate", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringDate}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringTimeInfo}>{isEditing ? <Input value={draft.performanceMonitoringSchedule.monitoringTimeInfo ?? ""} onChange={(event) => updateSchedule("monitoringTimeInfo", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringTimeInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringAddress}>{isEditing ? <Input value={draft.performanceMonitoringSchedule.monitoringAddress ?? ""} onChange={(event) => updateSchedule("monitoringAddress", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringAddress}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceMemo}>{isEditing ? <Input value={draft.performanceMemo} onChange={(event) => updateDraft("performanceMemo", event.target.value)} /> : draft.performanceMemo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.consultingStatus}>{isEditing ? <Input value={draft.performanceDetail.consultingStatus ?? ""} onChange={(event) => updateDetail("consultingStatus", event.target.value)} /> : draft.performanceDetail.consultingStatus}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.clientManagerName}>{isEditing ? <Input value={draft.performanceDetail.clientManagerName ?? ""} onChange={(event) => updateDetail("clientManagerName", event.target.value)} /> : draft.performanceDetail.clientManagerName}</DetailRow>
</section>
<section className="rounded-md border">
<div className="border-b bg-muted px-3 py-2 font-semibold">관계자 정보</div>
<div className="overflow-auto">
<table className="kmf-table min-w-[620px]">
<thead><tr><th>유형</th><th>이름</th><th>연락처1</th><th>연락처2</th><th>이메일</th></tr></thead>
<tbody>
{draft.performanceStaff.map((staff, index) => (
<tr key={staff.id}>
<td>{getCodeLabel(codes, "staff_type", staff.staffType)}</td>
<td>{isEditing ? <Input value={staff.staffName} onChange={(event) => updateStaff(index, "staffName", event.target.value)} /> : staff.staffName}</td>
<td>{isEditing ? <Input value={staff.staffTel1} onChange={(event) => updateStaff(index, "staffTel1", event.target.value)} /> : staff.staffTel1}</td>
<td>{isEditing ? <Input value={staff.staffTel2} onChange={(event) => updateStaff(index, "staffTel2", event.target.value)} /> : staff.staffTel2}</td>
<td>{isEditing ? <Input value={staff.staffEmail} onChange={(event) => updateStaff(index, "staffEmail", event.target.value)} /> : staff.staffEmail}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</div>
<section className="rounded-md border">
<div className="flex flex-wrap items-center justify-between gap-2 border-b bg-muted px-3 py-2">
<div className="font-semibold">현장모니터링 및 컨설팅</div>
<div className="flex flex-wrap gap-1">
{visibleReviewTypes.map((reviewType) => (
<Button
key={reviewType}
type="button"
size="xs"
variant="outline"
className="rounded-full"
disabled={reviewTemplateMutation.isPending}
onClick={() => downloadReviewTemplate(reviewType)}
>
<Download className="size-3" /> {reviewType === REVIEW_TYPE.CONSULTING ? "컨설팅" : "모니터링"} 양식
</Button>
))}
</div>
</div>
{visibleReviewSlots.map((slot) => (
<ReviewSlotCard
key={slot.reviewSlot}
performanceId={draft.performanceId}
slot={slot}
assignUser={fullPerformance?.performanceAssignList.find((assign) => assign.reviewSlot === slot.reviewSlot)?.assignUser}
review={Object.values(fullPerformance?.performanceReviewMap ?? {}).find((item) => item.reviewSlot === slot.reviewSlot)}
onChanged={onRefresh}
/>
))}
{visibleReviewSlots.length === 0 && <div className="p-8 text-center text-sm text-muted-foreground">등록된 평가 슬롯이 없습니다.</div>}
</section>
</div>
)}
</div>
<DialogFooter className="shrink-0 border-t pt-4">
{canDelete && draft && <Button type="button" variant="destructive" onClick={deletePerformance}>삭제</Button>}
{canEdit && draft && !isEditing && <Button type="button" onClick={() => setIsEditing(true)}>수정</Button>}
{canEdit && draft && isEditing && (
<>
<Button type="button" onClick={save}>저장</Button>
<Button type="button" variant="outline" onClick={() => { if (performance) setDraft(clonePerformance(performance)); setIsEditing(false); }}>취소</Button>
</>
)}
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,349 @@
"use client";
import {useEffect, useMemo, useRef, useState} from "react";
import {Edit, RotateCcw, Save, Send, X} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {
NOTIFICATION_REQUEST_SERVICE,
useNotificationTemplateQuery,
useNotificationTemplatesQuery,
useSaveNotificationTemplateMutation,
useSendSmsBulkMutation,
} from "@/query/notification";
import type {SaveTemplateRequest, Template} from "@/types/notification";
import {TMPLAT_PURPOSE} from "@/types/notification";
import type {UserCompact} from "@/types/kmusical";
import {getDetailValue} from "@/lib/kmusical/view";
import {
buildTemplatePreviewBody,
buildUserMsgParam,
getSmsByteLength,
isPhoneVerificationSupported,
} from "@/lib/kmusical/notification";
import {getSendParamLabel} from "@/lib/kmusical/field-labels";
import {useAuth} from "@/hooks/useAuth";
type TemplateDraft = Pick<
Template,
"tmplatIdx" | "tmplatTy" | "tmplatPurpose" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel"
>;
const toText = (value: string | null | undefined) => value ?? "";
const toDraft = (template: Template, clearContent = false): TemplateDraft => ({
tmplatIdx: template.tmplatIdx,
tmplatTy: template.tmplatTy,
tmplatPurpose: template.tmplatPurpose,
tmplatNm: template.tmplatNm ?? "",
tmplatTitle: clearContent ? "" : template.tmplatTitle ?? "",
tmplatBody: clearContent ? "" : template.tmplatBody ?? "",
sendTel: template.sendTel ?? "",
});
export function SmsSendDialog({
open,
onOpenChange,
title = "문자 발송",
templateIdx,
newMessageTemplateIdx,
selectedUsers,
addParams = {},
denyParamKeys = [],
onBeforeDefaultTemplateSend,
isBeforeSendPending = false,
onSent,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
title?: string;
templateIdx: number[];
newMessageTemplateIdx?: number;
selectedUsers: UserCompact[];
addParams?: Record<string, string>;
denyParamKeys?: string[];
onBeforeDefaultTemplateSend?: () => Promise<void>;
isBeforeSendPending?: boolean;
onSent?: () => void;
}>) {
const {auth} = useAuth();
const templateIdxKey = templateIdx.join(",");
const templateIdxList = useMemo(
() => Array.from(new Set(templateIdx.filter((idx) => idx > 0))),
[templateIdxKey]
);
const defaultTemplateIdx = templateIdxList[0] ?? 0;
const [activeTemplateIdx, setActiveTemplateIdx] = useState(defaultTemplateIdx);
const [draft, setDraft] = useState<TemplateDraft | null>(null);
const [isEditing, setIsEditing] = useState(false);
const [isNewMessage, setIsNewMessage] = useState(false);
const bodyTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const templatesQuery = useNotificationTemplatesQuery(templateIdxList, open);
const newMessageTemplateQuery = useNotificationTemplateQuery(
newMessageTemplateIdx ?? 0,
Boolean(open && isNewMessage && newMessageTemplateIdx)
);
const saveMutation = useSaveNotificationTemplateMutation();
const sendMutation = useSendSmsBulkMutation();
const activeTemplate = isNewMessage
? newMessageTemplateQuery.data
: templatesQuery.data.find((template) => template.tmplatIdx === activeTemplateIdx);
const isBusy = templatesQuery.isLoading
|| newMessageTemplateQuery.isLoading
|| saveMutation.isPending
|| sendMutation.isPending
|| isBeforeSendPending;
const canEdit = isNewMessage || isEditing;
const destinations = useMemo(() => {
const denied = new Set(denyParamKeys);
return selectedUsers.flatMap((user) => {
const destTel = getDetailValue(user.userDetail, "userTel").trim();
const destNm = (user.userName || user.userId).trim();
if (!destTel || !destNm) return [];
const msgParam = Object.fromEntries(
Object.entries({...buildUserMsgParam(user), ...addParams})
.filter(([key, value]) => !denied.has(key) && value.trim().length > 0)
);
return [{sid: user.userId, destTel, destNm, msgParam}];
});
}, [addParams, denyParamKeys, selectedUsers]);
const msgParamKeys = useMemo(
() => Array.from(new Set(destinations.flatMap((destination) => Object.keys(destination.msgParam)))),
[destinations]
);
useEffect(() => {
if (!open) return;
setActiveTemplateIdx(defaultTemplateIdx);
setDraft(null);
setIsEditing(false);
setIsNewMessage(false);
}, [defaultTemplateIdx, open, templateIdxKey]);
useEffect(() => {
if (!open || !activeTemplate) return;
setDraft(toDraft(activeTemplate, isNewMessage));
}, [activeTemplate, isNewMessage, open]);
const updateDraft = <K extends keyof TemplateDraft>(key: K, value: TemplateDraft[K]) => {
setDraft((current) => current ? {...current, [key]: value} : current);
};
const insertMsgParam = (key: string) => {
if (!draft || !canEdit || isBusy) return;
const token = `#{${key}}`;
const start = bodyTextareaRef.current?.selectionStart ?? draft.tmplatBody.length;
const end = bodyTextareaRef.current?.selectionEnd ?? start;
updateDraft("tmplatBody", `${draft.tmplatBody.slice(0, start)}${token}${draft.tmplatBody.slice(end)}`);
window.setTimeout(() => {
bodyTextareaRef.current?.focus();
bodyTextareaRef.current?.setSelectionRange(start + token.length, start + token.length);
}, 0);
};
const saveTemplate = async () => {
if (!draft || !draft.tmplatNm.trim() || !draft.tmplatBody.trim()) {
alert("템플릿 이름과 내용을 입력해 주세요.");
return null;
}
const payload: SaveTemplateRequest = {
tmplatIdx: draft.tmplatIdx,
tmplatNm: draft.tmplatNm.trim(),
tmplatTitle: draft.tmplatTitle?.trim(),
tmplatBody: draft.tmplatBody,
};
const saved = await saveMutation.mutateAsync(payload);
setDraft(toDraft(saved));
setIsEditing(false);
return saved;
};
const cancelEdit = () => {
if (activeTemplate) setDraft(toDraft(activeTemplate, isNewMessage));
setIsEditing(false);
};
const changeTemplate = (value: string) => {
setActiveTemplateIdx(Number(value));
setIsNewMessage(false);
setIsEditing(false);
setDraft(null);
};
const switchToNewMessage = () => {
if (!newMessageTemplateIdx) return;
setActiveTemplateIdx(newMessageTemplateIdx);
setIsNewMessage(true);
setIsEditing(false);
setDraft(null);
};
const restoreTemplate = () => {
setActiveTemplateIdx(defaultTemplateIdx);
setIsNewMessage(false);
setIsEditing(false);
setDraft(null);
};
const previewBody = draft ? buildTemplatePreviewBody(draft) : "";
const isSmsOrLms = draft ? isPhoneVerificationSupported(draft) : false;
const send = async () => {
if (!draft || !auth.user?.userCmpn || !auth.user.userId) {
alert("로그인 사용자 또는 템플릿 정보를 확인할 수 없습니다.");
return;
}
if (destinations.length === 0) {
alert("발송 가능한 연락처가 없습니다.");
return;
}
if (destinations.length !== selectedUsers.length && !confirm("연락처가 없는 사용자를 제외하고 발송하시겠습니까?")) {
return;
}
if (isEditing || isNewMessage) {
const saved = await saveTemplate();
if (!saved) return;
}
if (!isNewMessage) await onBeforeDefaultTemplateSend?.();
const result = await sendMutation.mutateAsync({
templateIdx: draft.tmplatIdx,
reqstCmpn: auth.user.userCmpn,
reqstUser: auth.user.userId,
reqstSvc: NOTIFICATION_REQUEST_SERVICE,
destinations,
});
alert(`문자 발송 요청 ${result.requestCount}건이 접수되었습니다.`);
onSent?.();
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent showCloseButton={false} className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-2xl">
<DialogHeader className="flex-row flex-wrap items-center justify-between gap-3 space-y-0">
<DialogTitle>{title}</DialogTitle>
<div className="flex flex-wrap items-center gap-2">
<div className="text-sm whitespace-nowrap text-muted-foreground">
선택 인원: <span className="font-semibold text-foreground">{selectedUsers.length}</span>명
{destinations.length !== selectedUsers.length && (
<span className="ml-2 text-destructive">발송 가능 {destinations.length}명</span>
)}
</div>
{newMessageTemplateIdx && (
isNewMessage ? (
<Button type="button" size="sm" variant="outline" onClick={restoreTemplate} disabled={isBusy}>
<RotateCcw className="h-4 w-4" /> 기본 템플릿
</Button>
) : (
<Button type="button" size="sm" variant="outline" onClick={switchToNewMessage} disabled={isBusy}>
새문자 보내기
</Button>
)
)}
<DialogClose asChild>
<Button type="button" size="icon" variant="ghost" className="h-8 w-8 shrink-0">
<X className="h-4 w-4" />
<span className="sr-only">닫기</span>
</Button>
</DialogClose>
</div>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
{isBusy && !draft && (
<div className="rounded-md border p-4 text-sm text-muted-foreground">템플릿 정보를 불러오는 중입니다.</div>
)}
{(templatesQuery.isError || newMessageTemplateQuery.isError) && !draft && (
<div className="rounded-md border border-destructive p-4 text-sm text-destructive">템플릿 정보를 불러오지 못했습니다.</div>
)}
{draft && (
<div className="space-y-3">
<div className="grid gap-3 md:grid-cols-2">
<label className="space-y-1 text-sm">
<span className="font-medium">템플릿명</span>
<Select value={String(activeTemplateIdx)} onValueChange={changeTemplate} disabled={isBusy || isEditing || isNewMessage || templateIdxList.length <= 1}>
<SelectTrigger className="w-full"><SelectValue placeholder="템플릿 선택" /></SelectTrigger>
<SelectContent>
{isNewMessage && <SelectItem value={String(draft.tmplatIdx)}>{toText(draft.tmplatNm) || String(draft.tmplatIdx)}</SelectItem>}
{templatesQuery.data.map((template) => (
<SelectItem key={template.tmplatIdx} value={String(template.tmplatIdx)}>
{toText(template.tmplatNm) || String(template.tmplatIdx)}
{template.tmplatPurpose === TMPLAT_PURPOSE.PHONE_VERIFICATION && " (인증)"}
</SelectItem>
))}
</SelectContent>
</Select>
</label>
<label className="space-y-1 text-sm">
<span className="font-medium">발신번호</span>
<Input value={draft.sendTel ?? ""} disabled />
</label>
</div>
<label className="space-y-1 text-sm">
<span className="font-medium">제목</span>
<Input value={draft.tmplatTitle ?? ""} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("tmplatTitle", event.target.value)} />
</label>
{isSmsOrLms && (
<label className="space-y-1 text-sm">
<span className="font-medium">템플릿 용도</span>
<Select value={String(draft.tmplatPurpose)} disabled>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={String(TMPLAT_PURPOSE.NORMAL)}>일반</SelectItem>
<SelectItem value={String(TMPLAT_PURPOSE.PHONE_VERIFICATION)}>휴대전화번호 인증</SelectItem>
</SelectContent>
</Select>
</label>
)}
<label className="space-y-1 text-sm">
<span className="font-medium">내용</span>
<textarea ref={bodyTextareaRef} value={draft.tmplatBody} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("tmplatBody", event.target.value)} className="min-h-52 w-full rounded-md border border-input bg-background p-3 text-sm disabled:cursor-not-allowed disabled:opacity-70" />
</label>
{msgParamKeys.length > 0 && (
<div className="space-y-1 text-sm">
<div className="font-medium text-muted-foreground">사용 가능 변수값</div>
<div className="max-h-36 overflow-y-auto rounded-md border bg-muted/20 p-2">
<div className="flex flex-wrap gap-1.5">
{msgParamKeys.map((key) => (
<Button key={key} type="button" className="h-auto flex-col items-start gap-0 rounded bg-muted px-2 py-1 text-center text-xs text-foreground hover:bg-muted/80 disabled:cursor-not-allowed disabled:opacity-50" disabled={!canEdit || isBusy} onClick={() => insertMsgParam(key)}>
<span className="text-center">{getSendParamLabel(key)}</span>
<code className="font-mono text-muted-foreground">{`#{${key}}`}</code>
</Button>
))}
</div>
</div>
</div>
)}
</div>
)}
</div>
<DialogFooter className="shrink-0 border-t pt-4">
{!isNewMessage && draft && !isEditing && (
<Button type="button" variant="outline" onClick={() => setIsEditing(true)} disabled={isBusy}><Edit className="h-4 w-4" /> 수정</Button>
)}
{!isNewMessage && draft && isEditing && (
<>
<Button type="button" variant="outline" onClick={saveTemplate} disabled={isBusy}><Save className="h-4 w-4" /> 저장</Button>
<Button type="button" variant="outline" onClick={cancelEdit} disabled={isBusy}><RotateCcw className="h-4 w-4" /> 취소</Button>
</>
)}
<Button type="button" disabled={!draft || isBusy || isEditing || selectedUsers.length === 0} onClick={send}><Send className="h-4 w-4" /> 발송</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}