260617_01_ENH: 배정 테스트를 위해 개발 중도 커밋
This commit is contained in:
@@ -1,9 +1,307 @@
|
||||
'use client'
|
||||
"use client";
|
||||
|
||||
const UserPage = () => {
|
||||
return (
|
||||
<div>UserPage</div>
|
||||
);
|
||||
import {MouseEvent, ReactNode, useEffect, useMemo, useRef, useState} from "react";
|
||||
import {Search, Send, Upload} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {FilterSelect} from "@/components/gwcf/FilterSelect";
|
||||
import {MultiFilterSelect} from "@/components/gwcf/MultiFilterSelect";
|
||||
import {PagePanel} from "@/components/gwcf/PagePanel";
|
||||
import {ExcelRegisterDialog} from "@/components/dialog/ExcelRegisterDialog";
|
||||
import {SmsSendDialog} from "@/components/dialog/SmsSendDialog";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {DataTableColumn} from "@/components/data-table/DataTable.type";
|
||||
import {useCodesQuery} from "@/query/code";
|
||||
import {useAssignUserCountsQuery} from "@/query/assign";
|
||||
import {
|
||||
useDeleteUserMutation,
|
||||
useDownloadUserExcelTemplateMutation,
|
||||
useUpdateUserMutation,
|
||||
useUploadUsersExcelMutation,
|
||||
useUsersQuery,
|
||||
} from "@/query/user";
|
||||
import {filterUser, getDetailValue, ROLE} from "@/lib/gwcf/view";
|
||||
import {Code, UserFull} from "@/types/gwcf";
|
||||
import {SMS_TEMPLATE_IDS} from "@/query/notification";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {downloadFile} from "@/lib/utils";
|
||||
|
||||
type UserTab = "monitoring" | "written";
|
||||
type UserFilters = {area: string[]; gender: string[]; genre: string[]; keyword: string};
|
||||
|
||||
const tabRole: Record<UserTab, number> = {
|
||||
monitoring: ROLE.MONITORING,
|
||||
written: ROLE.WRITTEN_REVIEWER,
|
||||
};
|
||||
|
||||
function StopCell({children}: {children: ReactNode}) {
|
||||
const stop = (event: MouseEvent<HTMLDivElement>) => event.stopPropagation();
|
||||
return <div onClick={stop}>{children}</div>;
|
||||
}
|
||||
|
||||
export default UserPage;
|
||||
const getOptionLabel = (options: Code[], value: string) => {
|
||||
if (!value) return "";
|
||||
return options.find((option) => String(option.codeValue) === value)?.codeLabel ?? value;
|
||||
};
|
||||
|
||||
const UserPage = () => {
|
||||
const mounted = useMounted();
|
||||
const {data: codes} = useCodesQuery();
|
||||
const {data: assignCounts = [], refetch: refetchAssignCounts} = useAssignUserCountsQuery();
|
||||
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
||||
const [tab, setTab] = useState<UserTab>("monitoring");
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([]);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [, forceDraftRender] = useState(0);
|
||||
const draftRef = useRef<UserFull | null>(null);
|
||||
const [filters, setFilters] = useState<UserFilters>({area: [], gender: [], genre: [], keyword: ""});
|
||||
|
||||
const userRole = tabRole[tab];
|
||||
const {data = [], refetch: refetchUsers} = useUsersQuery(userRole);
|
||||
const updateMutation = useUpdateUserMutation();
|
||||
const deleteMutation = useDeleteUserMutation();
|
||||
const uploadMutation = useUploadUsersExcelMutation(userRole);
|
||||
const templateMutation = useDownloadUserExcelTemplateMutation(userRole);
|
||||
|
||||
const assignCountMap = useMemo(() => new Map(assignCounts.map((item) => [item.assignUser, item.assignCount])), [assignCounts]);
|
||||
|
||||
const refreshUserList = () => {
|
||||
void refetchUsers();
|
||||
void refetchAssignCounts();
|
||||
};
|
||||
|
||||
const updateFilters = (updater: (prev: UserFilters) => UserFilters) => {
|
||||
setFilters(updater);
|
||||
refreshUserList();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedIds([]);
|
||||
setEditingId(null);
|
||||
draftRef.current = null;
|
||||
forceDraftRender((prev) => prev + 1);
|
||||
setFilters({area: [], gender: [], genre: [], keyword: ""});
|
||||
}, [tab]);
|
||||
|
||||
const filteredData = useMemo(() => data.filter((user) => filterUser(user, filters)), [data, filters]);
|
||||
const smsTargetUsers = useMemo(
|
||||
() => data.filter((user) => selectedIds.includes(user.userId)),
|
||||
[data, selectedIds]
|
||||
);
|
||||
|
||||
const startEdit = (user: UserFull) => {
|
||||
setEditingId(user.userId);
|
||||
draftRef.current = {...user, userDetail: {...user.userDetail}};
|
||||
forceDraftRender((prev) => prev + 1);
|
||||
};
|
||||
|
||||
const updateDraft = (updater: (prev: UserFull) => UserFull) => {
|
||||
if (!draftRef.current) return;
|
||||
draftRef.current = updater(draftRef.current);
|
||||
forceDraftRender((prev) => prev + 1);
|
||||
};
|
||||
|
||||
const updateDetail = (key: string, value: string) => {
|
||||
updateDraft((prev) => ({...prev, userDetail: {...prev.userDetail, [key]: value}}));
|
||||
};
|
||||
|
||||
const saveEdit = () => {
|
||||
if (!draftRef.current) return;
|
||||
updateMutation.mutate(draftRef.current, {
|
||||
onSuccess: () => {
|
||||
alert("사용자 정보가 수정되었습니다.");
|
||||
setEditingId(null);
|
||||
draftRef.current = null;
|
||||
forceDraftRender((prev) => prev + 1);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const deleteUser = (userId: string) => {
|
||||
if (!confirm("사용자 정보가 완전히 지워집니다 정말로 삭제 하시겠습니까?")) return;
|
||||
deleteMutation.mutate(userId, {
|
||||
onSuccess: () => alert("사용자 정보가 삭제되었습니다."),
|
||||
});
|
||||
};
|
||||
|
||||
const downloadTemplate = async () => {
|
||||
const buffer = await templateMutation.mutateAsync();
|
||||
const blob = new Blob([buffer], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
|
||||
downloadFile(blob, tab === "monitoring" ? "모니터링 요원 template.xlsx" : "서면 평가위원 template.xlsx");
|
||||
};
|
||||
|
||||
const renderEditableCell = (user: UserFull, key: string, fallbackKeys: string[], type: "text" | "select" = "text", options: Code[] = []) => {
|
||||
const draft = draftRef.current;
|
||||
const isEditing = editingId === user.userId && draft;
|
||||
const source = isEditing ? draft.userDetail : user.userDetail;
|
||||
const value = getDetailValue(source, [key, ...fallbackKeys]);
|
||||
|
||||
if (!isEditing) return type === "select" ? (getOptionLabel(options, value) || "-") : (value || "-");
|
||||
|
||||
if (type === "select") {
|
||||
return (
|
||||
<StopCell>
|
||||
<FilterSelect value={value} onChange={(next) => updateDetail(key, next)} options={options} placeholder="선택" className="w-full min-w-28" />
|
||||
</StopCell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StopCell>
|
||||
<Input value={value} onChange={(event) => updateDetail(key, event.target.value)} />
|
||||
</StopCell>
|
||||
);
|
||||
};
|
||||
|
||||
const columns = useMemo<DataTableColumn<UserFull>[]>(() => {
|
||||
const commonColumns: DataTableColumn<UserFull>[] = [
|
||||
{accessorKey: "userId", header: "ID", enableSorting: true},
|
||||
{id: "password", header: "PW", cell: () => "****"},
|
||||
];
|
||||
|
||||
const monitoringColumns: DataTableColumn<UserFull>[] = [
|
||||
{id: "participationCount", header: "참여 횟수", cell: ({row}) => assignCountMap.get(row.original.userId) ?? 0, enableSorting: true},
|
||||
{id: "area", header: "지역", cell: ({row}) => renderEditableCell(row.original, "area", ["userArea", "region"], "select", codes.area)},
|
||||
{id: "gender", header: "성별", cell: ({row}) => renderEditableCell(row.original, "gender", ["userGender"], "select", codes.gender)},
|
||||
{id: "age", header: "연령", cell: ({row}) => renderEditableCell(row.original, "age", ["userAge"])},
|
||||
{id: "tel", header: "연락처", cell: ({row}) => renderEditableCell(row.original, "tel", ["phone", "userTel"])},
|
||||
{id: "email", header: "이메일", cell: ({row}) => renderEditableCell(row.original, "email", ["userEmail"])},
|
||||
{id: "hasCar", header: "자차 여부", cell: ({row}) => renderEditableCell(row.original, "userHasCar", ["has_car", "hasCar"], "select", codes.has_car)},
|
||||
];
|
||||
|
||||
const writtenColumns: DataTableColumn<UserFull>[] = [
|
||||
{id: "genre", header: "장르", cell: ({row}) => renderEditableCell(row.original, "userGenre", ["genre", "reviewGenre"], "select", codes.genre)},
|
||||
{id: "tel", header: "연락처", cell: ({row}) => renderEditableCell(row.original, "tel", ["phone", "userTel"])},
|
||||
{id: "email", header: "이메일", cell: ({row}) => renderEditableCell(row.original, "email", ["userEmail"])},
|
||||
];
|
||||
|
||||
const actionColumns: DataTableColumn<UserFull>[] = [
|
||||
{
|
||||
id: "memo",
|
||||
header: "메모",
|
||||
cell: ({row}) => {
|
||||
const draft = draftRef.current;
|
||||
return editingId === row.original.userId && draft ? (
|
||||
<StopCell>
|
||||
<Input value={draft.memo} onChange={(event) => updateDraft((prev) => ({...prev, memo: event.target.value}))} />
|
||||
</StopCell>
|
||||
) : row.original.memo;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "edit",
|
||||
header: "수정",
|
||||
cell: ({row}) => (
|
||||
<StopCell>
|
||||
{editingId === row.original.userId ? (
|
||||
<Button type="button" size="xs" onClick={saveEdit}>저장</Button>
|
||||
) : (
|
||||
<Button type="button" size="xs" variant="outline" onClick={() => startEdit(row.original)}>수정</Button>
|
||||
)}
|
||||
</StopCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "delete",
|
||||
header: "삭제",
|
||||
cell: ({row}) => (
|
||||
<StopCell>
|
||||
<Button type="button" size="xs" variant="destructive" onClick={() => deleteUser(row.original.userId)}>삭제</Button>
|
||||
</StopCell>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return [...commonColumns, ...(tab === "monitoring" ? monitoringColumns : writtenColumns), ...actionColumns];
|
||||
}, [assignCountMap, codes, editingId, tab]);
|
||||
|
||||
if(!mounted) return <LoadingOverlay force={true} />
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant={tab === "monitoring" ? "default" : "outline"} onClick={() => setTab("monitoring")}>모니터링</Button>
|
||||
<Button type="button" variant={tab === "written" ? "default" : "outline"} onClick={() => setTab("written")}>서면평가</Button>
|
||||
</div>
|
||||
|
||||
<PagePanel>
|
||||
<div className="grid gap-2 md:grid-cols-[160px_160px_1fr_auto]">
|
||||
{tab === "monitoring" ? (
|
||||
<>
|
||||
<MultiFilterSelect value={filters.area} onChange={(value) => updateFilters((prev) => ({...prev, area: value}))} options={codes.area} placeholder="지역" />
|
||||
<MultiFilterSelect value={filters.gender} onChange={(value) => updateFilters((prev) => ({...prev, gender: value}))} options={codes.gender} placeholder="성별" />
|
||||
</>
|
||||
) : (
|
||||
<MultiFilterSelect value={filters.genre} onChange={(value) => updateFilters((prev) => ({...prev, genre: value}))} options={codes.genre} placeholder="장르" className="md:col-span-2" />
|
||||
)}
|
||||
<Input value={filters.keyword} onChange={(event) => updateFilters((prev) => ({...prev, keyword: event.target.value}))} placeholder={tab === "monitoring" ? "ID or 연락처 or 이메일" : "ID or 이름 or 연락처 or 이메일"} />
|
||||
<Button type="button" variant="outline" onClick={refreshUserList}>
|
||||
<Search className="h-4 w-4" />
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
</PagePanel>
|
||||
|
||||
<PagePanel className="overflow-x-auto">
|
||||
<div className="flex gap-2 justify-end mb-3">
|
||||
{tab === "monitoring" && (
|
||||
<Button type="button" variant="outline" onClick={() => showDialog("userSmsSendDialog")} disabled={selectedIds.length === 0}>
|
||||
<Send className="h-4 w-4" />
|
||||
문자 발송
|
||||
</Button>
|
||||
)}
|
||||
<Button type="button" onClick={() => showDialog("userExcelRegisterDialog")}>
|
||||
<Upload className="h-4 w-4" />
|
||||
계정 등록
|
||||
</Button>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={filteredData}
|
||||
getRowId={(row) => row.userId}
|
||||
selectMode={tab === "monitoring" ? "multi" : "none"}
|
||||
onRowSelectionChange={(rows) => setSelectedIds(rows.map((row) => row.userId))}
|
||||
defaultPageSize={10}
|
||||
/>
|
||||
</PagePanel>
|
||||
|
||||
<ExcelRegisterDialog
|
||||
open={isDialogOpen("userExcelRegisterDialog")}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
showDialog("userExcelRegisterDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("userExcelRegisterDialog");
|
||||
refreshUserList();
|
||||
}}
|
||||
title="계정 등록"
|
||||
onDownloadTemplate={downloadTemplate}
|
||||
onUpload={(file) => uploadMutation.mutateAsync(file)}
|
||||
isUploading={uploadMutation.isPending}
|
||||
/>
|
||||
|
||||
<SmsSendDialog
|
||||
open={isDialogOpen("userSmsSendDialog")}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
showDialog("userSmsSendDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("userSmsSendDialog");
|
||||
refreshUserList();
|
||||
}}
|
||||
templateIdx={SMS_TEMPLATE_IDS.ACCOUNT_MONITORING}
|
||||
newMessageTemplateIdx={SMS_TEMPLATE_IDS.CUSTOM}
|
||||
selectedUsers={smsTargetUsers}
|
||||
onSent={refreshUserList}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserPage;
|
||||
|
||||
Reference in New Issue
Block a user