summaryrefslogtreecommitdiff
path: root/lib/tech-vendors
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-07-17 10:50:52 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-07-17 10:50:52 +0000
commit2ef02e27dbe639876fa3b90c30307dda183545ec (patch)
treee132ae7f3dd774e1ce767291c2849be4a63ae762 /lib/tech-vendors
parentfb276ed3db86fe4fc0c0fcd870fd3d085b034be0 (diff)
(최겸) 기술영업 변경사항 적용
Diffstat (limited to 'lib/tech-vendors')
-rw-r--r--lib/tech-vendors/contacts-table/add-contact-dialog.tsx21
-rw-r--r--lib/tech-vendors/contacts-table/contact-table-columns.tsx45
-rw-r--r--lib/tech-vendors/items-table/add-item-dialog.tsx308
-rw-r--r--lib/tech-vendors/items-table/feature-flags-provider.tsx108
-rw-r--r--lib/tech-vendors/items-table/item-table-columns.tsx192
-rw-r--r--lib/tech-vendors/items-table/item-table-toolbar-actions.tsx104
-rw-r--r--lib/tech-vendors/items-table/item-table.tsx83
-rw-r--r--lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-columns.tsx243
-rw-r--r--lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-toolbar-actions.tsx52
-rw-r--r--lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table.tsx120
-rw-r--r--lib/tech-vendors/service.ts312
-rw-r--r--lib/tech-vendors/table/add-vendor-dialog.tsx74
-rw-r--r--lib/tech-vendors/table/invite-tech-vendor-dialog.tsx184
-rw-r--r--lib/tech-vendors/table/tech-vendors-table-columns.tsx117
-rw-r--r--lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx16
-rw-r--r--lib/tech-vendors/table/tech-vendors-table.tsx5
-rw-r--r--lib/tech-vendors/utils.ts10
-rw-r--r--lib/tech-vendors/validations.ts50
18 files changed, 1082 insertions, 962 deletions
diff --git a/lib/tech-vendors/contacts-table/add-contact-dialog.tsx b/lib/tech-vendors/contacts-table/add-contact-dialog.tsx
index 05e5092e..ff845e20 100644
--- a/lib/tech-vendors/contacts-table/add-contact-dialog.tsx
+++ b/lib/tech-vendors/contacts-table/add-contact-dialog.tsx
@@ -39,6 +39,7 @@ export function AddContactDialog({ vendorId }: AddContactDialogProps) {
contactPosition: "",
contactEmail: "",
contactPhone: "",
+ country: "",
isPrimary: false,
},
})
@@ -50,6 +51,12 @@ export function AddContactDialog({ vendorId }: AddContactDialogProps) {
alert(`에러: ${result.error}`)
return
}
+
+ // 성공 시 메시지 표시
+ if (result.data?.message) {
+ alert(result.data.message)
+ }
+
// 성공 시 모달 닫고 폼 리셋
form.reset()
setOpen(false)
@@ -139,6 +146,20 @@ export function AddContactDialog({ vendorId }: AddContactDialogProps) {
)}
/>
+ <FormField
+ control={form.control}
+ name="country"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Country</FormLabel>
+ <FormControl>
+ <Input placeholder="예: Korea" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
{/* 단순 checkbox */}
<FormField
control={form.control}
diff --git a/lib/tech-vendors/contacts-table/contact-table-columns.tsx b/lib/tech-vendors/contacts-table/contact-table-columns.tsx
index fece5013..b8f4e7a2 100644
--- a/lib/tech-vendors/contacts-table/contact-table-columns.tsx
+++ b/lib/tech-vendors/contacts-table/contact-table-columns.tsx
@@ -4,48 +4,35 @@ import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import { Ellipsis } 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,
DropdownMenuItem,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
-import { DataTableColumnHeader } from "@/components/data-table/data-table-column-header"
-import { VendorContact, vendors } from "@/db/schema/vendors"
-import { modifyVendor } from "../service"
+import { TechVendorContact } from "@/db/schema/techVendors"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
-import { vendorContactsColumnsConfig } from "@/config/vendorContactsColumnsConfig"
-
-
-
+import { techVendorContactsColumnsConfig } from "@/config/techVendorContactsColumnsConfig"
interface GetColumnsProps {
- setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<VendorContact> | null>>;
+ setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<TechVendorContact> | null>>;
}
/**
* tanstack table 컬럼 정의 (중첩 헤더 버전)
*/
-export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<VendorContact>[] {
+export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<TechVendorContact>[] {
// ----------------------------------------------------------------
// 1) select 컬럼 (체크박스)
// ----------------------------------------------------------------
- const selectColumn: ColumnDef<VendorContact> = {
+ const selectColumn: ColumnDef<TechVendorContact> = {
id: "select",
header: ({ table }) => (
<Checkbox
@@ -74,12 +61,10 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<VendorC
// ----------------------------------------------------------------
// 2) actions 컬럼 (Dropdown 메뉴)
// ----------------------------------------------------------------
- const actionsColumn: ColumnDef<VendorContact> = {
+ const actionsColumn: ColumnDef<TechVendorContact> = {
id: "actions",
enableHiding: false,
cell: function Cell({ row }) {
- const [isUpdatePending, startUpdateTransition] = React.useTransition()
-
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -95,7 +80,6 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<VendorC
<DropdownMenuItem
onSelect={() => {
setRowAction({ row, type: "update" })
-
}}
>
Edit
@@ -118,10 +102,10 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<VendorC
// ----------------------------------------------------------------
// 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
// ----------------------------------------------------------------
- // 3-1) groupMap: { [groupName]: ColumnDef<VendorContact>[] }
- const groupMap: Record<string, ColumnDef<VendorContact>[]> = {}
+ // 3-1) groupMap: { [groupName]: ColumnDef<TechVendorContact>[] }
+ const groupMap: Record<string, ColumnDef<TechVendorContact>[]> = {}
- vendorContactsColumnsConfig.forEach((cfg) => {
+ techVendorContactsColumnsConfig.forEach((cfg) => {
// 만약 group가 없으면 "_noGroup" 처리
const groupName = cfg.group || "_noGroup"
@@ -130,7 +114,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<VendorC
}
// child column 정의
- const childCol: ColumnDef<VendorContact> = {
+ const childCol: ColumnDef<TechVendorContact> = {
accessorKey: cfg.id,
enableResizing: true,
header: ({ column }) => (
@@ -142,19 +126,16 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<VendorC
type: cfg.type,
},
cell: ({ row, cell }) => {
-
-
if (cfg.id === "createdAt") {
const dateVal = cell.getValue() as Date
- return formatDate(dateVal, "KR")
+ return formatDate(dateVal)
}
if (cfg.id === "updatedAt") {
const dateVal = cell.getValue() as Date
- return formatDate(dateVal, "KR")
+ return formatDate(dateVal)
}
-
// code etc...
return row.getValue(cfg.id) ?? ""
},
@@ -166,7 +147,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<VendorC
// ----------------------------------------------------------------
// 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기
// ----------------------------------------------------------------
- const nestedColumns: ColumnDef<VendorContact>[] = []
+ const nestedColumns: ColumnDef<TechVendorContact>[] = []
// 순서를 고정하고 싶다면 group 순서를 미리 정의하거나 sort해야 함
// 여기서는 그냥 Object.entries 순서
diff --git a/lib/tech-vendors/items-table/add-item-dialog.tsx b/lib/tech-vendors/items-table/add-item-dialog.tsx
deleted file mode 100644
index 21875295..00000000
--- a/lib/tech-vendors/items-table/add-item-dialog.tsx
+++ /dev/null
@@ -1,308 +0,0 @@
-"use client"
-
-import * as React from "react"
-import { useForm } from "react-hook-form"
-import { zodResolver } from "@hookform/resolvers/zod"
-import { Check, ChevronsUpDown } from "lucide-react"
-import { useRouter } from "next/navigation"
-
-import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
-} from "@/components/ui/form"
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover"
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
-} from "@/components/ui/command"
-import { cn } from "@/lib/utils"
-import { toast } from "sonner"
-
-import {
- createTechVendorItemSchema,
- type CreateTechVendorItemSchema,
-} from "@/lib/tech-vendors/validations"
-
-import { createTechVendorItem, getItemsForTechVendor, ItemDropdownOption } from "../service"
-
-interface AddItemDialogProps {
- vendorId: number
- vendorType: string // UI에서 전달하지만 내부적으로는 사용하지 않음
-}
-
-export function AddItemDialog({ vendorId }: AddItemDialogProps) {
- const router = useRouter()
- const [open, setOpen] = React.useState(false)
- const [commandOpen, setCommandOpen] = React.useState(false)
- const [items, setItems] = React.useState<ItemDropdownOption[]>([])
- const [filteredItems, setFilteredItems] = React.useState<ItemDropdownOption[]>([])
- const [isLoading, setIsLoading] = React.useState(false)
- const [searchTerm, setSearchTerm] = React.useState("")
-
- const [selectedItem, setSelectedItem] = React.useState<{
- itemName: string;
- description: string;
- } | null>(null)
-
- const form = useForm<CreateTechVendorItemSchema>({
- resolver: zodResolver(createTechVendorItemSchema),
- defaultValues: {
- vendorId,
- itemCode: "",
- },
- })
-
- const fetchItems = React.useCallback(async () => {
- if (items.length > 0) return
-
- console.log(`[AddItemDialog] fetchItems - 벤더 ID: ${vendorId} 시작`)
-
- setIsLoading(true)
- try {
- console.log(`[AddItemDialog] getItemsForTechVendor 호출 - vendorId: ${vendorId}`)
- const result = await getItemsForTechVendor(vendorId)
- console.log(`[AddItemDialog] getItemsForTechVendor 결과:`, result)
-
- if (result.data) {
- console.log(`[AddItemDialog] 사용 가능한 아이템 목록:`, result.data)
- setItems(result.data as ItemDropdownOption[])
- setFilteredItems(result.data as ItemDropdownOption[])
- } else if (result.error) {
- console.error("[AddItemDialog] 아이템 조회 실패:", result.error)
- toast.error(result.error)
- }
- } catch (err) {
- console.error("[AddItemDialog] 아이템 조회 실패:", err)
- toast.error("아이템 목록을 불러오는데 실패했습니다.")
- } finally {
- setIsLoading(false)
- console.log(`[AddItemDialog] fetchItems 완료`)
- }
- }, [items.length, vendorId])
-
- React.useEffect(() => {
- if (commandOpen) {
- console.log(`[AddItemDialog] Popover 열림 - fetchItems 호출`)
- fetchItems()
- }
- }, [commandOpen, fetchItems])
-
- React.useEffect(() => {
- if (!items.length) return
-
- if (!searchTerm.trim()) {
- setFilteredItems(items)
- return
- }
-
- console.log(`[AddItemDialog] 검색어로 필터링: "${searchTerm}"`)
- const lowerSearch = searchTerm.toLowerCase()
- const filtered = items.filter(item =>
- item.itemCode.toLowerCase().includes(lowerSearch) ||
- item.itemList.toLowerCase().includes(lowerSearch) ||
- (item.subItemList && item.subItemList.toLowerCase().includes(lowerSearch))
- )
-
- console.log(`[AddItemDialog] 필터링 결과: ${filtered.length}개 아이템`)
- setFilteredItems(filtered)
- }, [searchTerm, items])
-
- const handleSelectItem = (item: ItemDropdownOption) => {
- console.log(`[AddItemDialog] 아이템 선택: ${item.itemCode}`)
- form.setValue("itemCode", item.itemCode, { shouldValidate: true })
- setSelectedItem({
- itemName: item.itemList,
- description: item.subItemList || "",
- })
- console.log(`[AddItemDialog] 선택된 아이템 정보:`, {
- itemCode: item.itemCode,
- itemName: item.itemList,
- description: item.subItemList || ""
- })
- setCommandOpen(false)
- }
-
- async function onSubmit(data: CreateTechVendorItemSchema) {
- console.log(`[AddItemDialog] 폼 제출 시작 - 데이터:`, data)
- try {
- if (!data.itemCode) {
- console.error(`[AddItemDialog] itemCode가 없습니다.`)
- toast.error("아이템을 선택해주세요.")
- return
- }
-
- console.log(`[AddItemDialog] createTechVendorItem 호출 - vendorId: ${data.vendorId}, itemCode: ${data.itemCode}`)
- const submitData = {
- ...data,
- itemName: selectedItem?.itemName || "기술영업"
- }
- console.log(`[AddItemDialog] 최종 제출 데이터:`, submitData)
-
- const result = await createTechVendorItem(submitData)
- console.log(`[AddItemDialog] createTechVendorItem 결과:`, result)
-
- if (result.error) {
- console.error(`[AddItemDialog] 추가 실패:`, result.error)
- toast.error(result.error)
- return
- }
-
- console.log(`[AddItemDialog] 아이템 추가 성공`)
- toast.success("아이템이 추가되었습니다.")
- form.reset()
- setSelectedItem(null)
- setOpen(false)
- console.log(`[AddItemDialog] 화면 새로고침 시작`)
- router.refresh()
- console.log(`[AddItemDialog] 화면 새로고침 완료`)
- } catch (err) {
- console.error("[AddItemDialog] 아이템 추가 오류:", err)
- toast.error("아이템 추가 중 오류가 발생했습니다.")
- }
- }
-
- function handleDialogOpenChange(nextOpen: boolean) {
- console.log(`[AddItemDialog] 다이얼로그 상태 변경: ${nextOpen ? '열림' : '닫힘'}`)
- if (!nextOpen) {
- form.reset()
- setSelectedItem(null)
- }
- setOpen(nextOpen)
- }
-
- const selectedItemCode = form.watch("itemCode")
- console.log(`[AddItemDialog] 현재 선택된 itemCode:`, selectedItemCode)
- const displayItemName = selectedItem?.itemName || ""
-
- return (
- <Dialog open={open} onOpenChange={handleDialogOpenChange}>
- <DialogTrigger asChild>
- <Button variant="default" size="sm">
- Add Item
- </Button>
- </DialogTrigger>
-
- <DialogContent className="max-h-[90vh] overflow-hidden flex flex-col">
- <DialogHeader>
- <DialogTitle>Create New Item</DialogTitle>
- <DialogDescription>
- 아이템을 선택한 후 <b>Create</b> 버튼을 누르세요.
- </DialogDescription>
- </DialogHeader>
-
- <Form {...form}>
- <form onSubmit={(e) => {
- console.log(`[AddItemDialog] 폼 제출 이벤트 발생`)
- form.handleSubmit(onSubmit)(e)
- }} className="flex flex-col flex-1 overflow-hidden">
- <div className="space-y-4 py-4 flex-1 overflow-y-auto">
- <div>
- <FormLabel className="text-sm font-medium">아이템 선택</FormLabel>
- <Popover open={commandOpen} onOpenChange={setCommandOpen}>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- aria-expanded={commandOpen}
- className="w-full justify-between mt-1"
- >
- {selectedItemCode
- ? `${selectedItemCode} - ${displayItemName}`
- : "아이템 선택..."}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-[400px] p-0">
- <Command>
- <CommandInput
- placeholder="아이템 코드/이름 검색..."
- onValueChange={setSearchTerm}
- />
- <CommandList className="max-h-[200px]">
- <CommandEmpty>검색 결과가 없습니다</CommandEmpty>
- {isLoading ? (
- <div className="py-6 text-center text-sm">로딩 중...</div>
- ) : (
- <CommandGroup>
- {filteredItems.map((item) => (
- <CommandItem
- key={item.itemCode}
- value={`${item.itemCode} ${item.itemList}`}
- onSelect={() => handleSelectItem(item)}
- >
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- selectedItemCode === item.itemCode
- ? "opacity-100"
- : "opacity-0"
- )}
- />
- <span className="font-medium">{item.itemCode}</span>
- <span className="ml-2 text-gray-500 truncate">- {item.itemList}</span>
- </CommandItem>
- ))}
- </CommandGroup>
- )}
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- </div>
-
- {selectedItem && (
- <div className="rounded-md border p-3 mt-4 overflow-hidden">
- <h3 className="font-medium text-sm mb-2">선택된 아이템 정보</h3>
-
- <FormField
- control={form.control}
- name="itemCode"
- render={({ field }) => (
- <FormItem className="hidden">
- <FormControl>
- <Input {...field} />
- </FormControl>
- </FormItem>
- )}
- />
-
- <div className="mb-2">
- <div className="text-sm font-medium text-gray-500">Item Name</div>
- <div className="text-sm">{selectedItem.itemName}</div>
- </div>
-
- {selectedItem.description && (
- <div>
- <div className="text-sm font-medium text-gray-500">Description</div>
- <div className="text-sm">{selectedItem.description}</div>
- </div>
- )}
- </div>
- )}
- </div>
-
- <DialogFooter className="pt-4 border-t">
- <Button type="submit" disabled={!selectedItemCode}>
- Create
- </Button>
- </DialogFooter>
- </form>
- </Form>
- </DialogContent>
- </Dialog>
- )
-} \ No newline at end of file
diff --git a/lib/tech-vendors/items-table/feature-flags-provider.tsx b/lib/tech-vendors/items-table/feature-flags-provider.tsx
deleted file mode 100644
index 81131894..00000000
--- a/lib/tech-vendors/items-table/feature-flags-provider.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-"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/tech-vendors/items-table/item-table-columns.tsx b/lib/tech-vendors/items-table/item-table-columns.tsx
deleted file mode 100644
index 72986849..00000000
--- a/lib/tech-vendors/items-table/item-table-columns.tsx
+++ /dev/null
@@ -1,192 +0,0 @@
-"use client"
-
-import * as React from "react"
-import { type DataTableRowAction } from "@/types/table"
-import { type ColumnDef } from "@tanstack/react-table"
-import { MoreHorizontal } from "lucide-react"
-import { format } from "date-fns"
-import { ko } from "date-fns/locale"
-
-import { Badge } from "@/components/ui/badge"
-import { Button } from "@/components/ui/button"
-import { Checkbox } from "@/components/ui/checkbox"
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-
-import { TechVendorItemsView } from "@/db/schema/techVendors"
-import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
-import {
- techVendorItemsColumnsConfig,
- shipbuildingColumnsConfig,
- offshoreTopColumnsConfig,
- offshoreHullColumnsConfig
-} from "@/config/techVendorItemsColumnsConfig"
-
-interface ColumnConfig {
- id: string
- label: string
- excelHeader: string
- type: string
- minWidth: number
- defaultWidth: number
- group?: string
-}
-
-interface GetColumnsOptions {
- setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<TechVendorItemsView> | null>>
- vendorType: string
-}
-
-export function getColumns({ setRowAction, vendorType }: GetColumnsOptions): ColumnDef<TechVendorItemsView>[] {
- // 벤더 타입에 따라 적절한 컬럼 설정 선택
- const columnsConfig = (() => {
- switch (vendorType) {
- case "조선":
- return shipbuildingColumnsConfig;
- case "해양TOP":
- return offshoreTopColumnsConfig;
- case "해양HULL":
- return offshoreHullColumnsConfig;
- default:
- return techVendorItemsColumnsConfig;
- }
- })();
-
- // ----------------------------------------------------------------
- // 1) select 컬럼 (체크박스)
- // ----------------------------------------------------------------
- const selectColumn: ColumnDef<TechVendorItemsView> = {
- id: "select",
- header: ({ table }) => (
- <Checkbox
- checked={
- table.getIsAllPageRowsSelected() ||
- (table.getIsSomePageRowsSelected() && "indeterminate")
- }
- onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
- aria-label="Select all"
- className="translate-y-[2px]"
- />
- ),
- cell: ({ row }) => (
- <Checkbox
- checked={row.getIsSelected()}
- onCheckedChange={(value) => row.toggleSelected(!!value)}
- aria-label="Select row"
- className="translate-y-[2px]"
- />
- ),
- enableSorting: false,
- enableHiding: false,
- }
-
- // ----------------------------------------------------------------
- // 2) actions 컬럼 (Dropdown 메뉴)
- // ----------------------------------------------------------------
- // const actionsColumn: ColumnDef<TechVendorItemsView> = {
- // id: "actions",
- // cell: ({ row }) => {
- // return (
- // <DropdownMenu>
- // <DropdownMenuTrigger asChild>
- // <Button variant="ghost" className="h-8 w-8 p-0">
- // <span className="sr-only">Open menu</span>
- // <MoreHorizontal className="h-4 w-4" />
- // </Button>
- // </DropdownMenuTrigger>
- // <DropdownMenuContent align="end">
- // <DropdownMenuLabel>Actions</DropdownMenuLabel>
- // <DropdownMenuItem onClick={() =>
- // setRowAction({
- // type: "update",
- // row,
- // })
- // }>
- // View Details
- // </DropdownMenuItem>
- // </DropdownMenuContent>
- // </DropdownMenu>
- // )
- // },
- // }
-
- // ----------------------------------------------------------------
- // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
- // ----------------------------------------------------------------
- const groupMap: Record<string, ColumnDef<TechVendorItemsView>[]> = {}
-
- columnsConfig.forEach((cfg: ColumnConfig) => {
- // 만약 group가 없으면 "_noGroup" 처리
- const groupName = cfg.group || "_noGroup"
-
- if (!groupMap[groupName]) {
- groupMap[groupName] = []
- }
-
- // child column 정의
- const childCol: ColumnDef<TechVendorItemsView> = {
- accessorKey: cfg.id,
- enableResizing: true,
- header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title={cfg.label} />
- ),
- minSize: cfg.minWidth,
- size: cfg.defaultWidth,
- meta: {
- excelHeader: cfg.excelHeader,
- group: cfg.group,
- type: cfg.type,
- },
- cell: ({ row, cell }) => {
- if (cfg.id === "createdAt" || cfg.id === "updatedAt") {
- const dateVal = cell.getValue() as Date
- return format(dateVal, "PPP", { locale: ko })
- }
-
- if (cfg.id === "techVendorType") {
- const type = cell.getValue() as string
- return type ? (
- <Badge variant="outline" className="capitalize">
- {type}
- </Badge>
- ) : null
- }
-
- return row.getValue(cfg.id) ?? ""
- },
- }
-
- groupMap[groupName].push(childCol)
- })
-
- // ----------------------------------------------------------------
- // 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기
- // ----------------------------------------------------------------
- const nestedColumns: ColumnDef<TechVendorItemsView>[] = []
-
- Object.entries(groupMap).forEach(([groupName, colDefs]) => {
- if (groupName === "_noGroup") {
- nestedColumns.push(...colDefs)
- } else {
- nestedColumns.push({
- id: groupName,
- header: groupName,
- columns: colDefs,
- })
- }
- })
-
- // ----------------------------------------------------------------
- // 4) 최종 컬럼 배열: select, nestedColumns, actions
- // ----------------------------------------------------------------
- return [
- selectColumn,
- ...nestedColumns,
- // actionsColumn,
- ]
-} \ No newline at end of file
diff --git a/lib/tech-vendors/items-table/item-table-toolbar-actions.tsx b/lib/tech-vendors/items-table/item-table-toolbar-actions.tsx
deleted file mode 100644
index b327ff56..00000000
--- a/lib/tech-vendors/items-table/item-table-toolbar-actions.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-"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 { TechVendorItemsView } from "@/db/schema/techVendors"
-import { AddItemDialog } from "./add-item-dialog"
-import { importTasksExcel } from "@/lib/tasks/service"
-
-interface TechVendorItemsTableToolbarActionsProps {
- table: Table<TechVendorItemsView>
- vendorId: number
- vendorType: string
-}
-
-export function TechVendorItemsTableToolbarActions({ table, vendorId, vendorType }: TechVendorItemsTableToolbarActionsProps) {
- // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식
- const fileInputRef = React.useRef<HTMLInputElement>(null)
-
- // 파일이 선택되었을 때 처리
- async function onFileChange(event: React.ChangeEvent<HTMLInputElement>) {
- const file = event.target.files?.[0]
- if (!file) return
-
- // 파일 초기화 (동일 파일 재업로드 시에도 onChange가 트리거되도록)
- event.target.value = ""
-
- // 서버 액션 or API 호출
- try {
- // 예: 서버 액션 호출
- const { errorFile, errorMessage } = await importTasksExcel(file)
-
- if (errorMessage) {
- toast.error(errorMessage)
- }
- if (errorFile) {
- // 에러 엑셀을 다운로드
- const url = URL.createObjectURL(errorFile)
- const link = document.createElement("a")
- link.href = url
- link.download = "errors.xlsx"
- link.click()
- URL.revokeObjectURL(url)
- } else {
- // 성공
- toast.success("Import success")
- // 필요 시 revalidateTag("tasks") 등
- }
-
- } catch (err) {
- console.error("파일 업로드 중 오류가 발생했습니다:", err)
- toast.error("파일 업로드 중 오류가 발생했습니다.")
- }
- }
-
- function handleImportClick() {
- // 숨겨진 <input type="file" /> 요소를 클릭
- fileInputRef.current?.click()
- }
-
- return (
- <div className="flex items-center gap-2">
-
- {/* <AddItemDialog vendorId={vendorId} vendorType={vendorType} /> */}
-
- {/** 3) Import 버튼 (파일 업로드) */}
- <Button variant="outline" size="sm" className="gap-2" onClick={handleImportClick}>
- <Upload className="size-4" aria-hidden="true" />
- <span className="hidden sm:inline">Import</span>
- </Button>
- {/*
- 실제로는 숨겨진 input과 연결:
- - accept=".xlsx,.xls" 등으로 Excel 파일만 업로드 허용
- */}
- <input
- ref={fileInputRef}
- type="file"
- accept=".xlsx,.xls"
- className="hidden"
- onChange={onFileChange}
- />
-
- {/** 4) Export 버튼 */}
- <Button
- variant="outline"
- size="sm"
- onClick={() =>
- exportTableToExcel(table, {
- filename: "tech-vendor-items",
- 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/tech-vendors/items-table/item-table.tsx b/lib/tech-vendors/items-table/item-table.tsx
deleted file mode 100644
index 2eecd829..00000000
--- a/lib/tech-vendors/items-table/item-table.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-"use client"
-
-import * as React from "react"
-import type {
- DataTableAdvancedFilterField,
- DataTableFilterField,
- DataTableRowAction,
-} from "@/types/table"
-
-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 { getColumns } from "./item-table-columns"
-import { getVendorItemsByType } from "@/lib/tech-vendors/service"
-import { TechVendorItemsTableToolbarActions } from "./item-table-toolbar-actions"
-
-interface TechVendorItemsTableProps {
- promises: Promise<Awaited<ReturnType<typeof getVendorItemsByType>>>
- vendorId: number
- vendorType: string
-}
-
-export function TechVendorItemsTable({ promises, vendorId, vendorType }: TechVendorItemsTableProps) {
- // Suspense로 받아온 데이터
- const { data } = React.use(promises)
-
- const [rowAction, setRowAction] = React.useState<DataTableRowAction<any> | null>(null)
-
- const columns = React.useMemo(
- () => getColumns({
- setRowAction,
- vendorType
- }),
- [vendorType]
- )
-
- const filterFields: DataTableFilterField<any>[] = []
-
- const advancedFilterFields: DataTableAdvancedFilterField<any>[] = [
- { id: "itemList", label: "Item List", type: "text" },
- { id: "itemCode", label: "Item Code", type: "text" },
- { id: "workType", label: "Work Type", type: "text" },
- { id: "subItemList", label: "Sub Item List", type: "text" },
- { id: "createdAt", label: "Created at", type: "date" },
- { id: "updatedAt", label: "Updated at", type: "date" },
- ]
-
- const { table } = useDataTable({
- data,
- columns,
- pageCount: 1,
- filterFields,
- enablePinning: true,
- enableAdvancedFilter: true,
- initialState: {
- sorting: [{ id: "createdAt", desc: true }],
- columnPinning: { right: ["actions"] },
- },
- getRowId: (originalRow) => String(originalRow.itemCode),
- shallow: false,
- clearOnDefault: true,
- })
-
- return (
- <>
- <DataTable
- table={table}
- >
- <DataTableAdvancedToolbar
- table={table}
- filterFields={advancedFilterFields}
- shallow={false}
- >
- <TechVendorItemsTableToolbarActions
- table={table}
- vendorId={vendorId}
- vendorType={vendorType}
- />
- </DataTableAdvancedToolbar>
- </DataTable>
- </>
- )
-} \ No newline at end of file
diff --git a/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-columns.tsx b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-columns.tsx
new file mode 100644
index 00000000..a7eed1d2
--- /dev/null
+++ b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-columns.tsx
@@ -0,0 +1,243 @@
+"use client"
+
+import * as React from "react"
+import { type DataTableRowAction } from "@/types/table"
+import { type ColumnDef } from "@tanstack/react-table"
+import { Ellipsis } from "lucide-react"
+import Link from "next/link"
+
+import { formatDate } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
+import { Checkbox } from "@/components/ui/checkbox"
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu"
+import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
+import { techVendorRfqHistoryColumnsConfig } from "@/config/techVendorRfqHistoryColumnsConfig"
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
+
+export interface TechVendorRfqHistoryRow {
+ id: number;
+ rfqCode: string | null;
+ description: string | null;
+ projectCode: string | null;
+ projectName: string | null;
+ projectType: string | null; // 프로젝트 타입 추가
+ status: string;
+ totalAmount: string | null;
+ currency: string | null;
+ dueDate: Date | null;
+ createdAt: Date;
+ quotationCode: string | null;
+ submittedAt: Date | null;
+}
+
+// 프로젝트 타입에 따른 RFQ 페이지 URL 생성 함수
+function getRfqPageUrl(projectType: string | null, description: string | null): string {
+ const baseUrls = {
+ 'SHIP': '/evcp/budgetary-tech-sales-ship',
+ 'TOP': '/evcp/budgetary-tech-sales-top',
+ 'HULL': '/evcp/budgetary-tech-sales-hull'
+ };
+
+ const url = baseUrls[projectType as keyof typeof baseUrls] || '/evcp/budgetary-tech-sales-ship';
+
+ // description이 있으면 search 파라미터로 추가
+ if (description) {
+ return `${url}?search=${encodeURIComponent(description)}`;
+ }
+
+ return url;
+}
+
+// 프로젝트 타입 표시 함수
+function getProjectTypeDisplay(projectType: string | null): string {
+ const typeMap = {
+ 'SHIP': '조선',
+ 'TOP': '해양TOP',
+ 'HULL': '해양HULL'
+ };
+
+ return typeMap[projectType as keyof typeof typeMap] || projectType || '-';
+}
+
+interface GetColumnsProps {
+ setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<TechVendorRfqHistoryRow> | null>>;
+}
+
+export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<TechVendorRfqHistoryRow>[] {
+ // ----------------------------------------------------------------
+ // 1) select 컬럼 (체크박스)
+ // ----------------------------------------------------------------
+ const selectColumn: ColumnDef<TechVendorRfqHistoryRow> = {
+ 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) actions 컬럼 (Dropdown 메뉴)
+ // ----------------------------------------------------------------
+ const actionsColumn: ColumnDef<TechVendorRfqHistoryRow> = {
+ id: "actions",
+ enableHiding: false,
+ cell: function Cell({ row }) {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ aria-label="Open menu"
+ variant="ghost"
+ className="flex size-8 p-0 data-[state=open]:bg-muted"
+ >
+ <Ellipsis className="size-4" aria-hidden="true" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem
+ onSelect={() => setRowAction({ row, type: "update" })}
+ >
+ View Details
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ },
+ size: 40,
+ }
+
+ // ----------------------------------------------------------------
+ // 3) 일반 컬럼들
+ // ----------------------------------------------------------------
+ const basicColumns: ColumnDef<TechVendorRfqHistoryRow>[] = techVendorRfqHistoryColumnsConfig.map((cfg) => {
+ const column: ColumnDef<TechVendorRfqHistoryRow> = {
+ accessorKey: cfg.id,
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title={cfg.label} />
+ ),
+ size: cfg.size,
+ }
+
+ if (cfg.id === "rfqCode") {
+ column.cell = ({ row }) => {
+ const rfqCode = row.original.rfqCode
+ const projectType = row.original.projectType
+ if (!rfqCode) return null
+
+ const rfqUrl = getRfqPageUrl(projectType, rfqCode);
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Link
+ href={rfqUrl}
+ className="break-words whitespace-normal line-clamp-2 hover:underline cursor-pointer"
+ >
+ {rfqCode}
+ </Link>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="max-w-[400px] whitespace-pre-wrap break-words">
+ <div>
+ <div className="font-medium">{rfqCode}</div>
+ <div className="text-xs text-muted-foreground mt-1">
+ 클릭하여 RFQ 페이지로 이동
+ </div>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ )
+ }
+ }
+
+ if (cfg.id === "projectType") {
+ column.cell = ({ row }) => {
+ const projectType = row.original.projectType
+ return (
+ <div className="whitespace-nowrap">
+ {getProjectTypeDisplay(projectType)}
+ </div>
+ )
+ }
+ }
+
+ if (cfg.id === "status") {
+ column.cell = ({ row }) => {
+ const statusVal = row.original.status
+ if (!statusVal) return null
+ return (
+ <div className="flex items-center">
+ <span className="capitalize">{statusVal}</span>
+ </div>
+ )
+ }
+ }
+
+ if (cfg.id === "totalAmount") {
+ column.cell = ({ row }) => {
+ const amount = row.original.totalAmount
+ const currency = row.original.currency
+ if (!amount || !currency) return <span className="text-gray-400">-</span>
+ return (
+ <div className="whitespace-nowrap">
+ {`${currency} ${Number(amount).toLocaleString()}`}
+ </div>
+ )
+ }
+ }
+
+ if (cfg.id === "dueDate" || cfg.id === "createdAt") {
+ column.cell = ({ row }) => {
+ const dateValue = row.getValue(cfg.id) as Date
+ if (!dateValue) return <span className="text-gray-400">-</span>
+ return (
+ <div className="whitespace-nowrap">
+ {formatDate(dateValue)}
+ </div>
+ )
+ }
+ }
+
+ if (cfg.id === "projectCode" || cfg.id === "projectName") {
+ column.cell = ({ row }) => {
+ const value = row.getValue(cfg.id) as string | null
+ if (!value) return <span className="text-gray-400">-</span>
+ return value
+ }
+ column.size = 100;
+ }
+
+ return column
+ })
+
+ // ----------------------------------------------------------------
+ // 4) 최종 컬럼 배열
+ // ----------------------------------------------------------------
+ return [
+ selectColumn,
+ ...basicColumns,
+ actionsColumn,
+ ]
+} \ No newline at end of file
diff --git a/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-toolbar-actions.tsx b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-toolbar-actions.tsx
new file mode 100644
index 00000000..e09cc17f
--- /dev/null
+++ b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table-toolbar-actions.tsx
@@ -0,0 +1,52 @@
+"use client"
+
+import * as React from "react"
+import { type Table } from "@tanstack/react-table"
+import { Download } from "lucide-react"
+
+import { exportTableToExcel } from "@/lib/export"
+import { Button } from "@/components/ui/button"
+
+interface TechVendorRfqHistoryRow {
+ id: number;
+ rfqCode: string | null;
+ description: string | null;
+ projectCode: string | null;
+ projectName: string | null;
+ status: string;
+ totalAmount: string | null;
+ currency: string | null;
+ dueDate: Date | null;
+ createdAt: Date;
+ quotationCode: string | null;
+ submittedAt: Date | null;
+}
+
+interface TechVendorRfqHistoryTableToolbarActionsProps {
+ table: Table<TechVendorRfqHistoryRow>
+}
+
+export function TechVendorRfqHistoryTableToolbarActions({
+ table,
+}: TechVendorRfqHistoryTableToolbarActionsProps) {
+ return (
+ <div className="flex items-center gap-2">
+
+ {/** Export 버튼 */}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ exportTableToExcel(table, {
+ filename: "tech-vendor-rfq-history",
+ 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/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table.tsx b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table.tsx
new file mode 100644
index 00000000..642c2d9c
--- /dev/null
+++ b/lib/tech-vendors/rfq-history-table/tech-vendor-rfq-history-table.tsx
@@ -0,0 +1,120 @@
+"use client"
+
+import * as React from "react"
+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 { getColumns, type TechVendorRfqHistoryRow } from "./tech-vendor-rfq-history-table-columns"
+import { getTechVendorRfqHistory } from "../service"
+import { TechVendorRfqHistoryTableToolbarActions } from "./tech-vendor-rfq-history-table-toolbar-actions"
+import { getRFQStatusIcon } from "@/lib/tasks/utils"
+import { TooltipProvider } from "@/components/ui/tooltip"
+
+interface TechVendorRfqHistoryTableProps {
+ promises: Promise<
+ [
+ Awaited<ReturnType<typeof getTechVendorRfqHistory>>,
+ ]
+ >
+}
+
+export function TechVendorRfqHistoryTable({ promises }: TechVendorRfqHistoryTableProps) {
+ const [{ data, pageCount }] = React.use(promises)
+
+ const [rowAction, setRowAction] = React.useState<DataTableRowAction<TechVendorRfqHistoryRow> | null>(null)
+
+ // rowAction 처리 (향후 확장 가능)
+ React.useEffect(() => {
+ if (rowAction?.type === "update") {
+ // TODO: 상세보기 모달 등 구현
+ console.log("View details for:", rowAction.row.original)
+ setRowAction(null)
+ }
+ }, [rowAction])
+
+ const columns = React.useMemo(() => getColumns({
+ setRowAction,
+ }), [setRowAction]);
+
+ const filterFields: DataTableFilterField<TechVendorRfqHistoryRow>[] = [
+ {
+ id: "rfqCode",
+ label: "RFQ 코드",
+ placeholder: "RFQ 코드 검색...",
+ },
+ {
+ id: "status",
+ label: "상태",
+ options: ["DRAFT", "PUBLISHED", "EVALUATION", "AWARDED"].map((status) => ({
+ label: toSentenceCase(status),
+ value: status,
+ icon: getRFQStatusIcon(status as "DRAFT" | "PUBLISHED" | "EVALUATION" | "AWARDED"),
+ })),
+ },
+ {
+ id: "projectCode",
+ label: "프로젝트 코드",
+ placeholder: "프로젝트 코드 검색...",
+ }
+ ]
+
+ const advancedFilterFields: DataTableAdvancedFilterField<TechVendorRfqHistoryRow>[] = [
+ { id: "rfqCode", label: "RFQ 코드", type: "text" },
+ { id: "description", label: "RFQ 제목", type: "text" },
+ { id: "projectCode", label: "프로젝트 코드", type: "text" },
+ { id: "projectName", label: "프로젝트명", type: "text" },
+ {
+ id: "status",
+ label: "상태",
+ type: "multi-select",
+ options: ["DRAFT", "PUBLISHED", "EVALUATION", "AWARDED"].map((status) => ({
+ label: toSentenceCase(status),
+ value: status,
+ icon: getRFQStatusIcon(status as "DRAFT" | "PUBLISHED" | "EVALUATION" | "AWARDED"),
+ })),
+ },
+ { id: "dueDate", label: "마감일", type: "date" },
+ { id: "createdAt", label: "생성일", type: "date" },
+ ]
+
+ const { table } = useDataTable({
+ data,
+ columns,
+ pageCount,
+ filterFields,
+ enablePinning: true,
+ enableAdvancedFilter: true,
+ initialState: {
+ sorting: [{ id: "createdAt", desc: true }],
+ columnPinning: { right: ["actions"] },
+ },
+ getRowId: (originalRow) => String(originalRow.id),
+ shallow: true,
+ clearOnDefault: true,
+ })
+
+ return (
+ <>
+ <TooltipProvider>
+ <DataTable
+ table={table}
+ >
+ <DataTableAdvancedToolbar
+ table={table}
+ filterFields={advancedFilterFields}
+ shallow={false}
+ >
+ <TechVendorRfqHistoryTableToolbarActions table={table} />
+ </DataTableAdvancedToolbar>
+ </DataTable>
+ </TooltipProvider>
+ </>
+ )
+} \ No newline at end of file
diff --git a/lib/tech-vendors/service.ts b/lib/tech-vendors/service.ts
index da4a44eb..cb5aa89f 100644
--- a/lib/tech-vendors/service.ts
+++ b/lib/tech-vendors/service.ts
@@ -4,6 +4,7 @@ import { revalidateTag, unstable_noStore } from "next/cache";
import db from "@/db/db";
import { techVendorAttachments, techVendorContacts, techVendorPossibleItems, techVendors, techVendorItemsView, type TechVendor, techVendorCandidates } from "@/db/schema/techVendors";
import { items, itemShipbuilding, itemOffshoreTop, itemOffshoreHull } from "@/db/schema/items";
+import { users } from "@/db/schema/users";
import { filterColumns } from "@/lib/filter-columns";
import { unstable_cache } from "@/lib/unstable-cache";
@@ -32,12 +33,12 @@ import type {
CreateTechVendorContactSchema,
GetTechVendorItemsSchema,
CreateTechVendorItemSchema,
+ GetTechVendorRfqHistorySchema,
} from "./validations";
import { asc, desc, ilike, inArray, and, or, eq, isNull, not } from "drizzle-orm";
import path from "path";
import { sql } from "drizzle-orm";
-import { users } from "@/db/schema/users";
import { decryptWithServerAction } from "@/components/drm/drmUtils";
import { deleteFile, saveDRMFile } from "../file-stroage";
@@ -510,13 +511,16 @@ export async function createTechVendorContact(input: CreateTechVendorContactSche
contactPosition: input.contactPosition || "",
contactEmail: input.contactEmail,
contactPhone: input.contactPhone || "",
+ country: input.country || "",
isPrimary: input.isPrimary || false,
});
+
return newContact;
});
// 캐시 무효화
revalidateTag(`tech-vendor-contacts-${input.vendorId}`);
+ revalidateTag("users");
return { data: null, error: null };
} catch (err) {
@@ -1245,6 +1249,109 @@ export const findVendorById = async (id: number): Promise<TechVendor | null> =>
}
};
+/* -----------------------------------------------------
+ 8) 기술영업 벤더 RFQ 히스토리 조회
+----------------------------------------------------- */
+
+/**
+ * 기술영업 벤더의 RFQ 히스토리 조회 (간단한 버전)
+ */
+export async function getTechVendorRfqHistory(input: GetTechVendorRfqHistorySchema, id:number) {
+ try {
+
+ // 먼저 해당 벤더의 견적서가 있는지 확인
+ const { techSalesVendorQuotations } = await import("@/db/schema/techSales");
+
+ const quotationCheck = await db
+ .select({ count: sql<number>`count(*)`.as("count") })
+ .from(techSalesVendorQuotations)
+ .where(eq(techSalesVendorQuotations.vendorId, id));
+
+ console.log(`벤더 ${id}의 견적서 개수:`, quotationCheck[0]?.count);
+
+ if (quotationCheck[0]?.count === 0) {
+ console.log("해당 벤더의 견적서가 없습니다.");
+ return { data: [], pageCount: 0 };
+ }
+
+ const offset = (input.page - 1) * input.perPage;
+ const { techSalesRfqs } = await import("@/db/schema/techSales");
+ const { biddingProjects } = await import("@/db/schema/projects");
+
+ // 간단한 조회
+ let whereCondition = eq(techSalesVendorQuotations.vendorId, id);
+
+ // 검색이 있다면 추가
+ if (input.search) {
+ const s = `%${input.search}%`;
+ const searchCondition = and(
+ whereCondition,
+ or(
+ ilike(techSalesRfqs.rfqCode, s),
+ ilike(techSalesRfqs.description, s),
+ ilike(biddingProjects.pspid, s),
+ ilike(biddingProjects.projNm, s)
+ )
+ );
+ whereCondition = searchCondition;
+ }
+
+ // 데이터 조회 - 테이블에 필요한 필드들 (프로젝트 타입 추가)
+ const data = await db
+ .select({
+ id: techSalesRfqs.id,
+ rfqCode: techSalesRfqs.rfqCode,
+ description: techSalesRfqs.description,
+ projectCode: biddingProjects.pspid,
+ projectName: biddingProjects.projNm,
+ projectType: biddingProjects.pjtType, // 프로젝트 타입 추가
+ status: techSalesRfqs.status,
+ totalAmount: techSalesVendorQuotations.totalPrice,
+ currency: techSalesVendorQuotations.currency,
+ dueDate: techSalesRfqs.dueDate,
+ createdAt: techSalesRfqs.createdAt,
+ quotationCode: techSalesVendorQuotations.quotationCode,
+ submittedAt: techSalesVendorQuotations.submittedAt,
+ })
+ .from(techSalesVendorQuotations)
+ .innerJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id))
+ .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id))
+ .where(whereCondition)
+ .orderBy(desc(techSalesRfqs.createdAt))
+ .limit(input.perPage)
+ .offset(offset);
+
+ console.log("조회된 데이터:", data.length, "개");
+
+ // 전체 개수 조회
+ const totalResult = await db
+ .select({ count: sql<number>`count(*)`.as("count") })
+ .from(techSalesVendorQuotations)
+ .innerJoin(techSalesRfqs, eq(techSalesVendorQuotations.rfqId, techSalesRfqs.id))
+ .leftJoin(biddingProjects, eq(techSalesRfqs.biddingProjectId, biddingProjects.id))
+ .where(whereCondition);
+
+ const total = totalResult[0]?.count || 0;
+ const pageCount = Math.ceil(total / input.perPage);
+
+ console.log("기술영업 벤더 RFQ 히스토리 조회 완료", {
+ id,
+ dataLength: data.length,
+ total,
+ pageCount
+ });
+
+ return { data, pageCount };
+ } catch (err) {
+ console.error("기술영업 벤더 RFQ 히스토리 조회 오류:", {
+ err,
+ id,
+ stack: err instanceof Error ? err.stack : undefined
+ });
+ return { data: [], pageCount: 0 };
+ }
+}
+
/**
* 기술영업 벤더 엑셀 import 시 유저 생성 및 아이템 등록
*/
@@ -1408,43 +1515,91 @@ export async function createTechVendorFromSignup(params: {
try {
console.log("기술영업 벤더 회원가입 시작:", params.vendorData.vendorName);
+ // 초대 토큰 검증
+ let existingVendorId: number | null = null;
+ if (params.invitationToken) {
+ const { verifyTechVendorInvitationToken } = await import("@/lib/tech-vendor-invitation-token");
+ const tokenPayload = await verifyTechVendorInvitationToken(params.invitationToken);
+
+ if (!tokenPayload) {
+ throw new Error("유효하지 않은 초대 토큰입니다.");
+ }
+
+ existingVendorId = tokenPayload.vendorId;
+ console.log("초대 토큰 검증 성공, 벤더 ID:", existingVendorId);
+ }
+
const result = await db.transaction(async (tx) => {
- // 1. 이메일 중복 체크
- const existingVendor = await tx.query.techVendors.findFirst({
- where: eq(techVendors.email, params.vendorData.email),
- columns: { id: true, vendorName: true }
- });
+ let vendorResult;
+
+ if (existingVendorId) {
+ // 기존 벤더 정보 업데이트
+ const [updatedVendor] = await tx.update(techVendors)
+ .set({
+ vendorName: params.vendorData.vendorName,
+ vendorCode: params.vendorData.vendorCode || null,
+ taxId: params.vendorData.taxId,
+ country: params.vendorData.country,
+ address: params.vendorData.address || null,
+ phone: params.vendorData.phone || null,
+ email: params.vendorData.email,
+ website: params.vendorData.website || null,
+ techVendorType: params.vendorData.techVendorType,
+ status: "QUOTE_COMPARISON", // 가입 완료 시 QUOTE_COMPARISON으로 변경
+ representativeName: params.vendorData.representativeName || null,
+ representativeEmail: params.vendorData.representativeEmail || null,
+ representativePhone: params.vendorData.representativePhone || null,
+ representativeBirth: params.vendorData.representativeBirth || null,
+ items: params.vendorData.items,
+ updatedAt: new Date(),
+ })
+ .where(eq(techVendors.id, existingVendorId))
+ .returning();
+
+ vendorResult = updatedVendor;
+ console.log("기존 벤더 정보 업데이트 완료:", vendorResult.id);
+ } else {
+ // 1. 이메일 중복 체크 (새 벤더인 경우)
+ const existingVendor = await tx.query.techVendors.findFirst({
+ where: eq(techVendors.email, params.vendorData.email),
+ columns: { id: true, vendorName: true }
+ });
- if (existingVendor) {
- throw new Error(`이미 등록된 이메일입니다: ${params.vendorData.email}`);
- }
+ if (existingVendor) {
+ throw new Error(`이미 등록된 이메일입니다: ${params.vendorData.email}`);
+ }
- // 2. 벤더 생성
- const [newVendor] = await tx.insert(techVendors).values({
- vendorName: params.vendorData.vendorName,
- vendorCode: params.vendorData.vendorCode || null,
- taxId: params.vendorData.taxId,
- country: params.vendorData.country,
- address: params.vendorData.address || null,
- phone: params.vendorData.phone || null,
- email: params.vendorData.email,
- website: params.vendorData.website || null,
- techVendorType: params.vendorData.techVendorType,
- status: "ACTIVE",
- representativeName: params.vendorData.representativeName || null,
- representativeEmail: params.vendorData.representativeEmail || null,
- representativePhone: params.vendorData.representativePhone || null,
- representativeBirth: params.vendorData.representativeBirth || null,
- items: params.vendorData.items,
- }).returning();
+ // 2. 새 벤더 생성
+ const [newVendor] = await tx.insert(techVendors).values({
+ vendorName: params.vendorData.vendorName,
+ vendorCode: params.vendorData.vendorCode || null,
+ taxId: params.vendorData.taxId,
+ country: params.vendorData.country,
+ address: params.vendorData.address || null,
+ phone: params.vendorData.phone || null,
+ email: params.vendorData.email,
+ website: params.vendorData.website || null,
+ techVendorType: params.vendorData.techVendorType,
+ status: "ACTIVE",
+ isQuoteComparison: false,
+ representativeName: params.vendorData.representativeName || null,
+ representativeEmail: params.vendorData.representativeEmail || null,
+ representativePhone: params.vendorData.representativePhone || null,
+ representativeBirth: params.vendorData.representativeBirth || null,
+ items: params.vendorData.items,
+ }).returning();
+
+ vendorResult = newVendor;
+ console.log("새 벤더 생성 완료:", vendorResult.id);
+ }
- console.log("기술영업 벤더 생성 성공:", newVendor.id);
+ // 이 부분은 위에서 이미 처리되었으므로 주석 처리
// 3. 연락처 생성
if (params.contacts && params.contacts.length > 0) {
for (const [index, contact] of params.contacts.entries()) {
await tx.insert(techVendorContacts).values({
- vendorId: newVendor.id,
+ vendorId: vendorResult.id,
contactName: contact.contactName,
contactPosition: contact.contactPosition || null,
contactEmail: contact.contactEmail,
@@ -1457,7 +1612,7 @@ export async function createTechVendorFromSignup(params: {
// 4. 첨부파일 처리
if (params.files && params.files.length > 0) {
- await storeTechVendorFiles(tx, newVendor.id, params.files, "GENERAL");
+ await storeTechVendorFiles(tx, vendorResult.id, params.files, "GENERAL");
console.log("첨부파일 저장 완료:", params.files.length, "개");
}
@@ -1474,7 +1629,7 @@ export async function createTechVendorFromSignup(params: {
const [newUser] = await tx.insert(users).values({
name: params.vendorData.vendorName,
email: params.vendorData.email,
- techCompanyId: newVendor.id, // 중요: techCompanyId 설정
+ techCompanyId: vendorResult.id, // 중요: techCompanyId 설정
domain: "partners",
}).returning();
userId = newUser.id;
@@ -1483,7 +1638,7 @@ export async function createTechVendorFromSignup(params: {
// 기존 유저의 techCompanyId 업데이트
if (!existingUser.techCompanyId) {
await tx.update(users)
- .set({ techCompanyId: newVendor.id })
+ .set({ techCompanyId: vendorResult.id })
.where(eq(users.id, existingUser.id));
console.log("기존 유저의 techCompanyId 업데이트:", existingUser.id);
}
@@ -1494,13 +1649,13 @@ export async function createTechVendorFromSignup(params: {
if (params.vendorData.email) {
await tx.update(techVendorCandidates)
.set({
- vendorId: newVendor.id,
+ vendorId: vendorResult.id,
status: "INVITED"
})
.where(eq(techVendorCandidates.contactEmail, params.vendorData.email));
}
- return { vendor: newVendor, userId };
+ return { vendor: vendorResult, userId };
});
// 캐시 무효화
@@ -1538,6 +1693,7 @@ export async function addTechVendor(input: {
representativeEmail?: string | null;
representativePhone?: string | null;
representativeBirth?: string | null;
+ isQuoteComparison?: boolean;
}) {
unstable_noStore();
@@ -1565,7 +1721,7 @@ export async function addTechVendor(input: {
const [newVendor] = await tx.insert(techVendors).values({
vendorName: input.vendorName,
vendorCode: input.vendorCode || null,
- taxId: input.taxId,
+ taxId: input.taxId || null,
country: input.country || null,
countryEng: input.countryEng || null,
countryFab: input.countryFab || null,
@@ -1577,7 +1733,8 @@ export async function addTechVendor(input: {
email: input.email,
website: input.website || null,
techVendorType: Array.isArray(input.techVendorType) ? input.techVendorType.join(',') : input.techVendorType,
- status: "ACTIVE",
+ status: input.isQuoteComparison ? "PENDING_INVITE" : "ACTIVE",
+ isQuoteComparison: input.isQuoteComparison || false,
representativeName: input.representativeName || null,
representativeEmail: input.representativeEmail || null,
representativePhone: input.representativePhone || null,
@@ -1586,7 +1743,11 @@ export async function addTechVendor(input: {
console.log("벤더 생성 성공:", newVendor.id);
- // 3. 유저 생성 (techCompanyId 설정)
+ // 3. 견적비교용 벤더인 경우 PENDING_REVIEW 상태로 생성됨
+ // 초대는 별도의 초대 버튼을 통해 진행
+ console.log("벤더 생성 완료:", newVendor.id, "상태:", newVendor.status);
+
+ // 4. 유저 생성 (techCompanyId 설정)
console.log("유저 생성 시도:", input.email);
// 이미 존재하는 유저인지 확인
@@ -1650,3 +1811,80 @@ export async function getTechVendorPossibleItemsCount(vendorId: number): Promise
}
}
+/**
+ * 기술영업 벤더 초대 메일 발송
+ */
+export async function inviteTechVendor(params: {
+ vendorId: number;
+ subject: string;
+ message: string;
+ recipientEmail: string;
+}) {
+ unstable_noStore();
+
+ try {
+ console.log("기술영업 벤더 초대 메일 발송 시작:", params.vendorId);
+
+ const result = await db.transaction(async (tx) => {
+ // 벤더 정보 조회
+ const vendor = await tx.query.techVendors.findFirst({
+ where: eq(techVendors.id, params.vendorId),
+ });
+
+ if (!vendor) {
+ throw new Error("벤더를 찾을 수 없습니다.");
+ }
+
+ // 벤더 상태를 INVITED로 변경 (PENDING_INVITE에서)
+ if (vendor.status !== "PENDING_INVITE") {
+ throw new Error("초대 가능한 상태가 아닙니다. (PENDING_INVITE 상태만 초대 가능)");
+ }
+
+ await tx.update(techVendors)
+ .set({
+ status: "INVITED",
+ updatedAt: new Date(),
+ })
+ .where(eq(techVendors.id, params.vendorId));
+
+ // 초대 토큰 생성
+ const { createTechVendorInvitationToken, createTechVendorSignupUrl } = await import("@/lib/tech-vendor-invitation-token");
+ const { sendEmail } = await import("@/lib/mail/sendEmail");
+
+ const invitationToken = await createTechVendorInvitationToken({
+ vendorId: vendor.id,
+ vendorName: vendor.vendorName,
+ email: params.recipientEmail,
+ });
+
+ const signupUrl = await createTechVendorSignupUrl(invitationToken);
+
+ // 초대 메일 발송
+ await sendEmail({
+ to: params.recipientEmail,
+ subject: params.subject,
+ template: "tech-vendor-invitation",
+ context: {
+ companyName: vendor.vendorName,
+ language: "ko",
+ registrationLink: signupUrl,
+ customMessage: params.message,
+ }
+ });
+
+ console.log("초대 메일 발송 완료:", params.recipientEmail);
+
+ return { vendor, invitationToken, signupUrl };
+ });
+
+ // 캐시 무효화
+ revalidateTag("tech-vendors");
+
+ console.log("기술영업 벤더 초대 완료:", result);
+ return { success: true, data: result };
+ } catch (error) {
+ console.error("기술영업 벤더 초대 실패:", error);
+ return { success: false, error: getErrorMessage(error) };
+ }
+}
+
diff --git a/lib/tech-vendors/table/add-vendor-dialog.tsx b/lib/tech-vendors/table/add-vendor-dialog.tsx
index da9880d4..22c03bcc 100644
--- a/lib/tech-vendors/table/add-vendor-dialog.tsx
+++ b/lib/tech-vendors/table/add-vendor-dialog.tsx
@@ -51,6 +51,7 @@ const addVendorSchema = z.object({
representativeEmail: z.string().email("올바른 이메일 주소를 입력해주세요").optional().or(z.literal("")),
representativePhone: z.string().optional(),
representativeBirth: z.string().optional(),
+ isQuoteComparison: z.boolean().default(false),
})
type AddVendorFormData = z.infer<typeof addVendorSchema>
@@ -84,6 +85,7 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) {
representativeEmail: "",
representativePhone: "",
representativeBirth: "",
+ isQuoteComparison: false,
},
})
@@ -108,6 +110,7 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) {
representativePhone: data.representativePhone || null,
representativeBirth: data.representativeBirth || null,
taxId: data.taxId || "",
+ isQuoteComparison: data.isQuoteComparison,
})
if (result.success) {
@@ -238,6 +241,31 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) {
</FormItem>
)}
/>
+
+ <FormField
+ control={form.control}
+ name="isQuoteComparison"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-start space-x-3 space-y-0">
+ <FormControl>
+ <input
+ type="checkbox"
+ checked={field.value}
+ onChange={field.onChange}
+ className="w-4 h-4 mt-1"
+ />
+ </FormControl>
+ <div className="space-y-1 leading-none">
+ <FormLabel className="cursor-pointer">
+ 견적비교용 벤더
+ </FormLabel>
+ <p className="text-sm text-muted-foreground">
+ 체크 시 초대 메일을 발송하고 벤더가 직접 가입할 수 있습니다.
+ </p>
+ </div>
+ </FormItem>
+ )}
+ />
</div>
{/* 연락처 정보 */}
@@ -333,52 +361,6 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) {
</div>
</div>
- {/* 담당자 정보 */}
- <div className="space-y-4">
- <h3 className="text-lg font-medium">담당자 정보</h3>
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={form.control}
- name="agentName"
- render={({ field }) => (
- <FormItem>
- <FormLabel>담당자명</FormLabel>
- <FormControl>
- <Input placeholder="담당자명을 입력하세요" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="agentPhone"
- render={({ field }) => (
- <FormItem>
- <FormLabel>담당자 전화번호</FormLabel>
- <FormControl>
- <Input placeholder="담당자 전화번호를 입력하세요" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <FormField
- control={form.control}
- name="agentEmail"
- render={({ field }) => (
- <FormItem>
- <FormLabel>담당자 이메일</FormLabel>
- <FormControl>
- <Input type="email" placeholder="담당자 이메일을 입력하세요" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
-
{/* 대표자 정보 */}
<div className="space-y-4">
<h3 className="text-lg font-medium">대표자 정보</h3>
diff --git a/lib/tech-vendors/table/invite-tech-vendor-dialog.tsx b/lib/tech-vendors/table/invite-tech-vendor-dialog.tsx
new file mode 100644
index 00000000..823b2f4d
--- /dev/null
+++ b/lib/tech-vendors/table/invite-tech-vendor-dialog.tsx
@@ -0,0 +1,184 @@
+"use client"
+
+import * as React from "react"
+import { Button } from "@/components/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog"
+import { Badge } from "@/components/ui/badge"
+import { Mail, Send, Loader2, UserCheck } from "lucide-react"
+import { toast } from "sonner"
+import { TechVendor } from "@/db/schema/techVendors"
+import { inviteTechVendor } from "../service"
+
+// 더 이상 폼 스키마 불필요
+
+interface InviteTechVendorDialogProps {
+ vendors: TechVendor[]
+ open?: boolean
+ onOpenChange?: (open: boolean) => void
+ showTrigger?: boolean
+ onSuccess?: () => void
+}
+
+export function InviteTechVendorDialog({
+ vendors,
+ open,
+ onOpenChange,
+ showTrigger = true,
+ onSuccess,
+}: InviteTechVendorDialogProps) {
+ const [isLoading, setIsLoading] = React.useState(false)
+
+ const onSubmit = async () => {
+ if (vendors.length === 0) {
+ toast.error("초대할 벤더를 선택해주세요.")
+ return
+ }
+
+ setIsLoading(true)
+ try {
+ let successCount = 0
+ let errorCount = 0
+
+ for (const vendor of vendors) {
+ try {
+ const result = await inviteTechVendor({
+ vendorId: vendor.id,
+ subject: "기술영업 협력업체 등록 초대",
+ message: `안녕하세요.
+
+저희 EVCP 플랫폼에서 기술영업 협력업체로 등록하여 다양한 프로젝트에 참여하실 수 있는 기회를 제공하고 있습니다.
+
+아래 링크를 통해 업체 정보를 등록하시기 바랍니다.
+
+감사합니다.`,
+ recipientEmail: vendor.email || "",
+ })
+
+ if (result.success) {
+ successCount++
+ } else {
+ errorCount++
+ console.error(`벤더 ${vendor.vendorName} 초대 실패:`, result.error)
+ }
+ } catch (error) {
+ errorCount++
+ console.error(`벤더 ${vendor.vendorName} 초대 실패:`, error)
+ }
+ }
+
+ if (successCount > 0) {
+ toast.success(`${successCount}개 업체에 초대 메일이 성공적으로 발송되었습니다.`)
+ onOpenChange?.(false)
+ onSuccess?.()
+ }
+
+ if (errorCount > 0) {
+ toast.error(`${errorCount}개 업체 초대 메일 발송에 실패했습니다.`)
+ }
+ } catch (error) {
+ console.error("초대 메일 발송 실패:", error)
+ toast.error("초대 메일 발송 중 오류가 발생했습니다.")
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const getStatusBadge = (status: string) => {
+ const statusConfig = {
+ ACTIVE: { variant: "default" as const, text: "활성 상태", className: "bg-emerald-100 text-emerald-800" },
+ INACTIVE: { variant: "secondary" as const, text: "비활성 상태", className: "bg-gray-100 text-gray-800" },
+ PENDING_INVITE: { variant: "outline" as const, text: "초대 대기", className: "bg-blue-100 text-blue-800" },
+ INVITED: { variant: "outline" as const, text: "초대 완료", className: "bg-green-100 text-green-800" },
+ QUOTE_COMPARISON: { variant: "outline" as const, text: "견적 비교", className: "bg-purple-100 text-purple-800" },
+ BLACKLISTED: { variant: "destructive" as const, text: "거래 금지", className: "bg-red-100 text-red-800" },
+ }
+
+ const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.INACTIVE
+ return <Badge variant={config.variant} className={config.className}>{config.text}</Badge>
+ }
+
+ if (vendors.length === 0) {
+ return null
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ {showTrigger && (
+ <DialogTrigger asChild>
+ <Button variant="outline" size="sm" className="gap-2">
+ <Mail className="h-4 w-4" />
+ 초대 메일 발송 ({vendors.length})
+ </Button>
+ </DialogTrigger>
+ )}
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <UserCheck className="h-5 w-5" />
+ 기술영업 벤더 초대
+ </DialogTitle>
+ <DialogDescription>
+ 선택한 {vendors.length}개 벤더에게 등록 초대 메일을 발송합니다.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-6">
+ {/* 벤더 정보 */}
+ <div className="rounded-lg border bg-muted/50 p-4">
+ <h3 className="font-semibold mb-2">초대 대상 벤더 ({vendors.length}개)</h3>
+ <div className="space-y-2 max-h-60 overflow-y-auto">
+ {vendors.map((vendor) => (
+ <div key={vendor.id} className="flex items-center justify-between p-2 border rounded bg-background">
+ <div className="flex-1">
+ <div className="font-medium">{vendor.vendorName}</div>
+ <div className="text-sm text-muted-foreground">
+ {vendor.email || "이메일 없음"}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ {getStatusBadge(vendor.status)}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* 초대 확인 */}
+ <div className="space-y-4">
+
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange?.(false)}
+ disabled={isLoading}
+ >
+ 취소
+ </Button>
+ <Button onClick={onSubmit} disabled={isLoading}>
+ {isLoading ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ 발송 중...
+ </>
+ ) : (
+ <>
+ <Send className="mr-2 h-4 w-4" />
+ 초대 메일 발송
+ </>
+ )}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+} \ No newline at end of file
diff --git a/lib/tech-vendors/table/tech-vendors-table-columns.tsx b/lib/tech-vendors/table/tech-vendors-table-columns.tsx
index 69396c99..052794ce 100644
--- a/lib/tech-vendors/table/tech-vendors-table-columns.tsx
+++ b/lib/tech-vendors/table/tech-vendors-table-columns.tsx
@@ -225,6 +225,25 @@ export function getColumns({ setRowAction, router, openItemsDialog }: GetColumns
className: "bg-gray-100 text-gray-800 border-gray-300",
iconColor: "text-gray-600"
};
+
+ case "PENDING_INVITE":
+ return {
+ variant: "default",
+ className: "bg-blue-100 text-blue-800 border-blue-300",
+ iconColor: "text-blue-600"
+ };
+ case "INVITED":
+ return {
+ variant: "default",
+ className: "bg-green-100 text-green-800 border-green-300",
+ iconColor: "text-green-600"
+ };
+ case "QUOTE_COMPARISON":
+ return {
+ variant: "default",
+ className: "bg-purple-100 text-purple-800 border-purple-300",
+ iconColor: "text-purple-600"
+ };
case "BLACKLISTED":
return {
variant: "destructive",
@@ -246,7 +265,9 @@ export function getColumns({ setRowAction, router, openItemsDialog }: GetColumns
"ACTIVE": "활성 상태",
"INACTIVE": "비활성 상태",
"BLACKLISTED": "거래 금지",
- "PENDING_REVIEW": "비교 견적"
+ "PENDING_INVITE": "초대 대기",
+ "INVITED": "초대 완료",
+ "QUOTE_COMPARISON": "견적 비교"
};
return statusMap[status] || status;
@@ -269,56 +290,58 @@ export function getColumns({ setRowAction, router, openItemsDialog }: GetColumns
);
}
// TechVendorType 컬럼을 badge로 표시
- // if (cfg.id === "techVendorType") {
- // const techVendorType = row.original.techVendorType as string;
+ if (cfg.id === "techVendorType") {
+ const techVendorType = row.original.techVendorType as string | null | undefined;
- // // 벤더 타입 파싱 개선
- // let types: string[] = [];
- // if (!techVendorType) {
- // types = [];
- // } else if (techVendorType.startsWith('[') && techVendorType.endsWith(']')) {
- // // JSON 배열 형태
- // try {
- // const parsed = JSON.parse(techVendorType);
- // types = Array.isArray(parsed) ? parsed.filter(Boolean) : [techVendorType];
- // } catch {
- // types = [techVendorType];
- // }
- // } else if (techVendorType.includes(',')) {
- // // 콤마로 구분된 문자열
- // types = techVendorType.split(',').map(t => t.trim()).filter(Boolean);
- // } else {
- // // 단일 문자열
- // types = [techVendorType.trim()].filter(Boolean);
- // }
- // // 벤더 타입 정렬 - 조선 > 해양top > 해양hull 순
- // const typeOrder = ["조선", "해양top", "해양hull"];
- // types.sort((a, b) => {
- // const indexA = typeOrder.indexOf(a);
- // const indexB = typeOrder.indexOf(b);
-
- // // 정의된 순서에 있는 경우 우선순위 적용
- // if (indexA !== -1 && indexB !== -1) {
- // return indexA - indexB;
- // }
- // return a.localeCompare(b);
- // });
- // return (
- // <div className="flex flex-wrap gap-1">
- // {types.length > 0 ? types.map((type, index) => (
- // <Badge key={`${type}-${index}`} variant="secondary" className="text-xs">
- // {type}
- // </Badge>
- // )) : (
- // <span className="text-muted-foreground">-</span>
- // )}
- // </div>
- // );
- // }
+ // 벤더 타입 파싱 개선 - null/undefined 안전 처리
+ let types: string[] = [];
+ if (!techVendorType) {
+ types = [];
+ } else if (techVendorType.startsWith('[') && techVendorType.endsWith(']')) {
+ // JSON 배열 형태
+ try {
+ const parsed = JSON.parse(techVendorType);
+ types = Array.isArray(parsed) ? parsed.filter(Boolean) : [techVendorType];
+ } catch {
+ types = [techVendorType];
+ }
+ } else if (techVendorType.includes(',')) {
+ // 콤마로 구분된 문자열
+ types = techVendorType.split(',').map(t => t.trim()).filter(Boolean);
+ } else {
+ // 단일 문자열
+ types = [techVendorType.trim()].filter(Boolean);
+ }
+
+ // 벤더 타입 정렬 - 조선 > 해양top > 해양hull 순
+ const typeOrder = ["조선", "해양top", "해양hull"];
+ types.sort((a, b) => {
+ const indexA = typeOrder.indexOf(a);
+ const indexB = typeOrder.indexOf(b);
+
+ // 정의된 순서에 있는 경우 우선순위 적용
+ if (indexA !== -1 && indexB !== -1) {
+ return indexA - indexB;
+ }
+ return a.localeCompare(b);
+ });
+
+ return (
+ <div className="flex flex-wrap gap-1">
+ {types.length > 0 ? types.map((type, index) => (
+ <Badge key={`${type}-${index}`} variant="secondary" className="text-xs">
+ {type}
+ </Badge>
+ )) : (
+ <span className="text-muted-foreground">-</span>
+ )}
+ </div>
+ );
+ }
// 날짜 컬럼 포맷팅
if (cfg.type === "date" && cell.getValue()) {
- return formatDate(cell.getValue() as Date, "KR");
+ return formatDate(cell.getValue() as Date);
}
return cell.getValue();
diff --git a/lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx b/lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx
index 06b2cc42..ac7ee184 100644
--- a/lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx
+++ b/lib/tech-vendors/table/tech-vendors-table-toolbar-actions.tsx
@@ -20,6 +20,7 @@ import { TechVendor } from "@/db/schema/techVendors"
import { ImportTechVendorButton } from "./import-button"
import { exportTechVendorTemplate } from "./excel-template-download"
import { AddVendorDialog } from "./add-vendor-dialog"
+import { InviteTechVendorDialog } from "./invite-tech-vendor-dialog"
interface TechVendorsTableToolbarActionsProps {
table: Table<TechVendor>
@@ -36,6 +37,13 @@ export function TechVendorsTableToolbarActions({ table, onRefresh }: TechVendors
.rows
.map(row => row.original);
}, [table.getFilteredSelectedRowModel().rows]);
+
+ // 초대 가능한 벤더들 (PENDING_INVITE 상태 + 이메일 있음)
+ const invitableVendors = React.useMemo(() => {
+ return selectedVendors.filter(vendor =>
+ vendor.status === "PENDING_INVITE" && vendor.email
+ );
+ }, [selectedVendors]);
// 테이블의 모든 벤더 가져오기 (필터링된 결과)
const allFilteredVendors = React.useMemo(() => {
@@ -97,6 +105,14 @@ export function TechVendorsTableToolbarActions({ table, onRefresh }: TechVendors
return (
<div className="flex items-center gap-2">
+ {/* 초대 버튼 - 선택된 PENDING_REVIEW 벤더들이 있을 때만 표시 */}
+ {invitableVendors.length > 0 && (
+ <InviteTechVendorDialog
+ vendors={invitableVendors}
+ onSuccess={handleVendorAddSuccess}
+ />
+ )}
+
{/* 벤더 추가 다이얼로그 추가 */}
<AddVendorDialog onSuccess={handleVendorAddSuccess} />
diff --git a/lib/tech-vendors/table/tech-vendors-table.tsx b/lib/tech-vendors/table/tech-vendors-table.tsx
index 125e39dc..a8e18501 100644
--- a/lib/tech-vendors/table/tech-vendors-table.tsx
+++ b/lib/tech-vendors/table/tech-vendors-table.tsx
@@ -59,7 +59,9 @@ export function TechVendorsTable({ promises }: TechVendorsTableProps) {
"ACTIVE": "활성 상태",
"INACTIVE": "비활성 상태",
"BLACKLISTED": "거래 금지",
- "PENDING_REVIEW": "비교 견적",
+ "PENDING_INVITE": "초대 대기",
+ "INVITED": "초대 완료",
+ "QUOTE_COMPARISON": "견적 비교",
};
return statusMap[status] || status;
@@ -187,6 +189,7 @@ export function TechVendorsTable({ promises }: TechVendorsTableProps) {
onOpenChange={setItemsDialogOpen}
vendor={selectedVendorForItems}
/>
+
</>
)
} \ No newline at end of file
diff --git a/lib/tech-vendors/utils.ts b/lib/tech-vendors/utils.ts
index 693a6929..e409975a 100644
--- a/lib/tech-vendors/utils.ts
+++ b/lib/tech-vendors/utils.ts
@@ -1,4 +1,4 @@
-import { LucideIcon, Hourglass, CheckCircle2, XCircle, CircleAlert, Clock, ShieldAlert } from "lucide-react";
+import { LucideIcon, CheckCircle2, CircleAlert, Clock, ShieldAlert, Mail, BarChart2 } from "lucide-react";
import type { TechVendor } from "@/db/schema/techVendors";
type StatusType = TechVendor["status"];
@@ -8,8 +8,12 @@ type StatusType = TechVendor["status"];
*/
export function getVendorStatusIcon(status: StatusType): LucideIcon {
switch (status) {
- case "PENDING_REVIEW":
- return Hourglass;
+ case "PENDING_INVITE":
+ return Clock;
+ case "INVITED":
+ return Mail;
+ case "QUOTE_COMPARISON":
+ return BarChart2;
case "ACTIVE":
return CheckCircle2;
case "INACTIVE":
diff --git a/lib/tech-vendors/validations.ts b/lib/tech-vendors/validations.ts
index fa0d9ae3..0c850c1f 100644
--- a/lib/tech-vendors/validations.ts
+++ b/lib/tech-vendors/validations.ts
@@ -168,7 +168,7 @@ export const createTechVendorSchema = z
.min(1, "국가 선택은 필수입니다.")
.max(100, "Max length 100"),
phone: z.string().max(50, "Max length 50").optional(),
- website: z.string().url("유효하지 않은 URL입니다. https:// 혹은 http:// 로 시작하는 주소를 입력해주세요.").max(255).optional(),
+ website: z.string().max(255).optional(),
files: z.any().optional(),
status: z.enum(techVendors.status.enumValues).default("ACTIVE"),
@@ -233,6 +233,7 @@ export const createTechVendorContactSchema = z.object({
contactPosition: z.string().max(100, "Max length 100"),
contactEmail: z.string().email(),
contactPhone: z.string().max(50, "Max length 50").optional(),
+ country: z.string().max(100, "Max length 100").optional(),
isPrimary: z.boolean(),
});
@@ -244,6 +245,7 @@ export const updateTechVendorContactSchema = z.object({
contactPosition: z.string().max(100, "Max length 100").optional(),
contactEmail: z.string().email().optional(),
contactPhone: z.string().max(50, "Max length 50").optional(),
+ country: z.string().max(100, "Max length 100").optional(),
isPrimary: z.boolean().optional(),
});
@@ -260,10 +262,56 @@ export const updateTechVendorItemSchema = z.object({
itemCode: z.string().max(100, "Max length 100"),
});
+export const searchParamsRfqHistoryCache = createSearchParamsCache({
+ // 공통 플래그
+ flags: parseAsArrayOf(z.enum(["advancedTable", "floatingBar"])).withDefault(
+ []
+ ),
+
+ // 페이징
+ page: parseAsInteger.withDefault(1),
+ perPage: parseAsInteger.withDefault(10),
+
+ // 정렬 (RFQ 히스토리에 맞춰)
+ sort: getSortingStateParser<{
+ id: number;
+ rfqCode: string | null;
+ description: string | null;
+ projectCode: string | null;
+ projectName: string | null;
+ projectType: string | null; // 프로젝트 타입 추가
+ status: string;
+ totalAmount: string | null;
+ currency: string | null;
+ dueDate: Date | null;
+ createdAt: Date;
+ quotationCode: string | null;
+ submittedAt: Date | null;
+ }>().withDefault([
+ { id: "createdAt", desc: true },
+ ]),
+
+ // 고급 필터
+ filters: getFiltersStateParser().withDefault([]),
+ joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"),
+
+ // 검색 키워드
+ search: parseAsString.withDefault(""),
+
+ // RFQ 히스토리 특화 필드
+ rfqCode: parseAsString.withDefault(""),
+ description: parseAsString.withDefault(""),
+ projectCode: parseAsString.withDefault(""),
+ projectName: parseAsString.withDefault(""),
+ projectType: parseAsStringEnum(["SHIP", "TOP", "HULL"]), // 프로젝트 타입 필터 추가
+ status: parseAsStringEnum(["DRAFT", "PUBLISHED", "EVALUATION", "AWARDED"]),
+});
+
// 타입 내보내기
export type GetTechVendorsSchema = Awaited<ReturnType<typeof searchParamsCache.parse>>
export type GetTechVendorContactsSchema = Awaited<ReturnType<typeof searchParamsContactCache.parse>>
export type GetTechVendorItemsSchema = Awaited<ReturnType<typeof searchParamsItemCache.parse>>
+export type GetTechVendorRfqHistorySchema = Awaited<ReturnType<typeof searchParamsRfqHistoryCache.parse>>
export type UpdateTechVendorSchema = z.infer<typeof updateTechVendorSchema>
export type CreateTechVendorSchema = z.infer<typeof createTechVendorSchema>