278 lines
9.3 KiB
TypeScript
278 lines
9.3 KiB
TypeScript
"use client";
|
|
|
|
import {useEffect, useMemo, useState} from "react";
|
|
import {Edit, RotateCcw, Save, Send} 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 {
|
|
NOTIFICATION_REQUEST_SERVICE,
|
|
useNotificationTemplateQuery,
|
|
useSaveNotificationTemplateMutation,
|
|
useSendSmsBulkMutation,
|
|
} from "@/query/notification";
|
|
import {SaveTemplateRequest, Template} from "@/types/notification";
|
|
import {UserCompact} from "@/types/gwcf";
|
|
import {getDetailValue} from "@/lib/gwcf/view";
|
|
import {useAuth} from "@/hooks/useAuth";
|
|
import {buildUserMsgParam} from "@/lib/gwcf/notification";
|
|
|
|
type TemplateDraft = Pick<Template, "tmplatIdx" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel">;
|
|
|
|
const toText = (value: string | null | undefined) => value ?? "";
|
|
|
|
const toDraft = (template: Template, emptyBody = false): TemplateDraft => ({
|
|
tmplatIdx: template.tmplatIdx,
|
|
tmplatNm: toText(template.tmplatNm),
|
|
tmplatTitle: toText(template.tmplatTitle),
|
|
tmplatBody: emptyBody ? "" : toText(template.tmplatBody),
|
|
sendTel: toText(template.sendTel),
|
|
});
|
|
|
|
export function SmsSendDialog({
|
|
open,
|
|
onOpenChange,
|
|
title = "문자 발송",
|
|
templateIdx,
|
|
newMessageTemplateIdx,
|
|
selectedUsers,
|
|
addParams = {},
|
|
onBeforeDefaultTemplateSend,
|
|
isBeforeSendPending = false,
|
|
onSent,
|
|
}: Readonly<{
|
|
open: boolean;
|
|
onOpenChange: (open: boolean) => void;
|
|
title?: string;
|
|
templateIdx: number;
|
|
newMessageTemplateIdx?: number;
|
|
selectedUsers: UserCompact[];
|
|
addParams?: Record<string, string>;
|
|
onBeforeDefaultTemplateSend?: () => Promise<void>;
|
|
isBeforeSendPending?: boolean;
|
|
onSent?: () => void;
|
|
}>) {
|
|
const {auth} = useAuth();
|
|
const [activeTemplateIdx, setActiveTemplateIdx] = useState(templateIdx);
|
|
const [isNewMessage, setIsNewMessage] = useState(false);
|
|
const [isEditing, setIsEditing] = useState(false);
|
|
const [draft, setDraft] = useState<TemplateDraft | null>(null);
|
|
|
|
const templateQuery = useNotificationTemplateQuery(activeTemplateIdx, open);
|
|
const saveTemplateMutation = useSaveNotificationTemplateMutation();
|
|
const sendSmsMutation = useSendSmsBulkMutation();
|
|
|
|
const isBusy = templateQuery.isLoading || saveTemplateMutation.isPending || sendSmsMutation.isPending || isBeforeSendPending;
|
|
const canEdit = isNewMessage || isEditing;
|
|
|
|
const destinations = useMemo(() => {
|
|
return selectedUsers
|
|
.map((user) => ({
|
|
sid: user.userId,
|
|
destTel: getDetailValue(user.userDetail, ["userTel"]),
|
|
destNm: user.userName || user.userId,
|
|
msgParam: {
|
|
...buildUserMsgParam(user),
|
|
...addParams,
|
|
},
|
|
}))
|
|
.filter((item) => item.destTel);
|
|
}, [selectedUsers, addParams]);
|
|
|
|
const msgParamKeys = useMemo(() => {
|
|
return Array.from(
|
|
new Set(destinations.flatMap((destination) => Object.keys(destination.msgParam)))
|
|
);
|
|
}, [destinations]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
|
|
setActiveTemplateIdx(templateIdx);
|
|
setIsNewMessage(false);
|
|
setIsEditing(false);
|
|
setDraft(null);
|
|
}, [open, templateIdx]);
|
|
|
|
useEffect(() => {
|
|
if (!open || !templateQuery.data) return;
|
|
|
|
setDraft(toDraft(templateQuery.data, isNewMessage));
|
|
setIsEditing(false);
|
|
}, [isNewMessage, open, templateQuery.data]);
|
|
|
|
const updateDraft = <K extends keyof TemplateDraft>(key: K, value: TemplateDraft[K]) => {
|
|
setDraft((prev) => prev ? {...prev, [key]: value} : prev);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
|
|
console.log("d\estinations msgParam keys", msgParamKeys, destinations);
|
|
}, [msgParamKeys, open]);
|
|
|
|
const saveTemplate = async () => {
|
|
if (!draft) return null;
|
|
|
|
const payload: SaveTemplateRequest = {
|
|
tmplatIdx: draft.tmplatIdx,
|
|
tmplatNm: draft.tmplatNm,
|
|
tmplatTitle: draft.tmplatTitle,
|
|
tmplatBody: draft.tmplatBody,
|
|
sendTel: draft.sendTel,
|
|
};
|
|
|
|
const saved = await saveTemplateMutation.mutateAsync(payload);
|
|
setDraft(toDraft(saved));
|
|
setIsEditing(false);
|
|
return saved;
|
|
};
|
|
|
|
const switchToNewMessage = () => {
|
|
if (!newMessageTemplateIdx) return;
|
|
|
|
setActiveTemplateIdx(newMessageTemplateIdx);
|
|
setIsNewMessage(true);
|
|
setIsEditing(false);
|
|
setDraft(null);
|
|
};
|
|
|
|
const restoreTemplate = () => {
|
|
setActiveTemplateIdx(templateIdx);
|
|
setIsNewMessage(false);
|
|
setIsEditing(false);
|
|
setDraft(null);
|
|
};
|
|
|
|
const send = async () => {
|
|
if (!draft) return;
|
|
|
|
if (!auth.user?.userCmpn || !auth.user?.userId) {
|
|
alert("로그인 사용자 정보를 확인할 수 없습니다.");
|
|
return;
|
|
}
|
|
|
|
if (selectedUsers.length === 0) {
|
|
alert("문자를 발송할 사용자를 선택해 주세요.");
|
|
return;
|
|
}
|
|
|
|
if (destinations.length === 0) {
|
|
alert("발송 가능한 연락처가 없습니다.");
|
|
return;
|
|
}
|
|
|
|
if (destinations.length !== selectedUsers.length) {
|
|
if (!confirm("연락처가 없는 사용자는 제외하고 발송합니다. 계속하시겠습니까?")) return;
|
|
}
|
|
|
|
if (isNewMessage) {
|
|
await saveTemplate();
|
|
} else {
|
|
await onBeforeDefaultTemplateSend?.();
|
|
}
|
|
|
|
const result = await sendSmsMutation.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 className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-2xl">
|
|
<DialogHeader>
|
|
<DialogTitle>{title}</DialogTitle>
|
|
</DialogHeader>
|
|
|
|
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
|
|
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 p-3">
|
|
<div className="text-sm 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>
|
|
)
|
|
)}
|
|
</div>
|
|
|
|
{templateQuery.isLoading && (
|
|
<div className="rounded-md border p-4 text-sm text-muted-foreground">템플릿 정보를 불러오는 중입니다.</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>
|
|
<Input value={draft.tmplatNm} disabled />
|
|
</label>
|
|
<label className="space-y-1 text-sm">
|
|
<span className="font-medium">발신번호</span>
|
|
<Input value={draft.sendTel ?? ""} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("sendTel", event.target.value)} />
|
|
</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>
|
|
<label className="space-y-1 text-sm">
|
|
<span className="font-medium">내용</span>
|
|
<textarea
|
|
value={draft.tmplatBody}
|
|
disabled={!canEdit || isBusy}
|
|
onChange={(event) => updateDraft("tmplatBody", event.target.value)}
|
|
className="min-h-56 w-full rounded-md border border-input bg-background p-3 text-sm disabled:cursor-not-allowed disabled:opacity-70"
|
|
/>
|
|
</label>
|
|
</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" disabled={!draft || isBusy || isEditing || selectedUsers.length === 0} onClick={send}>
|
|
<Send className="h-4 w-4" />
|
|
발송
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|