diff options
Diffstat (limited to 'lib/techsales-rfq/table')
4 files changed, 453 insertions, 9 deletions
diff --git a/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx b/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx index fe9befe5..d3a12385 100644 --- a/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx +++ b/lib/techsales-rfq/table/detail-table/rfq-detail-column.tsx @@ -5,7 +5,7 @@ import type { ColumnDef, Row } from "@tanstack/react-table"; import { formatDate } from "@/lib/utils"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { Checkbox } from "@/components/ui/checkbox";
-import { MessageCircle, MoreHorizontal, Trash2, Paperclip, Users } from "lucide-react";
+import { MessageCircle, MoreHorizontal, Trash2, Paperclip, Users, Mail } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
@@ -79,6 +79,7 @@ interface GetColumnsProps<TData> { onQuotationClick?: (quotationId: number) => void; // 견적 클릭 핸들러
openQuotationAttachmentsSheet?: (quotationId: number, quotationInfo: QuotationInfo) => void; // 견적서 첨부파일 sheet 열기
openContactsDialog?: (quotationId: number, vendorName?: string) => void; // 담당자 조회 다이얼로그 열기
+ openEmlAttachmentsSheet?: (quotationId: number, quotationInfo: QuotationInfo) => void; // eml 첨부파일 sheet 열기
}
export function getRfqDetailColumns({
@@ -86,7 +87,8 @@ export function getRfqDetailColumns({ unreadMessages = {},
onQuotationClick,
openQuotationAttachmentsSheet,
- openContactsDialog
+ openContactsDialog,
+ openEmlAttachmentsSheet
}: GetColumnsProps<RfqDetailView>): ColumnDef<RfqDetailView>[] {
return [
{
@@ -351,6 +353,42 @@ export function getRfqDetailColumns({ size: 80,
},
{
+ id: "emlAttachments",
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title="eml 첨부" />
+ ),
+ cell: ({ row }) => {
+ const quotation = row.original;
+ const handleClick = () => {
+ if (!openEmlAttachmentsSheet) return;
+ openEmlAttachmentsSheet(quotation.id, {
+ id: quotation.id,
+ quotationCode: quotation.quotationCode || null,
+ vendorName: quotation.vendorName || undefined,
+ rfqCode: quotation.rfqCode || undefined,
+ });
+ };
+
+ return (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 w-8 p-0 group"
+ onClick={handleClick}
+ aria-label="eml 첨부파일 관리"
+ title="eml 첨부파일 관리"
+ >
+ <Mail className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
+ </Button>
+ );
+ },
+ meta: {
+ excelHeader: "eml 첨부"
+ },
+ enableResizing: false,
+ size: 80,
+ },
+ {
id: "contacts",
header: "담당자",
cell: ({ row }) => {
diff --git a/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx b/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx index 72f03dc3..d8ced6f8 100644 --- a/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx +++ b/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx @@ -19,6 +19,7 @@ import { VendorCommunicationDrawer } from "./vendor-communication-drawer" import { DeleteVendorDialog } from "./delete-vendors-dialog"
import { QuotationHistoryDialog } from "@/lib/techsales-rfq/table/detail-table/quotation-history-dialog"
import { TechSalesQuotationAttachmentsSheet, type QuotationAttachment } from "../tech-sales-quotation-attachments-sheet"
+import { TechSalesVendorEmlAttachmentsSheet, type VendorEmlAttachment } from "../tech-sales-vendor-eml-attachments-sheet"
import type { QuotationInfo } from "./rfq-detail-column"
import { VendorContactSelectionDialog } from "./vendor-contact-selection-dialog"
import { QuotationContactsViewDialog } from "./quotation-contacts-view-dialog"
@@ -89,6 +90,12 @@ export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps const [quotationAttachments, setQuotationAttachments] = useState<QuotationAttachment[]>([])
const [isLoadingAttachments, setIsLoadingAttachments] = useState(false)
+ // eml 첨부파일 sheet 상태 관리
+ const [emlAttachmentsSheetOpen, setEmlAttachmentsSheetOpen] = useState(false)
+ const [selectedQuotationForEml, setSelectedQuotationForEml] = useState<QuotationInfo | null>(null)
+ const [emlAttachments, setEmlAttachments] = useState<VendorEmlAttachment[]>([])
+ const [isLoadingEmlAttachments, setIsLoadingEmlAttachments] = useState(false)
+
// 벤더 contact 선택 다이얼로그 상태 관리
const [contactSelectionDialogOpen, setContactSelectionDialogOpen] = useState(false)
@@ -250,7 +257,7 @@ export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps contactId: number;
contactEmail: string;
contactName: string;
- }>) => {
+ }>, options?: { hideProjectInfoForVendors?: boolean }) => {
if (!selectedRfqId) {
toast.error("선택된 RFQ가 없습니다.");
return;
@@ -294,6 +301,7 @@ export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps name: session.data.user.name || undefined,
email: session.data.user.email || undefined,
},
+ hideProjectInfoForVendors: options?.hideProjectInfoForVendors,
});
if (result.success) {
@@ -463,6 +471,31 @@ export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps }
}, [])
+ // eml 첨부파일 sheet 열기 핸들러
+ const handleOpenEmlAttachmentsSheet = useCallback(async (quotationId: number, quotationInfo: QuotationInfo) => {
+ try {
+ setIsLoadingEmlAttachments(true)
+ setSelectedQuotationForEml(quotationInfo)
+ setEmlAttachmentsSheetOpen(true)
+
+ const { getTechSalesVendorQuotationEmlAttachments } = await import("@/lib/techsales-rfq/service")
+ const result = await getTechSalesVendorQuotationEmlAttachments(quotationId)
+
+ if (result.error) {
+ toast.error(result.error)
+ setEmlAttachments([])
+ } else {
+ setEmlAttachments(result.data || [])
+ }
+ } catch (error) {
+ console.error("eml 첨부파일 조회 오류:", error)
+ toast.error("eml 첨부파일을 불러오는 중 오류가 발생했습니다.")
+ setEmlAttachments([])
+ } finally {
+ setIsLoadingEmlAttachments(false)
+ }
+ }, [])
+
// 담당자 조회 다이얼로그 열기 함수
const handleOpenContactsDialog = useCallback((quotationId: number, vendorName?: string) => {
setSelectedQuotationForContacts({ id: quotationId, vendorName })
@@ -554,8 +587,9 @@ export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps unreadMessages,
onQuotationClick: handleOpenHistoryDialog,
openQuotationAttachmentsSheet: handleOpenQuotationAttachmentsSheet,
- openContactsDialog: handleOpenContactsDialog
- }), [unreadMessages, handleOpenHistoryDialog, handleOpenQuotationAttachmentsSheet, handleOpenContactsDialog])
+ openContactsDialog: handleOpenContactsDialog,
+ openEmlAttachmentsSheet: handleOpenEmlAttachmentsSheet
+ }), [unreadMessages, handleOpenHistoryDialog, handleOpenQuotationAttachmentsSheet, handleOpenContactsDialog, handleOpenEmlAttachmentsSheet])
// 필터 필드 정의 (메모이제이션)
const advancedFilterFields = useMemo(
@@ -928,6 +962,16 @@ export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps isLoading={isLoadingAttachments}
/>
+ {/* eml 첨부파일 Sheet */}
+ <TechSalesVendorEmlAttachmentsSheet
+ open={emlAttachmentsSheetOpen}
+ onOpenChange={setEmlAttachmentsSheetOpen}
+ quotation={selectedQuotationForEml}
+ attachments={emlAttachments}
+ isLoading={isLoadingEmlAttachments}
+ onAttachmentsChange={setEmlAttachments}
+ />
+
{/* 벤더 contact 선택 다이얼로그 */}
<VendorContactSelectionDialog
open={contactSelectionDialogOpen}
diff --git a/lib/techsales-rfq/table/detail-table/vendor-contact-selection-dialog.tsx b/lib/techsales-rfq/table/detail-table/vendor-contact-selection-dialog.tsx index d83394bb..8daa9be7 100644 --- a/lib/techsales-rfq/table/detail-table/vendor-contact-selection-dialog.tsx +++ b/lib/techsales-rfq/table/detail-table/vendor-contact-selection-dialog.tsx @@ -49,7 +49,10 @@ interface VendorContactSelectionDialogProps { onOpenChange: (open: boolean) => void
vendorIds: number[]
rfqId?: number // RFQ ID 추가
- onSendRfq: (selectedContacts: SelectedContact[]) => Promise<void>
+ onSendRfq: (
+ selectedContacts: SelectedContact[],
+ options: { hideProjectInfoForVendors: boolean }
+ ) => Promise<void>
}
export function VendorContactSelectionDialog({
@@ -63,6 +66,7 @@ export function VendorContactSelectionDialog({ const [selectedContacts, setSelectedContacts] = useState<SelectedContact[]>([])
const [isLoading, setIsLoading] = useState(false)
const [isSending, setIsSending] = useState(false)
+ const [hideProjectInfoForVendors, setHideProjectInfoForVendors] = useState(false)
// 벤더 contact 정보 조회
useEffect(() => {
@@ -77,6 +81,7 @@ export function VendorContactSelectionDialog({ setVendorsWithContacts({})
setSelectedContacts([])
setIsLoading(false)
+ setHideProjectInfoForVendors(false)
}
}, [open])
@@ -177,7 +182,7 @@ export function VendorContactSelectionDialog({ try {
setIsSending(true)
- await onSendRfq(selectedContacts)
+ await onSendRfq(selectedContacts, { hideProjectInfoForVendors })
onOpenChange(false)
} catch (error) {
console.error("RFQ 발송 오류:", error)
@@ -328,8 +333,17 @@ export function VendorContactSelectionDialog({ <DialogFooter>
<div className="flex items-center justify-between w-full">
- <div className="text-sm text-muted-foreground">
- 총 {selectedContacts.length}명의 연락처가 선택됨
+ <div className="flex flex-col gap-2">
+ <div className="text-sm text-muted-foreground">
+ 총 {selectedContacts.length}명의 연락처가 선택됨
+ </div>
+ <label className="flex items-center gap-2 text-sm">
+ <Checkbox
+ checked={hideProjectInfoForVendors}
+ onCheckedChange={(checked) => setHideProjectInfoForVendors(!!checked)}
+ />
+ 벤더 화면에서 프로젝트명/선주명을 숨기기
+ </label>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>
diff --git a/lib/techsales-rfq/table/tech-sales-vendor-eml-attachments-sheet.tsx b/lib/techsales-rfq/table/tech-sales-vendor-eml-attachments-sheet.tsx new file mode 100644 index 00000000..2b6f6753 --- /dev/null +++ b/lib/techsales-rfq/table/tech-sales-vendor-eml-attachments-sheet.tsx @@ -0,0 +1,348 @@ +"use client" + +import * as React from "react" +import { + Sheet, + SheetContent, + SheetHeader, + SheetTitle, + SheetDescription, + SheetFooter, + SheetClose, +} from "@/components/ui/sheet" +import { Button } from "@/components/ui/button" +import { + Dropzone, + DropzoneDescription, + DropzoneInput, + DropzoneTitle, + DropzoneUploadIcon, + DropzoneZone, +} from "@/components/ui/dropzone" +import { + FileList, + FileListAction, + FileListDescription, + FileListHeader, + FileListIcon, + FileListInfo, + FileListItem, + FileListName, +} from "@/components/ui/file-list" +import { Badge } from "@/components/ui/badge" +import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel } from "@/components/ui/form" +import { toast } from "sonner" +import { Download, Loader, Trash2, X } from "lucide-react" +import prettyBytes from "pretty-bytes" +import { useSession } from "next-auth/react" +import { useForm } from "react-hook-form" +import { formatDate } from "@/lib/utils" +import { + getTechSalesVendorQuotationEmlAttachments, + processTechSalesVendorQuotationEmlAttachments, +} from "@/lib/techsales-rfq/service" + +const MAX_FILE_SIZE = 6e8 // 600MB + +export interface VendorEmlAttachment { + id: number + quotationId: number + revisionId: number + fileName: string + originalFileName: string + fileSize: number + fileType: string | null + filePath: string + description: string | null + uploadedBy: number | null + vendorId: number | null + isVendorUpload: boolean + createdAt: Date + updatedAt: Date +} + +interface QuotationInfo { + id: number + quotationCode: string | null + vendorName?: string + rfqCode?: string +} + +interface TechSalesVendorEmlAttachmentsSheetProps extends React.ComponentPropsWithRef<typeof Sheet> { + quotation: QuotationInfo | null + attachments: VendorEmlAttachment[] + onAttachmentsChange?: (attachments: VendorEmlAttachment[]) => void + isLoading?: boolean +} + +export function TechSalesVendorEmlAttachmentsSheet({ + quotation, + attachments, + onAttachmentsChange, + isLoading = false, + ...props +}: TechSalesVendorEmlAttachmentsSheetProps) { + const session = useSession() + const [isPending, setIsPending] = React.useState(false) + const [existing, setExisting] = React.useState<VendorEmlAttachment[]>(attachments) + const [newUploads, setNewUploads] = React.useState<File[]>([]) + const [deleteIds, setDeleteIds] = React.useState<number[]>([]) + + const form = useForm({ + defaultValues: { + dummy: true, + }, + }) + + // sync when parent changes + React.useEffect(() => { + setExisting(attachments) + setNewUploads([]) + setDeleteIds([]) + }, [attachments]) + + const handleDownloadClick = React.useCallback(async (attachment: VendorEmlAttachment) => { + try { + const { downloadFile } = await import("@/lib/file-download") + await downloadFile(attachment.filePath, attachment.originalFileName || attachment.fileName, { + showToast: true, + onError: (error) => { + console.error("다운로드 오류:", error) + toast.error(error) + }, + }) + } catch (error) { + console.error("다운로드 오류:", error) + toast.error("파일 다운로드 중 오류가 발생했습니다.") + } + }, []) + + const handleDropAccepted = React.useCallback((accepted: File[]) => { + setNewUploads((prev) => [...prev, ...accepted]) + }, []) + + const handleDropRejected = React.useCallback(() => { + toast.error("파일 크기가 너무 크거나 지원하지 않는 형식입니다.") + }, []) + + const handleRemoveExisting = React.useCallback((id: number) => { + setDeleteIds((prev) => (prev.includes(id) ? prev : [...prev, id])) + setExisting((prev) => prev.filter((att) => att.id !== id)) + }, []) + + const handleRemoveNewUpload = React.useCallback((index: number) => { + setNewUploads((prev) => prev.filter((_, i) => i !== index)) + }, []) + + const handleSubmit = async () => { + if (!quotation) { + toast.error("견적 정보를 찾을 수 없습니다.") + return + } + + const userId = Number(session.data?.user.id || 0) + if (!userId) { + toast.error("로그인 정보를 확인해주세요.") + return + } + + setIsPending(true) + try { + const result = await processTechSalesVendorQuotationEmlAttachments({ + quotationId: quotation.id, + newFiles: newUploads.map((file) => ({ file })), + deleteAttachmentIds: deleteIds, + uploadedBy: userId, + }) + + if (result.error) { + toast.error(result.error) + return + } + + const refreshed = + result.data || + (await getTechSalesVendorQuotationEmlAttachments(quotation.id)).data || + [] + + setExisting(refreshed) + setNewUploads([]) + setDeleteIds([]) + onAttachmentsChange?.(refreshed) + toast.success("Eml 첨부파일이 저장되었습니다.") + props.onOpenChange?.(false) + } catch (error) { + console.error("eml 첨부파일 저장 오류:", error) + toast.error("eml 첨부파일 저장 중 오류가 발생했습니다.") + } finally { + setIsPending(false) + } + } + + const totalNewSize = newUploads.reduce((acc, f) => acc + f.size, 0) + + return ( + <Sheet {...props}> + <SheetContent className="flex flex-col gap-6 sm:max-w-md"> + <SheetHeader className="text-left"> + <SheetTitle>eml 첨부파일</SheetTitle> + <SheetDescription> + <div className="space-y-1"> + {quotation?.vendorName && <div>벤더: {quotation.vendorName}</div>} + {quotation?.rfqCode && <div>RFQ: {quotation.rfqCode}</div>} + </div> + </SheetDescription> + </SheetHeader> + + <Form {...form}> + <form onSubmit={(e) => e.preventDefault()} className="flex flex-1 flex-col gap-6"> + {/* 기존 첨부 */} + <div className="grid gap-4"> + <h6 className="font-semibold leading-none tracking-tight"> + 기존 첨부파일 ({existing.length}개) + </h6> + {isLoading ? ( + <div className="flex items-center gap-2 text-sm text-muted-foreground"> + <Loader className="h-4 w-4 animate-spin" /> + 로딩 중... + </div> + ) : existing.length === 0 ? ( + <div className="text-sm text-muted-foreground">첨부파일이 없습니다.</div> + ) : ( + existing.map((att) => ( + <div + key={att.id} + className="flex items-start justify-between p-3 border rounded-md gap-3" + > + <div className="flex-1 min-w-0"> + <div className="flex items-center gap-2 mb-1 flex-wrap"> + <p className="text-sm font-medium break-words leading-tight"> + {att.originalFileName || att.fileName} + </p> + <Badge variant="outline" className="text-xs shrink-0"> + rev {att.revisionId} + </Badge> + </div> + <p className="text-xs text-muted-foreground"> + {prettyBytes(att.fileSize)} • {formatDate(att.createdAt, "KR")} + </p> + {att.description && ( + <p className="text-xs text-muted-foreground mt-1 break-words"> + {att.description} + </p> + )} + </div> + + <div className="flex items-center gap-1 shrink-0"> + <Button + variant="ghost" + size="icon" + className="h-8 w-8" + type="button" + onClick={() => handleDownloadClick(att)} + title="다운로드" + > + <Download className="h-4 w-4" /> + </Button> + <Button + variant="ghost" + size="icon" + className="h-8 w-8" + type="button" + onClick={() => handleRemoveExisting(att.id)} + title="삭제" + > + <Trash2 className="h-4 w-4" /> + </Button> + </div> + </div> + )) + )} + </div> + + {/* 새 업로드 */} + <Dropzone + maxSize={MAX_FILE_SIZE} + onDropAccepted={handleDropAccepted} + onDropRejected={handleDropRejected} + > + {({ maxSize }) => ( + <FormField + control={form.control} + name="dummy" + render={() => ( + <FormItem> + <FormLabel>새 eml 파일 업로드</FormLabel> + <DropzoneZone className="flex justify-center"> + <FormControl> + <DropzoneInput /> + </FormControl> + <div className="flex items-center gap-6"> + <DropzoneUploadIcon /> + <div className="grid gap-0.5"> + <DropzoneTitle>파일을 드래그하거나 클릭하세요</DropzoneTitle> + <DropzoneDescription> + 최대 크기: {maxSize ? prettyBytes(maxSize) : "600MB"} + </DropzoneDescription> + </div> + </div> + </DropzoneZone> + <FormDescription>복수 파일 업로드 가능</FormDescription> + </FormItem> + )} + /> + )} + </Dropzone> + + {newUploads.length > 0 && ( + <div className="grid gap-3"> + <div className="flex items-center justify-between"> + <h6 className="font-semibold leading-none tracking-tight"> + 새 파일 ({newUploads.length}개) + </h6> + <span className="text-xs text-muted-foreground"> + 총 용량 {prettyBytes(totalNewSize)} + </span> + </div> + <FileList> + {newUploads.map((file, idx) => ( + <FileListItem key={`${file.name}-${idx}`}> + <FileListHeader> + <FileListIcon /> + <FileListInfo> + <FileListName>{file.name}</FileListName> + <FileListDescription>{prettyBytes(file.size)}</FileListDescription> + </FileListInfo> + <FileListAction onClick={() => handleRemoveNewUpload(idx)}> + <X /> + <span className="sr-only">제거</span> + </FileListAction> + </FileListHeader> + </FileListItem> + ))} + </FileList> + </div> + )} + + <SheetFooter className="gap-2 pt-2 sm:space-x-0"> + <SheetClose asChild> + <Button type="button" variant="outline"> + 닫기 + </Button> + </SheetClose> + <Button + type="button" + onClick={handleSubmit} + disabled={isPending || (!newUploads.length && deleteIds.length === 0)} + > + {isPending && <Loader className="mr-2 h-4 w-4 animate-spin" />} + {isPending ? "저장 중..." : "저장"} + </Button> + </SheetFooter> + </form> + </Form> + </SheetContent> + </Sheet> + ) +} + |
