diff options
Diffstat (limited to 'lib/tbe')
| -rw-r--r-- | lib/tbe/service.ts | 0 | ||||
| -rw-r--r-- | lib/tbe/table/comments-sheet.tsx | 334 | ||||
| -rw-r--r-- | lib/tbe/table/feature-flags-provider.tsx | 108 | ||||
| -rw-r--r-- | lib/tbe/table/file-dialog.tsx | 141 | ||||
| -rw-r--r-- | lib/tbe/table/invite-vendors-dialog.tsx | 203 | ||||
| -rw-r--r-- | lib/tbe/table/tbe-table-columns.tsx | 249 | ||||
| -rw-r--r-- | lib/tbe/table/tbe-table-toolbar-actions.tsx | 60 | ||||
| -rw-r--r-- | lib/tbe/table/tbe-table.tsx | 204 |
8 files changed, 1299 insertions, 0 deletions
diff --git a/lib/tbe/service.ts b/lib/tbe/service.ts new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/lib/tbe/service.ts diff --git a/lib/tbe/table/comments-sheet.tsx b/lib/tbe/table/comments-sheet.tsx new file mode 100644 index 00000000..7fcde35d --- /dev/null +++ b/lib/tbe/table/comments-sheet.tsx @@ -0,0 +1,334 @@ +"use client" + +import * as React from "react" +import { useForm, useFieldArray } from "react-hook-form" +import { z } from "zod" +import { zodResolver } from "@hookform/resolvers/zod" +import { Loader, Download, X } from "lucide-react" +import prettyBytes from "pretty-bytes" +import { toast } from "sonner" + +import { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" +import { Button } from "@/components/ui/button" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { + Textarea, +} from "@/components/ui/textarea" + +import { + Dropzone, + DropzoneZone, + DropzoneUploadIcon, + DropzoneTitle, + DropzoneDescription, + DropzoneInput +} from "@/components/ui/dropzone" + +import { + Table, + TableHeader, + TableRow, + TableHead, + TableBody, + TableCell +} from "@/components/ui/table" + +// DB 스키마에서 필요한 타입들을 가져온다고 가정 +// (실제 프로젝트에 맞춰 import를 수정하세요.) +import { RfqWithAll } from "@/db/schema/rfq" +import { formatDate } from "@/lib/utils" +import { createRfqCommentWithAttachments } from "@/lib/rfqs/service" + +// 코멘트 + 첨부파일 구조 (단순 예시) +// 실제 DB 스키마에 맞춰 조정 +export interface TbeComment { + id: number + commentText: string + commentedBy?: number + createdAt?: string | Date + attachments?: { + id: number + fileName: string + filePath: string + }[] +} + +interface CommentSheetProps extends React.ComponentPropsWithRef<typeof Sheet> { + /** 코멘트를 작성할 RFQ 정보 */ + /** 이미 존재하는 모든 코멘트 목록 (서버에서 불러와 주입) */ + initialComments?: TbeComment[] + + /** 사용자(작성자) ID (로그인 세션 등에서 가져옴) */ + currentUserId: number + rfqId:number + vendorId:number + /** 댓글 저장 후 갱신용 콜백 (옵션) */ + onCommentsUpdated?: (comments: TbeComment[]) => void +} + +// 새 코멘트 작성 폼 스키마 +const commentFormSchema = z.object({ + commentText: z.string().min(1, "댓글을 입력하세요."), + newFiles: z.array(z.any()).optional() // File[] +}) +type CommentFormValues = z.infer<typeof commentFormSchema> + +const MAX_FILE_SIZE = 30e6 // 30MB + +export function CommentSheet({ + rfqId, + vendorId, + initialComments = [], + currentUserId, + onCommentsUpdated, + ...props +}: CommentSheetProps) { + const [comments, setComments] = React.useState<TbeComment[]>(initialComments) + const [isPending, startTransition] = React.useTransition() + + React.useEffect(() => { + setComments(initialComments) + }, [initialComments]) + + + // RHF 세팅 + const form = useForm<CommentFormValues>({ + resolver: zodResolver(commentFormSchema), + defaultValues: { + commentText: "", + newFiles: [] + } + }) + + // formFieldArray 예시 (파일 목록) + const { fields: newFileFields, append, remove } = useFieldArray({ + control: form.control, + name: "newFiles" + }) + + // 1) 기존 코멘트 + 첨부 보여주기 + // 간단히 테이블 하나로 표현 + // 실제로는 Bubble 형태의 UI, Accordion, Timeline 등 다양하게 구성할 수 있음 + function renderExistingComments() { + if (comments.length === 0) { + return <p className="text-sm text-muted-foreground">No comments yet</p> + } + + return ( + <Table> + <TableHeader> + <TableRow> + <TableHead className="w-1/2">Comment</TableHead> + <TableHead>Attachments</TableHead> + <TableHead>Created At</TableHead> + <TableHead>Created By</TableHead> + </TableRow> + </TableHeader> + <TableBody> + {comments.map((c) => ( + <TableRow key={c.id}> + <TableCell>{c.commentText}</TableCell> + <TableCell> + {/* 첨부파일 표시 */} + {(!c.attachments || c.attachments.length === 0) && ( + <span className="text-sm text-muted-foreground">No files</span> + )} + {c.attachments && c.attachments.length > 0 && ( + <div className="flex flex-col gap-1"> + {c.attachments.map((att) => ( + <div key={att.id} className="flex items-center gap-2"> + <a + href={att.filePath} + download + target="_blank" + rel="noreferrer" + className="inline-flex items-center gap-1 text-blue-600 underline" + > + <Download className="h-4 w-4" /> + {att.fileName} + </a> + </div> + ))} + </div> + )} + </TableCell> + <TableCell> { c.createdAt ? formatDate(c.createdAt): "-"}</TableCell> + <TableCell> + {c.commentedBy ?? "-"} + </TableCell> + </TableRow> + ))} + </TableBody> + </Table> + ) + } + + // 2) 새 파일 Drop + function handleDropAccepted(files: File[]) { + // 드롭된 File[]을 RHF field array에 추가 + const toAppend = files.map((f) => f) + append(toAppend) + } + + + // 3) 저장(Submit) + async function onSubmit(data: CommentFormValues) { + + if (!rfqId) return + startTransition(async () => { + try { + // 서버 액션 호출 + const res = await createRfqCommentWithAttachments({ + rfqId: rfqId, + vendorId: vendorId, // 필요시 세팅 + commentText: data.commentText, + commentedBy: currentUserId, + evaluationId: null, // 필요시 세팅 + files: data.newFiles + }) + + if (!res.ok) { + throw new Error("Failed to create comment") + } + + toast.success("Comment created") + + // 새 코멘트를 다시 불러오거나, + // 여기서는 임시로 "새로운 코멘트가 추가됐다" 라고 가정하여 클라이언트에서 상태 업데이트 + const newComment: TbeComment = { + id: res.commentId, // 서버에서 반환된 commentId + commentText: data.commentText, + commentedBy: currentUserId, + createdAt: new Date().toISOString(), + attachments: (data.newFiles?.map((f, idx) => ({ + id: Math.random() * 100000, + fileName: f.name, + filePath: "/uploads/" + f.name, + })) || []) + } + setComments((prev) => [...prev, newComment]) + onCommentsUpdated?.([...comments, newComment]) + + // 폼 리셋 + form.reset() + } catch (err: any) { + console.error(err) + toast.error("Error: " + err.message) + } + }) + } + + return ( + <Sheet {...props}> + <SheetContent className="flex flex-col gap-6 sm:max-w-lg"> + <SheetHeader className="text-left"> + <SheetTitle>Comments</SheetTitle> + <SheetDescription> + 필요시 첨부파일과 함께 문의/코멘트를 남길 수 있습니다. + </SheetDescription> + </SheetHeader> + + {/* 기존 코멘트 목록 */} + <div className="max-h-[300px] overflow-y-auto"> + {renderExistingComments()} + </div> + + {/* 새 코멘트 작성 Form */} + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4"> + <FormField + control={form.control} + name="commentText" + render={({ field }) => ( + <FormItem> + <FormLabel>New Comment</FormLabel> + <FormControl> + <Textarea + placeholder="Enter your comment..." + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + {/* Dropzone (파일 첨부) */} + <Dropzone + maxSize={MAX_FILE_SIZE} + onDropAccepted={handleDropAccepted} + onDropRejected={(rej) => { + toast.error("File rejected: " + (rej[0]?.file?.name || "")) + }} + > + {({ maxSize }) => ( + <DropzoneZone className="flex justify-center"> + <DropzoneInput /> + <div className="flex items-center gap-6"> + <DropzoneUploadIcon /> + <div className="grid gap-0.5"> + <DropzoneTitle>Drop to attach files</DropzoneTitle> + <DropzoneDescription> + Max size: {prettyBytes(maxSize || 0)} + </DropzoneDescription> + </div> + </div> + </DropzoneZone> + )} + </Dropzone> + + {/* 선택된 파일 목록 */} + {newFileFields.length > 0 && ( + <div className="flex flex-col gap-2"> + {newFileFields.map((field, idx) => { + const file = form.getValues(`newFiles.${idx}`) + if (!file) return null + return ( + <div key={field.id} className="flex items-center justify-between border rounded p-2"> + <span className="text-sm">{file.name} ({prettyBytes(file.size)})</span> + <Button + variant="ghost" + size="icon" + type="button" + onClick={() => remove(idx)} + > + <X className="h-4 w-4" /> + </Button> + </div> + ) + })} + </div> + )} + + <SheetFooter className="gap-2 pt-4"> + <SheetClose asChild> + <Button type="button" variant="outline"> + Cancel + </Button> + </SheetClose> + <Button disabled={isPending}> + {isPending && <Loader className="mr-2 h-4 w-4 animate-spin" />} + Save + </Button> + </SheetFooter> + </form> + </Form> + </SheetContent> + </Sheet> + ) +}
\ No newline at end of file diff --git a/lib/tbe/table/feature-flags-provider.tsx b/lib/tbe/table/feature-flags-provider.tsx new file mode 100644 index 00000000..81131894 --- /dev/null +++ b/lib/tbe/table/feature-flags-provider.tsx @@ -0,0 +1,108 @@ +"use client" + +import * as React from "react" +import { useQueryState } from "nuqs" + +import { dataTableConfig, type DataTableConfig } from "@/config/data-table" +import { cn } from "@/lib/utils" +import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group" +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip" + +type FeatureFlagValue = DataTableConfig["featureFlags"][number]["value"] + +interface FeatureFlagsContextProps { + featureFlags: FeatureFlagValue[] + setFeatureFlags: (value: FeatureFlagValue[]) => void +} + +const FeatureFlagsContext = React.createContext<FeatureFlagsContextProps>({ + featureFlags: [], + setFeatureFlags: () => {}, +}) + +export function useFeatureFlags() { + const context = React.useContext(FeatureFlagsContext) + if (!context) { + throw new Error( + "useFeatureFlags must be used within a FeatureFlagsProvider" + ) + } + return context +} + +interface FeatureFlagsProviderProps { + children: React.ReactNode +} + +export function FeatureFlagsProvider({ children }: FeatureFlagsProviderProps) { + const [featureFlags, setFeatureFlags] = useQueryState<FeatureFlagValue[]>( + "flags", + { + defaultValue: [], + parse: (value) => value.split(",") as FeatureFlagValue[], + serialize: (value) => value.join(","), + eq: (a, b) => + a.length === b.length && a.every((value, index) => value === b[index]), + clearOnDefault: true, + shallow: false, + } + ) + + return ( + <FeatureFlagsContext.Provider + value={{ + featureFlags, + setFeatureFlags: (value) => void setFeatureFlags(value), + }} + > + <div className="w-full overflow-x-auto"> + <ToggleGroup + type="multiple" + variant="outline" + size="sm" + value={featureFlags} + onValueChange={(value: FeatureFlagValue[]) => setFeatureFlags(value)} + className="w-fit gap-0" + > + {dataTableConfig.featureFlags.map((flag, index) => ( + <Tooltip key={flag.value}> + <ToggleGroupItem + value={flag.value} + className={cn( + "gap-2 whitespace-nowrap rounded-none px-3 text-xs data-[state=on]:bg-accent/70 data-[state=on]:hover:bg-accent/90", + { + "rounded-l-sm border-r-0": index === 0, + "rounded-r-sm": + index === dataTableConfig.featureFlags.length - 1, + } + )} + asChild + > + <TooltipTrigger> + <flag.icon className="size-3.5 shrink-0" aria-hidden="true" /> + {flag.label} + </TooltipTrigger> + </ToggleGroupItem> + <TooltipContent + align="start" + side="bottom" + sideOffset={6} + className="flex max-w-60 flex-col space-y-1.5 border bg-background py-2 font-semibold text-foreground" + > + <div>{flag.tooltipTitle}</div> + <div className="text-xs text-muted-foreground"> + {flag.tooltipDescription} + </div> + </TooltipContent> + </Tooltip> + ))} + </ToggleGroup> + </div> + {children} + </FeatureFlagsContext.Provider> + ) +} diff --git a/lib/tbe/table/file-dialog.tsx b/lib/tbe/table/file-dialog.tsx new file mode 100644 index 00000000..b569f2b1 --- /dev/null +++ b/lib/tbe/table/file-dialog.tsx @@ -0,0 +1,141 @@ +"use client" + +import * as React from "react" +import { Download, X } from "lucide-react" +import { toast } from "sonner" + +import { getErrorMessage } from "@/lib/handle-error" +import { formatDateTime } from "@/lib/utils" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" + +import { + FileList, + FileListItem, + FileListIcon, + FileListInfo, + FileListName, + FileListDescription, + FileListAction, +} from "@/components/ui/file-list" +import { getTbeFilesForVendor } from "@/lib/rfqs/service" + +interface TBEFileDialogProps { + isOpen: boolean + onOpenChange: (open: boolean) => void + tbeId: number + vendorId: number + rfqId: number + onRefresh?: () => void +} + +export function TBEFileDialog({ + isOpen, + onOpenChange, + vendorId, + rfqId, + onRefresh, +}: TBEFileDialogProps) { + const [submittedFiles, setSubmittedFiles] = React.useState<any[]>([]) + const [isFetchingFiles, setIsFetchingFiles] = React.useState(false) + + + // Fetch submitted files when dialog opens + React.useEffect(() => { + if (isOpen && rfqId && vendorId) { + fetchSubmittedFiles() + } + }, [isOpen, rfqId, vendorId]) + + // Fetch submitted files using the service function + const fetchSubmittedFiles = async () => { + if (!rfqId || !vendorId) return + + setIsFetchingFiles(true) + try { + const { files, error } = await getTbeFilesForVendor(rfqId, vendorId) + + if (error) { + throw new Error(error) + } + + setSubmittedFiles(files) + } catch (error) { + toast.error("Failed to load files: " + getErrorMessage(error)) + } finally { + setIsFetchingFiles(false) + } + } + + // Download submitted file + const downloadSubmittedFile = async (file: any) => { + try { + const response = await fetch(`/api/file/${file.id}/download`) + if (!response.ok) { + throw new Error("Failed to download file") + } + + const blob = await response.blob() + const url = window.URL.createObjectURL(blob) + const a = document.createElement("a") + a.href = url + a.download = file.fileName + document.body.appendChild(a) + a.click() + window.URL.revokeObjectURL(url) + document.body.removeChild(a) + } catch (error) { + toast.error("Failed to download file: " + getErrorMessage(error)) + } + } + + return ( + <Dialog open={isOpen} onOpenChange={onOpenChange}> + <DialogContent className="sm:max-w-lg"> + <DialogHeader> + <DialogTitle>TBE 응답 파일</DialogTitle> + <DialogDescription>제출된 파일 목록을 확인하고 다운로드하세요.</DialogDescription> + </DialogHeader> + + {/* 제출된 파일 목록 */} + {isFetchingFiles ? ( + <div className="flex justify-center items-center py-8"> + <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div> + </div> + ) : submittedFiles.length > 0 ? ( + <div className="grid gap-2"> + <FileList> + {submittedFiles.map((file) => ( + <FileListItem key={file.id} className="flex items-center justify-between gap-3"> + <div className="flex items-center gap-3 flex-1"> + <FileListIcon className="flex-shrink-0" /> + <FileListInfo className="flex-1 min-w-0"> + <FileListName className="text-sm font-medium truncate">{file.fileName}</FileListName> + <FileListDescription className="text-xs text-muted-foreground"> + {file.uploadedAt ? formatDateTime(file.uploadedAt) : ""} + </FileListDescription> + </FileListInfo> + </div> + <FileListAction className="flex-shrink-0 ml-2"> + <Button variant="ghost" size="icon" onClick={() => downloadSubmittedFile(file)}> + <Download className="h-4 w-4" /> + <span className="sr-only">파일 다운로드</span> + </Button> + </FileListAction> + </FileListItem> + ))} + </FileList> + </div> + ) : ( + <div className="text-center py-8 text-muted-foreground">제출된 파일이 없습니다.</div> + )} + </DialogContent> + </Dialog> + ) +}
\ No newline at end of file diff --git a/lib/tbe/table/invite-vendors-dialog.tsx b/lib/tbe/table/invite-vendors-dialog.tsx new file mode 100644 index 00000000..87467e57 --- /dev/null +++ b/lib/tbe/table/invite-vendors-dialog.tsx @@ -0,0 +1,203 @@ +"use client" + +import * as React from "react" +import { type Row } from "@tanstack/react-table" +import { Loader, Send } from "lucide-react" +import { toast } from "sonner" + +import { useMediaQuery } from "@/hooks/use-media-query" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog" +import { + Drawer, + DrawerClose, + DrawerContent, + DrawerDescription, + DrawerFooter, + DrawerHeader, + DrawerTitle, + DrawerTrigger, +} from "@/components/ui/drawer" + +import { Input } from "@/components/ui/input" + +import { VendorWithTbeFields } from "@/config/vendorTbeColumnsConfig" +import { inviteTbeVendorsAction } from "@/lib/rfqs/service" + +interface InviteVendorsDialogProps + extends React.ComponentPropsWithoutRef<typeof Dialog> { + vendors: Row<VendorWithTbeFields>["original"][] + rfqId: number + showTrigger?: boolean + onSuccess?: () => void +} + +export function InviteVendorsDialog({ + vendors, + rfqId, + showTrigger = true, + onSuccess, + ...props +}: InviteVendorsDialogProps) { + const [isInvitePending, startInviteTransition] = React.useTransition() + + + // multiple 파일을 받을 state + const [files, setFiles] = React.useState<FileList | null>(null) + + // 미디어쿼리 (desktop 여부) + const isDesktop = useMediaQuery("(min-width: 640px)") + + function onInvite() { + startInviteTransition(async () => { + // 파일이 선택되지 않았다면 에러 + if (!files || files.length === 0) { + toast.error("Please attach TBE files before inviting.") + return + } + + // FormData 생성 + const formData = new FormData() + formData.append("rfqId", String(rfqId)) + vendors.forEach((vendor) => { + formData.append("vendorIds[]", String(vendor.id)) + }) + + // multiple 파일 + for (let i = 0; i < files.length; i++) { + formData.append("tbeFiles", files[i]) // key는 동일하게 "tbeFiles" + } + + // 서버 액션 호출 + const { error } = await inviteTbeVendorsAction(formData) + + if (error) { + toast.error(error) + return + } + + // 성공 + props.onOpenChange?.(false) + toast.success("Vendors invited with TBE!") + onSuccess?.() + }) + } + + // 파일 선택 UI + const fileInput = ( + <div className="mb-4"> + <label className="mb-2 block font-medium">TBE Sheets</label> + <Input + type="file" + multiple + onChange={(e) => { + setFiles(e.target.files) + }} + /> + </div> + ) + + // Desktop Dialog + if (isDesktop) { + return ( + <Dialog {...props}> + {showTrigger ? ( + <DialogTrigger asChild> + <Button variant="outline" size="sm"> + <Send className="mr-2 size-4" aria-hidden="true" /> + Invite ({vendors.length}) + </Button> + </DialogTrigger> + ) : null} + <DialogContent> + <DialogHeader> + <DialogTitle>Are you absolutely sure?</DialogTitle> + <DialogDescription> + This action cannot be undone. This will permanently invite{" "} + <span className="font-medium">{vendors.length}</span> + {vendors.length === 1 ? " vendor" : " vendors"}. 파일 첨부가 필수이므로 파일을 첨부해야지 버튼이 활성화됩니다. + </DialogDescription> + </DialogHeader> + + {/* 파일 첨부 */} + {fileInput} + + <DialogFooter className="gap-2 sm:space-x-0"> + <DialogClose asChild> + <Button variant="outline">Cancel</Button> + </DialogClose> + <Button + aria-label="Invite selected rows" + variant="destructive" + onClick={onInvite} + // 파일이 없거나 초대 진행중이면 비활성화 + disabled={isInvitePending || !files || files.length === 0} + > + {isInvitePending && ( + <Loader + className="mr-2 size-4 animate-spin" + aria-hidden="true" + /> + )} + Invite + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + ) + } + + // Mobile Drawer + return ( + <Drawer {...props}> + {showTrigger ? ( + <DrawerTrigger asChild> + <Button variant="outline" size="sm"> + <Send className="mr-2 size-4" aria-hidden="true" /> + Invite ({vendors.length}) + </Button> + </DrawerTrigger> + ) : null} + <DrawerContent> + <DrawerHeader> + <DrawerTitle>Are you absolutely sure?</DrawerTitle> + <DrawerDescription> + This action cannot be undone. This will permanently invite{" "} + <span className="font-medium">{vendors.length}</span> + {vendors.length === 1 ? " vendor" : " vendors"}. + </DrawerDescription> + </DrawerHeader> + + {/* 파일 첨부 */} + {fileInput} + + <DrawerFooter className="gap-2 sm:space-x-0"> + <DrawerClose asChild> + <Button variant="outline">Cancel</Button> + </DrawerClose> + <Button + aria-label="Invite selected rows" + variant="destructive" + onClick={onInvite} + // 파일이 없거나 초대 진행중이면 비활성화 + disabled={isInvitePending || !files || files.length === 0} + > + {isInvitePending && ( + <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" /> + )} + Invite + </Button> + </DrawerFooter> + </DrawerContent> + </Drawer> + ) +}
\ No newline at end of file diff --git a/lib/tbe/table/tbe-table-columns.tsx b/lib/tbe/table/tbe-table-columns.tsx new file mode 100644 index 00000000..f2bc2ced --- /dev/null +++ b/lib/tbe/table/tbe-table-columns.tsx @@ -0,0 +1,249 @@ +"use client" + +import * as React from "react" +import { type DataTableRowAction } from "@/types/table" +import { type ColumnDef } from "@tanstack/react-table" +import { Download, Ellipsis, MessageSquare } from "lucide-react" +import { toast } from "sonner" + +import { getErrorMessage } from "@/lib/handle-error" +import { formatDate } from "@/lib/utils" +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { useRouter } from "next/navigation" + +import { + VendorTbeColumnConfig, + vendorTbeColumnsConfig, + VendorWithTbeFields, +} from "@/config/vendorTbeColumnsConfig" + +type NextRouter = ReturnType<typeof useRouter> + +interface GetColumnsProps { + setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<VendorWithTbeFields> | null>> + router: NextRouter + openCommentSheet: (vendorId: number, rfqId: number) => void + openFilesDialog: (tbeId: number, vendorId: number, rfqId: number) => void +} + + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ + setRowAction, + router, + openCommentSheet, + openFilesDialog +}: GetColumnsProps): ColumnDef<VendorWithTbeFields>[] { + // ---------------------------------------------------------------- + // 1) Select 컬럼 (체크박스) + // ---------------------------------------------------------------- + const selectColumn: ColumnDef<VendorWithTbeFields> = { + id: "select", + header: ({ table }) => ( + <Checkbox + checked={ + table.getIsAllPageRowsSelected() || + (table.getIsSomePageRowsSelected() && "indeterminate") + } + onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} + aria-label="Select all" + className="translate-y-0.5" + /> + ), + cell: ({ row }) => ( + <Checkbox + checked={row.getIsSelected()} + onCheckedChange={(value) => row.toggleSelected(!!value)} + aria-label="Select row" + className="translate-y-0.5" + /> + ), + size: 40, + enableSorting: false, + enableHiding: false, + } + + // ---------------------------------------------------------------- + // 2) 그룹화(Nested) 컬럼 구성 + // ---------------------------------------------------------------- + const groupMap: Record<string, ColumnDef<VendorWithTbeFields>[]> = {} + + vendorTbeColumnsConfig.forEach((cfg) => { + const groupName = cfg.group || "_noGroup" + if (!groupMap[groupName]) { + groupMap[groupName] = [] + } + + // childCol: ColumnDef<VendorWithTbeFields> + const childCol: ColumnDef<VendorWithTbeFields> = { + accessorKey: cfg.id, + enableResizing: true, + header: ({ column }) => ( + <DataTableColumnHeaderSimple column={column} title={cfg.label} /> + ), + meta: { + excelHeader: cfg.excelHeader, + group: cfg.group, + type: cfg.type, + }, + // 셀 렌더링 + cell: ({ row, getValue }) => { + // 1) 필드값 가져오기 + const val = getValue() + + if (cfg.id === "vendorStatus") { + const statusVal = row.original.vendorStatus + if (!statusVal) return null + // const Icon = getStatusIcon(statusVal) + return ( + <Badge variant="outline"> + {statusVal} + </Badge> + ) + } + + + if (cfg.id === "rfqVendorStatus") { + const statusVal = row.original.rfqVendorStatus + if (!statusVal) return null + // const Icon = getStatusIcon(statusVal) + const variant = statusVal ==="INVITED"?"default" :statusVal ==="DECLINED"?"destructive":statusVal ==="ACCEPTED"?"secondary":"outline" + return ( + <Badge variant={variant}> + {statusVal} + </Badge> + ) + } + + // 예) TBE Updated (날짜) + if (cfg.id === "tbeUpdated") { + const dateVal = val as Date | undefined + if (!dateVal) return null + return formatDate(dateVal) + } + + // 그 외 필드는 기본 값 표시 + return val ?? "" + }, + } + + groupMap[groupName].push(childCol) + }) + + // groupMap → nestedColumns + const nestedColumns: ColumnDef<VendorWithTbeFields>[] = [] + Object.entries(groupMap).forEach(([groupName, colDefs]) => { + if (groupName === "_noGroup") { + nestedColumns.push(...colDefs) + } else { + nestedColumns.push({ + id: groupName, + header: groupName, + columns: colDefs, + }) + } + }) +// 파일 칼럼 +const filesColumn: ColumnDef<VendorWithTbeFields> = { + id: "files", + header: ({ column }) => ( + <DataTableColumnHeaderSimple column={column} title="Response Files" /> + ), + cell: ({ row }) => { + const vendor = row.original + const filesCount = vendor.files?.length ?? 0 + + function handleClick() { + // setRowAction으로 타입만 설정하고 끝내는 방법도 가능하지만 + // 혹은 바로 openFilesDialog()를 호출해도 됨. + setRowAction({ row, type: "files" }) + // 필요한 값을 직접 호출해서 넘겨줄 수도 있음. + openFilesDialog( + vendor.tbeId ?? 0, + vendor.vendorId ?? 0, + vendor.rfqId ?? 0, + ) + } + + return ( + <Button + variant="ghost" + size="sm" + className="relative h-8 w-8 p-0 group" + onClick={handleClick} + aria-label={filesCount > 0 ? `View ${filesCount} files` : "Upload file"} + > + <Download className="h-4 w-4" /> + {filesCount > 0 && ( + <Badge variant="secondary" className="absolute -top-1 -right-1 h-4 min-w-[1rem] p-0 text-[0.625rem] leading-none flex items-center justify-center"> + {filesCount} + </Badge> + )} + </Button> + ) + }, + enableSorting: false, + maxSize: 80, +} + +// 댓글 칼럼 +const commentsColumn: ColumnDef<VendorWithTbeFields> = { + id: "comments", + header: ({ column }) => ( + <DataTableColumnHeaderSimple column={column} title="Comments" /> + ), + cell: ({ row }) => { + const vendor = row.original + const commCount = vendor.comments?.length ?? 0 + + function handleClick() { + // setRowAction() 로 type 설정 + setRowAction({ row, type: "comments" }) + // 필요하면 즉시 openCommentSheet() 직접 호출 + openCommentSheet( + vendor.vendorId ?? 0, + vendor.rfqId ?? 0, + ) + } + + return ( + <Button variant="ghost" size="sm" className="h-8 w-8 p-0 group relative" onClick={handleClick}> + <MessageSquare className="h-4 w-4" /> + {commCount > 0 && ( + <Badge variant="secondary" className="absolute -top-1 -right-1 h-4 min-w-[1rem] text-[0.625rem] p-0 flex items-center justify-center"> + {commCount} + </Badge> + )} + </Button> + ) + }, + enableSorting: false, + maxSize: 80, +} +// ---------------------------------------------------------------- +// 5) 최종 컬럼 배열 - Update to include the files column +// ---------------------------------------------------------------- +return [ + selectColumn, + ...nestedColumns, + filesColumn, // Add the files column before comments + commentsColumn, + // actionsColumn, +] + +}
\ No newline at end of file diff --git a/lib/tbe/table/tbe-table-toolbar-actions.tsx b/lib/tbe/table/tbe-table-toolbar-actions.tsx new file mode 100644 index 00000000..6a336135 --- /dev/null +++ b/lib/tbe/table/tbe-table-toolbar-actions.tsx @@ -0,0 +1,60 @@ +"use client" + +import * as React from "react" +import { type Table } from "@tanstack/react-table" +import { Download, Upload } from "lucide-react" +import { toast } from "sonner" + +import { exportTableToExcel } from "@/lib/export" +import { Button } from "@/components/ui/button" + + +import { InviteVendorsDialog } from "./invite-vendors-dialog" +import { VendorWithTbeFields } from "@/config/vendorTbeColumnsConfig" + +interface VendorsTableToolbarActionsProps { + table: Table<VendorWithTbeFields> + rfqId: number +} + +export function VendorsTableToolbarActions({ table,rfqId }: VendorsTableToolbarActionsProps) { + // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식 + const fileInputRef = React.useRef<HTMLInputElement>(null) + + // 파일이 선택되었을 때 처리 + + function handleImportClick() { + // 숨겨진 <input type="file" /> 요소를 클릭 + fileInputRef.current?.click() + } + + return ( + <div className="flex items-center gap-2"> + {table.getFilteredSelectedRowModel().rows.length > 0 ? ( + <InviteVendorsDialog + vendors={table + .getFilteredSelectedRowModel() + .rows.map((row) => row.original)} + rfqId = {rfqId} + onSuccess={() => table.toggleAllRowsSelected(false)} + /> + ) : null} + + + <Button + variant="outline" + size="sm" + onClick={() => + exportTableToExcel(table, { + filename: "tasks", + excludeColumns: ["select", "actions"], + }) + } + className="gap-2" + > + <Download className="size-4" aria-hidden="true" /> + <span className="hidden sm:inline">Export</span> + </Button> + </div> + ) +}
\ No newline at end of file diff --git a/lib/tbe/table/tbe-table.tsx b/lib/tbe/table/tbe-table.tsx new file mode 100644 index 00000000..ed323800 --- /dev/null +++ b/lib/tbe/table/tbe-table.tsx @@ -0,0 +1,204 @@ +"use client" + +import * as React from "react" +import { useRouter } from "next/navigation" +import type { + DataTableAdvancedFilterField, + DataTableFilterField, + DataTableRowAction, +} from "@/types/table" + +import { toSentenceCase } from "@/lib/utils" +import { useDataTable } from "@/hooks/use-data-table" +import { DataTable } from "@/components/data-table/data-table" +import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar" +import { useFeatureFlags } from "./feature-flags-provider" +import { getColumns } from "./tbe-table-columns" +import { Vendor, vendors } from "@/db/schema/vendors" +import { InviteVendorsDialog } from "./invite-vendors-dialog" +import { CommentSheet, TbeComment } from "./comments-sheet" +import { VendorWithTbeFields } from "@/config/vendorTbeColumnsConfig" +import { TBEFileDialog } from "./file-dialog" +import { fetchRfqAttachmentsbyCommentId, getAllTBE } from "@/lib/rfqs/service" +import { VendorsTableToolbarActions } from "./tbe-table-toolbar-actions" + +interface VendorsTableProps { + promises: Promise<[ + Awaited<ReturnType<typeof getAllTBE>>, + ]> +} + +export function AllTbeTable({ promises }: VendorsTableProps) { + const { featureFlags } = useFeatureFlags() + const router = useRouter() + + // Suspense로 받아온 데이터 + const [{ data, pageCount }] = React.use(promises) + + const [rowAction, setRowAction] = React.useState<DataTableRowAction<VendorWithTbeFields> | null>(null) + + // 댓글 시트 관련 state + const [initialComments, setInitialComments] = React.useState<TbeComment[]>([]) + const [commentSheetOpen, setCommentSheetOpen] = React.useState(false) + const [selectedVendorIdForComments, setSelectedVendorIdForComments] = React.useState<number | null>(null) + const [selectedRfqIdForComments, setSelectedRfqIdForComments] = React.useState<number | null>(null) + + // 파일 다이얼로그 관련 state + const [isFileDialogOpen, setIsFileDialogOpen] = React.useState(false) + const [selectedVendorIdForFiles, setSelectedVendorIdForFiles] = React.useState<number | null>(null) + const [selectedTbeIdForFiles, setSelectedTbeIdForFiles] = React.useState<number | null>(null) + const [selectedRfqIdForFiles, setSelectedRfqIdForFiles] = React.useState<number | null>(null) + + // 테이블 리프레시용 + const handleRefresh = React.useCallback(() => { + router.refresh(); + }, [router]); + + // ----------------------------------------------------------- + // 특정 action이 설정될 때마다 실행되는 effect + // ----------------------------------------------------------- + React.useEffect(() => { + if (!rowAction) return + + if (rowAction.type === "comments") { + // rowAction가 새로 세팅되면 openCommentSheet 실행 + // row.original에 rfqId가 있다고 가정 + openCommentSheet( + rowAction.row.original.vendorId ?? 0, + rowAction.row.original.rfqId ?? 0, + ) + } else if (rowAction.type === "files") { + openFilesDialog( + rowAction.row.original.tbeId ?? 0, + rowAction.row.original.vendorId ?? 0, + rowAction.row.original.rfqId ?? 0, + ) + } + }, [rowAction]) + + // ----------------------------------------------------------- + // 댓글 시트 열기 + // ----------------------------------------------------------- + async function openCommentSheet(vendorId: number, rfqId: number) { + setInitialComments([]) + + const comments = rowAction?.row.original.comments + if (comments && comments.length > 0) { + const commentWithAttachments: TbeComment[] = await Promise.all( + comments.map(async (c) => { + const attachments = await fetchRfqAttachmentsbyCommentId(c.id) + return { + ...c, + commentedBy: 1, // DB나 API 응답에 있다고 가정 + attachments, + } + }) + ) + setInitialComments(commentWithAttachments) + } + + setSelectedVendorIdForComments(vendorId) + setSelectedRfqIdForComments(rfqId) + setCommentSheetOpen(true) + } + + // ----------------------------------------------------------- + // 파일 다이얼로그 열기 + // ----------------------------------------------------------- + const openFilesDialog = (tbeId: number, vendorId: number, rfqId: number) => { + setSelectedTbeIdForFiles(tbeId) + setSelectedVendorIdForFiles(vendorId) + setSelectedRfqIdForFiles(rfqId) + setIsFileDialogOpen(true) + } + + // ----------------------------------------------------------- + // 테이블 컬럼 + // ----------------------------------------------------------- + const columns = React.useMemo( + () => + getColumns({ + setRowAction, + router, + openCommentSheet, // 필요하면 직접 호출 가능 + openFilesDialog, + }), + [setRowAction, router] + ) + + // ----------------------------------------------------------- + // 필터 필드 + // ----------------------------------------------------------- + const filterFields: DataTableFilterField<VendorWithTbeFields>[] = [ + // 예: 표준 필터 + ] + const advancedFilterFields: DataTableAdvancedFilterField<VendorWithTbeFields>[] = [ + { id: "vendorName", label: "Vendor Name", type: "text" }, + { id: "vendorCode", label: "Vendor Code", type: "text" }, + { id: "email", label: "Email", type: "text" }, + { id: "country", label: "Country", type: "text" }, + { + id: "vendorStatus", + label: "Vendor Status", + type: "multi-select", + options: vendors.status.enumValues.map((status) => ({ + label: toSentenceCase(status), + value: status, + })), + }, + { id: "rfqVendorUpdated", label: "Updated at", type: "date" }, + ] + + // ----------------------------------------------------------- + // 테이블 생성 훅 + // ----------------------------------------------------------- + const { table } = useDataTable({ + data, + columns, + pageCount, + filterFields, + enablePinning: true, + enableAdvancedFilter: true, + initialState: { + sorting: [{ id: "rfqVendorUpdated", desc: true }], + columnPinning: { right: ["actions"] }, + }, + getRowId: (originalRow) => String(originalRow.id), + shallow: false, + clearOnDefault: true, + }) + + return ( + <> + <DataTable table={table}> + <DataTableAdvancedToolbar + table={table} + filterFields={advancedFilterFields} + shallow={false} + > + <VendorsTableToolbarActions table={table} rfqId={selectedRfqIdForFiles ?? 0} /> + </DataTableAdvancedToolbar> + </DataTable> + + {/* 댓글 시트 */} + <CommentSheet + currentUserId={1} + open={commentSheetOpen} + onOpenChange={setCommentSheetOpen} + vendorId={selectedVendorIdForComments ?? 0} + rfqId={selectedRfqIdForComments ?? 0} // ← 여기! + initialComments={initialComments} + /> + + {/* 파일 업로드/다운로드 다이얼로그 */} + <TBEFileDialog + isOpen={isFileDialogOpen} + onOpenChange={setIsFileDialogOpen} + tbeId={selectedTbeIdForFiles ?? 0} + vendorId={selectedVendorIdForFiles ?? 0} + rfqId={selectedRfqIdForFiles ?? 0} // ← 여기! + onRefresh={handleRefresh} + /> + </> + ) +}
\ No newline at end of file |
