diff options
| -rw-r--r-- | app/[lng]/evcp/(evcp)/tech-vendors/page.tsx | 43 | ||||
| -rw-r--r-- | app/[lng]/partners/(partners)/info/page.tsx | 12 | ||||
| -rw-r--r-- | components/additional-info/tech-vendor-info-form.tsx | 513 | ||||
| -rw-r--r-- | components/tech-vendors/tech-vendor-container.tsx | 100 | ||||
| -rw-r--r-- | components/tech-vendors/tech-vendor-items-container.tsx | 121 | ||||
| -rw-r--r-- | lib/tech-vendors/service.ts | 157 | ||||
| -rw-r--r-- | lib/tech-vendors/table/add-vendor-dialog.tsx | 50 | ||||
| -rw-r--r-- | lib/tech-vendors/table/excel-template-download.tsx | 4 | ||||
| -rw-r--r-- | lib/tech-vendors/table/update-vendor-sheet.tsx | 58 | ||||
| -rw-r--r-- | lib/tech-vendors/table/vendor-all-export.ts | 1 | ||||
| -rw-r--r-- | lib/tech-vendors/validations.ts | 9 |
11 files changed, 984 insertions, 84 deletions
diff --git a/app/[lng]/evcp/(evcp)/tech-vendors/page.tsx b/app/[lng]/evcp/(evcp)/tech-vendors/page.tsx index 64e8737f..8f542f59 100644 --- a/app/[lng]/evcp/(evcp)/tech-vendors/page.tsx +++ b/app/[lng]/evcp/(evcp)/tech-vendors/page.tsx @@ -2,14 +2,13 @@ import * as React from "react" import { type SearchParams } from "@/types/table"
import { getValidFilters } from "@/lib/data-table"
-import { Skeleton } from "@/components/ui/skeleton"
import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton"
import { Shell } from "@/components/shell"
-import { Ellipsis } from "lucide-react"
import { searchParamsCache } from "@/lib/tech-vendors/validations"
import { getTechVendors, getTechVendorStatusCounts } from "@/lib/tech-vendors/service"
import { TechVendorsTable } from "@/lib/tech-vendors/table/tech-vendors-table"
+import { TechVendorContainer } from "@/components/tech-vendors/tech-vendor-container"
interface IndexPageProps {
searchParams: Promise<SearchParams>
@@ -21,6 +20,14 @@ export default async function IndexPage(props: IndexPageProps) { const validFilters = getValidFilters(search.filters)
+ // 벤더 타입 정의
+ const vendorTypes = [
+ { id: "all", name: "전체", value: "" },
+ { id: "ship", name: "조선", value: "조선" },
+ { id: "top", name: "해양TOP", value: "해양TOP" },
+ { id: "hull", name: "해양HULL", value: "해양HULL" },
+ ]
+
const promises = Promise.all([
getTechVendors({
...search,
@@ -30,33 +37,7 @@ export default async function IndexPage(props: IndexPageProps) { ])
return (
- <Shell className="gap-2">
- <div className="flex items-center justify-between space-y-2">
- <div className="flex items-center justify-between space-y-2">
- <div>
- <h2 className="text-2xl font-bold tracking-tight">
- 기술영업 벤더 리스트
- </h2>
- <p className="text-muted-foreground">
- 기술영업 벤더에 대한 요약 정보를 확인하고{" "}
- <span className="inline-flex items-center whitespace-nowrap">
- <Ellipsis className="size-3" />
- <span className="ml-1">버튼</span>
- </span>
- 을 통해 담당자 연락처, 입찰 이력, 계약 이력, 패키지 내용 등을 확인 할 수 있습니다.
- </p>
- </div>
- </div>
- </div>
-
- <React.Suspense fallback={<Skeleton className="h-7 w-52" />}>
- {/* <DateRangePicker
- triggerSize="sm"
- triggerClassName="ml-auto w-56 sm:w-60"
- align="end"
- shallow={false}
- /> */}
- </React.Suspense>
+ <Shell className="gap-4">
<React.Suspense
fallback={
<DataTableSkeleton
@@ -68,7 +49,9 @@ export default async function IndexPage(props: IndexPageProps) { />
}
>
- <TechVendorsTable promises={promises} />
+ <TechVendorContainer vendorTypes={vendorTypes}>
+ <TechVendorsTable promises={promises} />
+ </TechVendorContainer>
</React.Suspense>
</Shell>
)
diff --git a/app/[lng]/partners/(partners)/info/page.tsx b/app/[lng]/partners/(partners)/info/page.tsx index 8215a451..cc1252e6 100644 --- a/app/[lng]/partners/(partners)/info/page.tsx +++ b/app/[lng]/partners/(partners)/info/page.tsx @@ -1,7 +1,10 @@ import { Suspense } from "react" import { Metadata } from "next" +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" import { JoinFormSkeleton } from "@/components/signup/join-form-skeleton" import { InfoForm } from "@/components/additional-info/join-form" +import { TechVendorInfoForm } from "@/components/additional-info/tech-vendor-info-form" // (Optional) If Next.js attempts to statically optimize this page and you need full runtime // behavior for query params, you may also need: @@ -12,10 +15,15 @@ export const metadata: Metadata = { description: "Authentication forms built using the components.", } -export default function IndexPage() { +export default async function IndexPage() { + const session = await getServerSession(authOptions) + + // 사용자의 techCompanyId가 있는지 확인 + const isTechVendor = session?.user?.techCompanyId + return ( <Suspense fallback={<JoinFormSkeleton/>}> - <InfoForm /> + {isTechVendor ? <TechVendorInfoForm /> : <InfoForm />} </Suspense> ) }
\ No newline at end of file diff --git a/components/additional-info/tech-vendor-info-form.tsx b/components/additional-info/tech-vendor-info-form.tsx new file mode 100644 index 00000000..8e6f7eaf --- /dev/null +++ b/components/additional-info/tech-vendor-info-form.tsx @@ -0,0 +1,513 @@ +"use client"
+
+import * as React from "react"
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useForm } from "react-hook-form"
+import { useSession } from "next-auth/react"
+
+import { Button } from "@/components/ui/button"
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form"
+import { Input } from "@/components/ui/input"
+import { toast } from "@/hooks/use-toast"
+import { Download, Loader2, Mail, Phone, User } from "lucide-react"
+import { Badge } from "@/components/ui/badge"
+
+// 기술영업 벤더 관련 임포트
+import { getTechVendorDetailById, modifyTechVendor } from "@/lib/tech-vendors/service"
+import { updateTechVendorSchema, type UpdateTechVendorSchema } from "@/lib/tech-vendors/validations"
+
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card"
+
+// 타입 정의
+interface TechVendorContact {
+ id: number
+ contactName: string
+ contactPosition: string | null
+ contactEmail: string
+ contactPhone: string | null
+ isPrimary: boolean
+}
+
+interface TechVendorAttachment {
+ id: number
+ fileName: string
+ filePath: string
+ attachmentType: string
+ createdAt: Date
+ updatedAt: Date
+}
+
+export function TechVendorInfoForm() {
+ const { data: session } = useSession()
+ const techCompanyId = session?.user?.techCompanyId
+
+ // 기술영업 벤더 데이터 상태
+ const [vendor, setVendor] = React.useState<any>(null)
+ const [contacts, setContacts] = React.useState<TechVendorContact[]>([])
+ const [attachments, setAttachments] = React.useState<TechVendorAttachment[]>([])
+ const [isLoading, setIsLoading] = React.useState(true)
+ const [isSubmitting, setIsSubmitting] = React.useState(false)
+ const [isDownloading, setIsDownloading] = React.useState(false)
+
+ // React Hook Form (기술영업 벤더용 스키마 사용)
+ const form = useForm<UpdateTechVendorSchema>({
+ resolver: zodResolver(updateTechVendorSchema),
+ defaultValues: {
+ vendorName: "",
+ vendorCode: "",
+ address: "",
+ email: "",
+ phone: "",
+ country: "",
+ website: "",
+ techVendorType: "",
+ status: "ACTIVE",
+ },
+ mode: "onChange",
+ })
+
+ const isFormValid = form.formState.isValid
+
+ // 기술영업 벤더 정보 가져오기
+ React.useEffect(() => {
+ async function fetchTechVendorData() {
+ if (!techCompanyId) return
+
+ try {
+ setIsLoading(true)
+ // 기술영업 벤더 상세 정보 가져오기 (연락처, 첨부파일 포함)
+ const vendorData = await getTechVendorDetailById(Number(techCompanyId))
+
+ if (!vendorData) {
+ toast({
+ variant: "destructive",
+ title: "오류",
+ description: "기술영업 벤더 정보를 찾을 수 없습니다.",
+ })
+ return
+ }
+
+ setVendor(vendorData)
+ setContacts(vendorData.contacts || [])
+ setAttachments(vendorData.attachments || [])
+
+ // 폼 기본값 설정
+ const formValues = {
+ vendorName: vendorData.vendorName || "",
+ vendorCode: vendorData.vendorCode || "",
+ address: vendorData.address || "",
+ email: vendorData.email || "",
+ phone: vendorData.phone || "",
+ country: vendorData.country || "",
+ website: vendorData.website || "",
+ techVendorType: vendorData.techVendorType || "",
+ status: vendorData.status || "ACTIVE",
+ }
+
+ form.reset(formValues)
+ } catch (error) {
+ console.error("Error fetching tech vendor data:", error)
+ toast({
+ variant: "destructive",
+ title: "데이터 로드 오류",
+ description: "기술영업 벤더 정보를 불러오는 중 오류가 발생했습니다.",
+ })
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ fetchTechVendorData()
+ }, [techCompanyId, form])
+
+ const handleDownloadFile = async (file: TechVendorAttachment) => {
+ try {
+ setIsDownloading(true)
+
+ const downloadUrl = `/api/tech-vendors/attachments/download?id=${file.id}&vendorId=${Number(techCompanyId)}`
+
+ const downloadLink = document.createElement('a')
+ downloadLink.href = downloadUrl
+ downloadLink.download = file.fileName
+ downloadLink.target = '_blank'
+ document.body.appendChild(downloadLink)
+ downloadLink.click()
+
+ setTimeout(() => {
+ document.body.removeChild(downloadLink)
+ }, 100)
+
+ toast({
+ title: "다운로드 시작",
+ description: "파일 다운로드가 시작되었습니다.",
+ })
+ } catch (error) {
+ console.error("Error downloading file:", error)
+ toast({
+ variant: "destructive",
+ title: "다운로드 오류",
+ description: "파일 다운로드 중 오류가 발생했습니다.",
+ })
+ } finally {
+ setIsDownloading(false)
+ }
+ }
+
+ const handleDownloadAllFiles = async () => {
+ try {
+ setIsDownloading(true)
+
+ const downloadUrl = `/api/tech-vendors/attachments/download-all?vendorId=${Number(techCompanyId)}`
+
+ const downloadLink = document.createElement('a')
+ downloadLink.href = downloadUrl
+ downloadLink.download = `tech-vendor-${techCompanyId}-files.zip`
+ downloadLink.target = '_blank'
+ document.body.appendChild(downloadLink)
+ downloadLink.click()
+
+ setTimeout(() => {
+ document.body.removeChild(downloadLink)
+ }, 100)
+
+ toast({
+ title: "다운로드 시작",
+ description: "전체 파일 다운로드가 시작되었습니다.",
+ })
+ } catch (error) {
+ console.error("Error downloading files:", error)
+ toast({
+ variant: "destructive",
+ title: "다운로드 오류",
+ description: "파일 다운로드 중 오류가 발생했습니다.",
+ })
+ } finally {
+ setIsDownloading(false)
+ }
+ }
+
+ async function onSubmit(values: UpdateTechVendorSchema) {
+ if (!techCompanyId) return
+
+ setIsSubmitting(true)
+
+ try {
+ const { error } = await modifyTechVendor({
+ ...values,
+ id: String(techCompanyId),
+ })
+
+ if (error) {
+ throw new Error(error)
+ }
+
+ toast({
+ title: "업데이트 완료",
+ description: "기술영업 벤더 정보가 성공적으로 업데이트되었습니다.",
+ })
+ } catch (error) {
+ console.error("Error updating tech vendor:", error)
+ toast({
+ variant: "destructive",
+ title: "업데이트 오류",
+ description: "기술영업 벤더 정보 업데이트 중 오류가 발생했습니다.",
+ })
+ } finally {
+ setIsSubmitting(false)
+ }
+ }
+
+ if (isLoading) {
+ return (
+ <div className="flex items-center justify-center p-8">
+ <Loader2 className="h-8 w-8 animate-spin" />
+ <span className="ml-2">기술영업 벤더 정보를 불러오는 중...</span>
+ </div>
+ )
+ }
+
+ if (!vendor) {
+ return (
+ <div className="flex items-center justify-center p-8">
+ <span>기술영업 벤더 정보를 찾을 수 없습니다.</span>
+ </div>
+ )
+ }
+
+ return (
+ <div className="space-y-6 p-6">
+ <div className="flex items-center justify-between">
+ <div>
+ <h2 className="text-2xl font-bold">기술영업 벤더 정보</h2>
+ <p className="text-gray-600">기술영업 벤더 정보를 확인하고 업데이트할 수 있습니다.</p>
+ </div>
+ {attachments.length > 0 && (
+ <Button
+ variant="outline"
+ onClick={handleDownloadAllFiles}
+ disabled={isDownloading}
+ >
+ <Download className="h-4 w-4 mr-2" />
+ {isDownloading ? "다운로드 중..." : "전체 파일 다운로드"}
+ </Button>
+ )}
+ </div>
+
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>기본 정보</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="vendorName"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>벤더명</FormLabel>
+ <FormControl>
+ <Input {...field} disabled />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="vendorCode"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>벤더 코드</FormLabel>
+ <FormControl>
+ <Input {...field} disabled />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ {/* 사업자등록번호 */}
+ {vendor.taxId && (
+ <div>
+ <label className="text-sm font-medium text-gray-600">사업자등록번호</label>
+ <p className="mt-1">{vendor.taxId}</p>
+ </div>
+ )}
+
+ {/* 공급품목 */}
+ {vendor.items && (
+ <div>
+ <label className="text-sm font-medium text-gray-600">공급품목</label>
+ <p className="mt-1 text-sm leading-relaxed">{vendor.items}</p>
+ </div>
+ )}
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>이메일</FormLabel>
+ <FormControl>
+ <Input {...field} type="email" />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="phone"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>전화번호</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <FormField
+ control={form.control}
+ name="address"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>주소</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="country"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>국가</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="website"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>웹사이트</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ </CardContent>
+ </Card>
+
+
+ {/* 연락처 정보 */}
+ {contacts.length > 0 && (
+ <Card>
+ <CardHeader>
+ <CardTitle>연락처 정보</CardTitle>
+ <CardDescription>
+ 등록된 연락처 정보입니다.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-4">
+ {contacts.map((contact) => (
+ <div
+ key={contact.id}
+ className="flex items-center justify-between p-4 border rounded-lg"
+ >
+ <div className="flex items-center space-x-4">
+ <div className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-100">
+ <User className="h-5 w-5 text-blue-600" />
+ </div>
+ <div>
+ <div className="flex items-center space-x-2">
+ <h4 className="font-medium">{contact.contactName}</h4>
+ {contact.isPrimary && (
+ <Badge variant="secondary">주 담당자</Badge>
+ )}
+ </div>
+ {contact.contactPosition && (
+ <p className="text-sm text-gray-600">{contact.contactPosition}</p>
+ )}
+ </div>
+ </div>
+ <div className="flex space-x-2">
+ {contact.contactEmail && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => window.open(`mailto:${contact.contactEmail}`)}
+ >
+ <Mail className="h-4 w-4" />
+ </Button>
+ )}
+ {contact.contactPhone && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => window.open(`tel:${contact.contactPhone}`)}
+ >
+ <Phone className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ )}
+
+ {/* 첨부파일 정보 */}
+ {attachments.length > 0 && (
+ <Card>
+ <CardHeader>
+ <CardTitle>첨부파일</CardTitle>
+ <CardDescription>
+ 업로드된 파일들을 확인하고 다운로드할 수 있습니다.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-2">
+ {attachments.map((file) => (
+ <div
+ key={file.id}
+ className="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50"
+ >
+ <div className="flex-1">
+ <h4 className="font-medium">{file.fileName}</h4>
+ <div className="flex items-center space-x-2 text-sm text-gray-600">
+ <span>{file.attachmentType}</span>
+ <span>•</span>
+ <span>{new Date(file.createdAt).toLocaleDateString()}</span>
+ </div>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => handleDownloadFile(file)}
+ disabled={isDownloading}
+ >
+ <Download className="h-4 w-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ )}
+
+ <div className="flex justify-end space-x-4">
+ <Button
+ type="submit"
+ disabled={isSubmitting || !isFormValid}
+ >
+ {isSubmitting ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ 업데이트 중...
+ </>
+ ) : (
+ "정보 업데이트"
+ )}
+ </Button>
+ </div>
+ </form>
+ </Form>
+ </div>
+ )
+}
\ No newline at end of file diff --git a/components/tech-vendors/tech-vendor-container.tsx b/components/tech-vendors/tech-vendor-container.tsx new file mode 100644 index 00000000..583d507c --- /dev/null +++ b/components/tech-vendors/tech-vendor-container.tsx @@ -0,0 +1,100 @@ +"use client"
+
+import * as React from "react"
+import { useRouter, usePathname, useSearchParams } from "next/navigation"
+import { ChevronDown } from "lucide-react"
+
+import { Button } from "@/components/ui/button"
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu"
+
+interface VendorType {
+ id: string
+ name: string
+ value: string
+}
+
+interface TechVendorContainerProps {
+ vendorTypes: VendorType[]
+ children: React.ReactNode
+}
+
+export function TechVendorContainer({
+ vendorTypes,
+ children,
+}: TechVendorContainerProps) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const searchParamsObj = useSearchParams()
+
+ // useSearchParams를 메모이제이션하여 안정적인 참조 생성
+ const searchParams = React.useMemo(
+ () => searchParamsObj || new URLSearchParams(),
+ [searchParamsObj]
+ )
+
+ // URL에서 현재 선택된 벤더 타입 가져오기
+ const vendorType = searchParams.get("vendorType") || "all"
+
+ // 선택한 벤더 타입에 해당하는 이름 찾기
+ const selectedVendor = vendorTypes.find((vendor) => vendor.id === vendorType)?.name || "전체"
+
+ // 벤더 타입 변경 핸들러
+ const handleVendorTypeChange = React.useCallback((value: string) => {
+ const params = new URLSearchParams(searchParams.toString())
+ if (value === "all") {
+ params.delete("vendorType")
+ } else {
+ params.set("vendorType", value)
+ }
+
+ router.push(`${pathname}?${params.toString()}`)
+ }, [router, pathname, searchParams])
+
+ return (
+ <>
+ {/* 상단 영역: 제목 왼쪽 / 벤더 타입 선택기 오른쪽 */}
+ <div className="flex items-center justify-between">
+ {/* 왼쪽: 타이틀 & 설명 */}
+ <div>
+ <h2 className="text-2xl font-bold tracking-tight">기술영업 벤더 리스트</h2>
+ <p className="text-muted-foreground">
+ 기술영업 벤더에 대한 요약 정보를 확인하고 관리할 수 있습니다.
+ </p>
+ </div>
+
+ {/* 오른쪽: 벤더 타입 드롭다운 */}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" className="min-w-[150px]">
+ {selectedVendor}
+ <ChevronDown className="ml-2 h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-[200px]">
+ {vendorTypes.map((vendor) => (
+ <DropdownMenuItem
+ key={vendor.id}
+ onClick={() => handleVendorTypeChange(vendor.id)}
+ className={vendor.id === vendorType ? "bg-muted" : ""}
+ >
+ {vendor.name}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ {/* 컨텐츠 영역 */}
+ <section className="overflow-hidden">
+ <div>
+ {children}
+ </div>
+ </section>
+ </>
+ )
+}
\ No newline at end of file diff --git a/components/tech-vendors/tech-vendor-items-container.tsx b/components/tech-vendors/tech-vendor-items-container.tsx new file mode 100644 index 00000000..49a9d4ee --- /dev/null +++ b/components/tech-vendors/tech-vendor-items-container.tsx @@ -0,0 +1,121 @@ +"use client"
+
+import * as React from "react"
+import { useRouter, usePathname, useSearchParams } from "next/navigation"
+import { ChevronDown } from "lucide-react"
+
+import { type TechVendor } from "@/db/schema/techVendors"
+
+import { Button } from "@/components/ui/button"
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu"
+import { TechVendorItemsTable } from "@/lib/tech-vendors/items-table/item-table"
+import { getVendorItemsByType } from "@/lib/tech-vendors/service"
+
+interface ItemType {
+ id: string
+ name: string
+ vendorType: string
+}
+
+interface TechVendorItemsContainerProps {
+ vendorId: number
+ vendor: TechVendor
+ itemTypes: ItemType[]
+}
+
+export function TechVendorItemsContainer({
+ vendorId,
+ vendor,
+ itemTypes,
+}: TechVendorItemsContainerProps) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const searchParamsObj = useSearchParams()
+
+ // useSearchParams를 메모이제이션하여 안정적인 참조 생성
+ const currentSearchParams = React.useMemo(
+ () => searchParamsObj || new URLSearchParams(),
+ [searchParamsObj]
+ )
+
+ // URL에서 현재 선택된 아이템 타입 가져오기 (기본값은 첫 번째 타입)
+ const itemType = currentSearchParams.get("type") || itemTypes[0]?.id || "ship"
+
+ // 선택한 아이템 타입에 해당하는 정보 찾기
+ const selectedItemType = itemTypes.find((item) => item.id === itemType) || itemTypes[0]
+
+ // 아이템 타입 변경 핸들러
+ const handleItemTypeChange = React.useCallback((value: string) => {
+ const params = new URLSearchParams(currentSearchParams.toString())
+ params.set("type", value)
+
+ router.push(`${pathname}?${params.toString()}`)
+ }, [router, pathname, currentSearchParams])
+
+ // 현재 선택된 벤더 타입에 대한 아이템 데이터 가져오기
+ const promises = React.useMemo(() => {
+ if (selectedItemType) {
+ return getVendorItemsByType(vendorId, selectedItemType.vendorType)
+ }
+ return Promise.resolve({ data: [] })
+ }, [vendorId, selectedItemType])
+
+ // 벤더 타입이 하나뿐인 경우 드롭다운 숨기기
+ const showDropdown = itemTypes.length > 1
+
+ return (
+ <>
+ {/* 상단 영역: 제목 왼쪽 / 아이템 타입 선택기 오른쪽 */}
+ <div className="flex items-center justify-between">
+ {/* 왼쪽: 타이틀 & 설명 */}
+ <div>
+ <h4 className="text-lg font-medium">자재 목록</h4>
+ <p className="text-sm text-muted-foreground">
+ {vendor.vendorName}의 공급 가능한 자재 목록입니다.
+ </p>
+ </div>
+
+ {/* 오른쪽: 아이템 타입 드롭다운 (타입이 여러 개인 경우에만 표시) */}
+ {showDropdown && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" className="min-w-[150px]">
+ {selectedItemType?.name || "타입 선택"}
+ <ChevronDown className="ml-2 h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-[200px]">
+ {itemTypes.map((item) => (
+ <DropdownMenuItem
+ key={item.id}
+ onClick={() => handleItemTypeChange(item.id)}
+ className={item.id === itemType ? "bg-muted" : ""}
+ >
+ {item.name}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+
+ {/* 컨텐츠 영역 */}
+ <section className="overflow-hidden">
+ <div>
+ {selectedItemType && (
+ <TechVendorItemsTable
+ promises={promises}
+ vendorId={vendorId}
+ vendorType={selectedItemType.vendorType}
+ />
+ )}
+ </div>
+ </section>
+ </>
+ )
+}
\ No newline at end of file diff --git a/lib/tech-vendors/service.ts b/lib/tech-vendors/service.ts index 05ec1178..b2dec1ab 100644 --- a/lib/tech-vendors/service.ts +++ b/lib/tech-vendors/service.ts @@ -2,7 +2,7 @@ import { revalidateTag, unstable_noStore } from "next/cache"; import db from "@/db/db"; -import { techVendorAttachments, techVendorContacts, techVendorPossibleItems, techVendors, techVendorItemsView, type TechVendor } from "@/db/schema/techVendors"; +import { techVendorAttachments, techVendorContacts, techVendorPossibleItems, techVendors, techVendorItemsView, type TechVendor, techVendorCandidates } from "@/db/schema/techVendors"; import { items, itemShipbuilding, itemOffshoreTop, itemOffshoreHull } from "@/db/schema/items"; import { filterColumns } from "@/lib/filter-columns"; @@ -272,7 +272,7 @@ export async function createTechVendor(input: CreateTechVendorSchema) { phone: input.phone || null, email: input.email, website: input.website || null, - techVendorType: input.techVendorType as "조선" | "해양TOP" | "해양HULL", + techVendorType: Array.isArray(input.techVendorType) ? input.techVendorType.join(',') : input.techVendorType, representativeName: input.representativeName || null, representativeBirth: input.representativeBirth || null, representativeEmail: input.representativeEmail || null, @@ -1066,9 +1066,9 @@ export async function exportTechVendorDetails(vendorIds: number[]) { } /** - * 기술영업 벤더 상세 정보 조회 + * 기술영업 벤더 상세 정보 조회 (연락처, 첨부파일 포함) */ -async function getTechVendorDetailById(id: number) { +export async function getTechVendorDetailById(id: number) { try { const vendor = await db.select().from(techVendors).where(eq(techVendors.id, id)).limit(1); @@ -1255,7 +1255,7 @@ export async function importTechVendorsFromExcel( phone: vendor.phone || null, email: vendor.email, website: vendor.website || null, - techVendorType: vendor.techVendorType as "조선" | "해양TOP" | "해양HULL", + techVendorType: vendor.techVendorType, status: "ACTIVE", representativeName: vendor.representativeName || null, representativeEmail: vendor.representativeEmail || null, @@ -1345,6 +1345,149 @@ export async function findTechVendorById(id: number): Promise<TechVendor | null> } /** + * 회원가입 폼을 통한 기술영업 벤더 생성 (초대 토큰 기반) + */ +export async function createTechVendorFromSignup(params: { + vendorData: { + vendorName: string + vendorCode?: string + items: string + website?: string + taxId: string + address?: string + email: string + phone?: string + country: string + techVendorType: "조선" | "해양TOP" | "해양HULL" + representativeName?: string + representativeBirth?: string + representativeEmail?: string + representativePhone?: string + } + files?: File[] + contacts: { + contactName: string + contactPosition?: string + contactEmail: string + contactPhone?: string + isPrimary?: boolean + }[] + invitationToken?: string // 초대 토큰 +}) { + unstable_noStore(); + + try { + console.log("기술영업 벤더 회원가입 시작:", params.vendorData.vendorName); + + 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 } + }); + + 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(); + + 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, + contactName: contact.contactName, + contactPosition: contact.contactPosition || null, + contactEmail: contact.contactEmail, + contactPhone: contact.contactPhone || null, + isPrimary: index === 0, // 첫 번째 연락처를 primary로 설정 + }); + } + console.log("연락처 생성 완료:", params.contacts.length, "개"); + } + + // 4. 첨부파일 처리 + if (params.files && params.files.length > 0) { + await storeTechVendorFiles(tx, newVendor.id, params.files, "GENERAL"); + console.log("첨부파일 저장 완료:", params.files.length, "개"); + } + + // 5. 유저 생성 (techCompanyId 설정) + console.log("유저 생성 시도:", params.vendorData.email); + + const existingUser = await tx.query.users.findFirst({ + where: eq(users.email, params.vendorData.email), + columns: { id: true, techCompanyId: true } + }); + + let userId = null; + if (!existingUser) { + const [newUser] = await tx.insert(users).values({ + name: params.vendorData.vendorName, + email: params.vendorData.email, + techCompanyId: newVendor.id, // 중요: techCompanyId 설정 + domain: "partners", + }).returning(); + userId = newUser.id; + console.log("유저 생성 성공:", userId); + } else { + // 기존 유저의 techCompanyId 업데이트 + if (!existingUser.techCompanyId) { + await tx.update(users) + .set({ techCompanyId: newVendor.id }) + .where(eq(users.id, existingUser.id)); + console.log("기존 유저의 techCompanyId 업데이트:", existingUser.id); + } + userId = existingUser.id; + } + + // 6. 후보에서 해당 이메일이 있으면 vendorId 업데이트 및 상태 변경 + if (params.vendorData.email) { + await tx.update(techVendorCandidates) + .set({ + vendorId: newVendor.id, + status: "INVITED" + }) + .where(eq(techVendorCandidates.contactEmail, params.vendorData.email)); + } + + return { vendor: newVendor, userId }; + }); + + // 캐시 무효화 + revalidateTag("tech-vendors"); + revalidateTag("tech-vendor-candidates"); + revalidateTag("users"); + + console.log("기술영업 벤더 회원가입 완료:", result); + return { success: true, data: result }; + } catch (error) { + console.error("기술영업 벤더 회원가입 실패:", error); + return { success: false, error: getErrorMessage(error) }; + } +} + +/** * 단일 기술영업 벤더 추가 (사용자 계정도 함께 생성) */ export async function addTechVendor(input: { @@ -1361,7 +1504,7 @@ export async function addTechVendor(input: { address?: string | null; phone?: string | null; website?: string | null; - techVendorType: "조선" | "해양TOP" | "해양HULL"; + techVendorType: string; representativeName?: string | null; representativeEmail?: string | null; representativePhone?: string | null; @@ -1404,7 +1547,7 @@ export async function addTechVendor(input: { phone: input.phone || null, email: input.email, website: input.website || null, - techVendorType: input.techVendorType, + techVendorType: Array.isArray(input.techVendorType) ? input.techVendorType.join(',') : input.techVendorType, status: "ACTIVE", representativeName: input.representativeName || null, representativeEmail: input.representativeEmail || null, diff --git a/lib/tech-vendors/table/add-vendor-dialog.tsx b/lib/tech-vendors/table/add-vendor-dialog.tsx index bc260d51..da9880d4 100644 --- a/lib/tech-vendors/table/add-vendor-dialog.tsx +++ b/lib/tech-vendors/table/add-vendor-dialog.tsx @@ -25,13 +25,7 @@ import { FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select"
+
import { Textarea } from "@/components/ui/textarea"
import { Plus, Loader2 } from "lucide-react"
@@ -52,9 +46,7 @@ const addVendorSchema = z.object({ address: z.string().optional(),
phone: z.string().optional(),
website: z.string().optional(),
- techVendorType: z.enum(["조선", "해양TOP", "해양HULL"], {
- required_error: "벤더 타입을 선택해주세요",
- }),
+ techVendorType: z.array(z.enum(["조선", "해양TOP", "해양HULL"])).min(1, "최소 하나의 벤더 타입을 선택해주세요"),
representativeName: z.string().optional(),
representativeEmail: z.string().email("올바른 이메일 주소를 입력해주세요").optional().or(z.literal("")),
representativePhone: z.string().optional(),
@@ -87,7 +79,7 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) { address: "",
phone: "",
website: "",
- techVendorType: undefined,
+ techVendorType: [],
representativeName: "",
representativeEmail: "",
representativePhone: "",
@@ -110,6 +102,7 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) { address: data.address || null,
phone: data.phone || null,
website: data.website || null,
+ techVendorType: data.techVendorType.join(','),
representativeName: data.representativeName || null,
representativeEmail: data.representativeEmail || null,
representativePhone: data.representativePhone || null,
@@ -218,18 +211,29 @@ export function AddVendorDialog({ onSuccess }: AddVendorDialogProps) { render={({ field }) => (
<FormItem>
<FormLabel>벤더 타입 *</FormLabel>
- <Select onValueChange={field.onChange} defaultValue={field.value}>
- <FormControl>
- <SelectTrigger>
- <SelectValue placeholder="벤더 타입을 선택하세요" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- <SelectItem value="조선">조선</SelectItem>
- <SelectItem value="해양TOP">해양TOP</SelectItem>
- <SelectItem value="해양HULL">해양HULL</SelectItem>
- </SelectContent>
- </Select>
+ <div className="space-y-2">
+ {["조선", "해양TOP", "해양HULL"].map((type) => (
+ <div key={type} className="flex items-center space-x-2">
+ <input
+ type="checkbox"
+ id={type}
+ checked={field.value?.includes(type as "조선" | "해양TOP" | "해양HULL")}
+ onChange={(e) => {
+ const currentValue = field.value || [];
+ if (e.target.checked) {
+ field.onChange([...currentValue, type]);
+ } else {
+ field.onChange(currentValue.filter((v) => v !== type));
+ }
+ }}
+ className="w-4 h-4"
+ />
+ <label htmlFor={type} className="text-sm font-medium cursor-pointer">
+ {type}
+ </label>
+ </div>
+ ))}
+ </div>
<FormMessage />
</FormItem>
)}
diff --git a/lib/tech-vendors/table/excel-template-download.tsx b/lib/tech-vendors/table/excel-template-download.tsx index db2c5fb5..b6011e2c 100644 --- a/lib/tech-vendors/table/excel-template-download.tsx +++ b/lib/tech-vendors/table/excel-template-download.tsx @@ -72,7 +72,7 @@ export async function exportTechVendorTemplate() { phone: '02-1234-5678', email: 'sample1@example.com', website: 'https://example1.com', - techVendorType: '조선', + techVendorType: '조선,해양TOP', representativeName: '홍길동', representativeEmail: 'ceo1@example.com', representativePhone: '010-1234-5678', @@ -93,7 +93,7 @@ export async function exportTechVendorTemplate() { phone: '051-234-5678', email: 'sample2@example.com', website: 'https://example2.com', - techVendorType: '해양TOP', + techVendorType: '해양HULL', representativeName: '김철수', representativeEmail: 'ceo2@example.com', representativePhone: '010-2345-6789', diff --git a/lib/tech-vendors/table/update-vendor-sheet.tsx b/lib/tech-vendors/table/update-vendor-sheet.tsx index cc6b4003..774299f1 100644 --- a/lib/tech-vendors/table/update-vendor-sheet.tsx +++ b/lib/tech-vendors/table/update-vendor-sheet.tsx @@ -65,24 +65,6 @@ type StatusConfig = { // 상태 표시 유틸리티 함수 const getStatusConfig = (status: StatusType): StatusConfig => { switch(status) { - case "PENDING_REVIEW": - return { - Icon: ClipboardList, - className: "text-yellow-600", - label: "가입 신청 중" - }; - case "IN_REVIEW": - return { - Icon: FilePenLine, - className: "text-blue-600", - label: "심사 중" - }; - case "REJECTED": - return { - Icon: XCircle, - className: "text-red-600", - label: "심사 거부됨" - }; case "ACTIVE": return { Icon: Activity, @@ -127,6 +109,7 @@ export function UpdateVendorSheet({ vendor, ...props }: UpdateVendorSheetProps) phone: vendor?.phone ?? "", email: vendor?.email ?? "", website: vendor?.website ?? "", + techVendorType: vendor?.techVendorType ? vendor.techVendorType.split(',').filter(Boolean) : [], status: vendor?.status ?? "ACTIVE", }, }) @@ -141,6 +124,7 @@ export function UpdateVendorSheet({ vendor, ...props }: UpdateVendorSheetProps) phone: vendor?.phone ?? "", email: vendor?.email ?? "", website: vendor?.website ?? "", + techVendorType: vendor?.techVendorType ? vendor.techVendorType.split(',').filter(Boolean) : [], status: vendor?.status ?? "ACTIVE", }); @@ -172,7 +156,8 @@ export function UpdateVendorSheet({ vendor, ...props }: UpdateVendorSheetProps) id: String(vendor.id), userId: Number(session.user.id), // Add user ID from session comment: statusComment, // Add comment for status changes - ...data // 모든 데이터 전달 - 서비스 함수에서 필요한 필드만 처리 + ...data, // 모든 데이터 전달 - 서비스 함수에서 필요한 필드만 처리 + techVendorType: data.techVendorType ? data.techVendorType.join(',') : undefined, }) if (error) throw new Error(error) @@ -312,6 +297,41 @@ export function UpdateVendorSheet({ vendor, ...props }: UpdateVendorSheetProps) )} /> + {/* techVendorType */} + <FormField + control={form.control} + name="techVendorType" + render={({ field }) => ( + <FormItem className="md:col-span-2"> + <FormLabel>벤더 타입 *</FormLabel> + <div className="space-y-2"> + {["조선", "해양TOP", "해양HULL"].map((type) => ( + <div key={type} className="flex items-center space-x-2"> + <input + type="checkbox" + id={`update-${type}`} + checked={field.value?.includes(type as "조선" | "해양TOP" | "해양HULL")} + onChange={(e) => { + const currentValue = field.value || []; + if (e.target.checked) { + field.onChange([...currentValue, type]); + } else { + field.onChange(currentValue.filter((v) => v !== type)); + } + }} + className="w-4 h-4" + /> + <label htmlFor={`update-${type}`} className="text-sm font-medium cursor-pointer"> + {type} + </label> + </div> + ))} + </div> + <FormMessage /> + </FormItem> + )} + /> + {/* status with icons */} <FormField control={form.control} diff --git a/lib/tech-vendors/table/vendor-all-export.ts b/lib/tech-vendors/table/vendor-all-export.ts index a1ad4fd1..f2650102 100644 --- a/lib/tech-vendors/table/vendor-all-export.ts +++ b/lib/tech-vendors/table/vendor-all-export.ts @@ -108,6 +108,7 @@ function createBasicInfoSheet( address: vendor.address, representativeName: vendor.representativeName, createdAt: vendor.createdAt ? formatDate(vendor.createdAt) : "", + techVendorType: vendor.techVendorType?.split(',').join(', ') || vendor.techVendorType, }); }); } diff --git a/lib/tech-vendors/validations.ts b/lib/tech-vendors/validations.ts index bae3e5b4..c45eb97d 100644 --- a/lib/tech-vendors/validations.ts +++ b/lib/tech-vendors/validations.ts @@ -117,6 +117,10 @@ export const updateTechVendorSchema = z.object({ phone: z.string().optional(), email: z.string().email("유효한 이메일 주소를 입력해주세요").optional(), website: z.string().url("유효한 URL을 입력해주세요").optional(), + techVendorType: z.union([ + z.array(z.enum(VENDOR_TYPES)).min(1, "최소 하나의 벤더 타입을 선택해주세요"), + z.string().min(1, "벤더 타입을 선택해주세요") + ]).optional(), status: z.enum(techVendors.status.enumValues).optional(), userId: z.number().optional(), comment: z.string().optional(), @@ -155,7 +159,10 @@ export const createTechVendorSchema = z files: z.any().optional(), status: z.enum(techVendors.status.enumValues).default("ACTIVE"), - techVendorType: z.enum(VENDOR_TYPES).default("조선"), + techVendorType: z.union([ + z.array(z.enum(VENDOR_TYPES)).min(1, "최소 하나의 벤더 타입을 선택해주세요"), + z.string().min(1, "벤더 타입을 선택해주세요") + ]).default(["조선"]), representativeName: z.union([z.string().max(255), z.literal("")]).optional(), representativeBirth: z.union([z.string().max(20), z.literal("")]).optional(), |
