Files
frontend/apps/cs/src/pages/groups/ui/add-user-dialog.tsx
T

228 lines
5.7 KiB
TypeScript

"use client";
import { useState, useEffect } from "react";
import {
keepPreviousData,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import {
getCoreRowModel,
type PaginationState,
type RowSelectionState,
type ColumnDef,
} from "@tanstack/react-table";
import {
Button,
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
Input,
Checkbox,
Label,
} from "@common/components";
import {
UserApi,
type UserListResponse,
type UserSearchParams,
} from "@/entities/user";
import { GroupUsersApi } from "@/entities/group-user";
import { ENDPOINT } from "@/shared/config";
import { useAlertStore, useDataTable } from "@/shared/lib";
type AdditionalUserDialogProps = {
groupId?: string;
};
function AddUserDialog({ groupId }: AdditionalUserDialogProps) {
const queryClient = useQueryClient();
const alert = useAlertStore((state) => state.setMessage);
const [open, setOpen] = useState(false);
const [userName, setUserName] = useState("");
const [searchParam, setSearchParam] = useState<UserSearchParams>({
userName: "",
});
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const [userRowSelection, setUserRowSelection] = useState<RowSelectionState>(
{},
);
const query = useQuery({
queryKey: [ENDPOINT.USER_SERVICE.USERS, searchParam, pagination],
queryFn: () =>
UserApi.findPageUser({
...searchParam,
page: pagination.pageIndex,
size: pagination.pageSize,
}),
enabled: open,
placeholderData: keepPreviousData,
});
const userColumns: ColumnDef<UserListResponse>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="전체 선택"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="행 선택"
/>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "userId",
header: "사용자ID",
},
{
accessorKey: "userName",
header: "이름",
},
{
accessorKey: "ogdpSeNm",
header: "소속",
},
{
accessorKey: "mphn",
header: "연락처",
},
];
const { tableComponent, tableInstance: table } = useDataTable({
query,
tableOptions: {
columns: userColumns,
state: { pagination, rowSelection: userRowSelection },
manualPagination: true,
enableRowSelection: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: setPagination,
onRowSelectionChange: setUserRowSelection,
getRowId: (row) => row.userUnqId,
},
dataTableOptions: {
viewPagination: true,
},
});
const handleAddUsers = async () => {
const selectedRows = Object.keys(userRowSelection);
if (selectedRows.length === 0 || !groupId) return;
try {
const usersToAdd = selectedRows.map((userUnqId) => ({
mode: "C",
groupId,
userUnqId,
}));
await GroupUsersApi.saveGroupUser(usersToAdd);
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.GROUP_USERS, groupId],
});
alert("사용자 추가를 완료했습니다.", () => {
setOpen(false);
setUserRowSelection({});
});
} catch (error) {
console.error(error);
}
};
const handleSearch = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
e.stopPropagation();
setPagination({
...pagination,
pageIndex: 0,
});
setSearchParam({ userName });
};
const resetSearch = () => {
setPagination({
pageIndex: 0,
pageSize: 10,
});
setUserName("");
setSearchParam({ userName: "" });
setUserRowSelection({});
};
useEffect(() => {
if (open) resetSearch();
}, [open]);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button disabled={!groupId}>사용자 추가</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle>사용자 추가</DialogTitle>
</DialogHeader>
<form onSubmit={handleSearch} className="mb-4 flex items-end gap-2">
<div className="flex items-center gap-2">
<Label htmlFor="userName" className="mr-2 text-label">
사용자 이름
</Label>
<Input
id="userName"
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem]"
value={userName}
onChange={(e) => setUserName(e.target.value)}
placeholder="사용자 이름으로 검색"
/>
</div>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
<Button
type="button"
color="white"
className="h-[3.2rem]"
onClick={resetSearch}
>
초기화
</Button>
</form>
{tableComponent}
<DialogFooter>
<Button color="white" onClick={() => setOpen(false)}>
취소
</Button>
<Button
onClick={handleAddUsers}
disabled={table.getSelectedRowModel().rows.length === 0}
>
추가
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export { AddUserDialog };