diff options
Diffstat (limited to 'components')
| -rw-r--r-- | components/additional-info/tech-vendor-info-form.tsx | 513 | ||||
| -rw-r--r-- | components/document-lists/vendor-doc-list-client.tsx | 2 | ||||
| -rw-r--r-- | components/form-data/form-data-table.tsx | 2 | ||||
| -rw-r--r-- | components/spread-js/dataBinding.tsx | 491 | ||||
| -rw-r--r-- | components/spread-js/testSheet.tsx | 90 | ||||
| -rw-r--r-- | components/tech-vendors/tech-vendor-container.tsx | 100 | ||||
| -rw-r--r-- | components/tech-vendors/tech-vendor-items-container.tsx | 121 |
7 files changed, 1317 insertions, 2 deletions
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/document-lists/vendor-doc-list-client.tsx b/components/document-lists/vendor-doc-list-client.tsx index 4dea591f..d914b6f0 100644 --- a/components/document-lists/vendor-doc-list-client.tsx +++ b/components/document-lists/vendor-doc-list-client.tsx @@ -51,7 +51,7 @@ export default function VendorDocumentListClient({ setProjectType("plant") // Navigate to the contract's documents page - router.push(`/partners/document-list/${contractId}?projectType=plnat`) + router.push(`/partners/document-list/${contractId}?projectType=plant`) } return ( diff --git a/components/form-data/form-data-table.tsx b/components/form-data/form-data-table.tsx index b59684e3..92ec3c56 100644 --- a/components/form-data/form-data-table.tsx +++ b/components/form-data/form-data-table.tsx @@ -111,7 +111,7 @@ async function fetchTemplateFromSEDP(projectCode: string, formCode: string): Pro // Make the API call const response = await fetch( - `${SEDP_API_BASE_URL}/Data/GetPubData`, + `${SEDP_API_BASE_URL}/Template/GetByRegisterID`, { method: 'POST', headers: { diff --git a/components/spread-js/dataBinding.tsx b/components/spread-js/dataBinding.tsx new file mode 100644 index 00000000..52171dbf --- /dev/null +++ b/components/spread-js/dataBinding.tsx @@ -0,0 +1,491 @@ +// @ts-nocheck +"use client"; + +import * as React from "react"; +import GC from "@mescius/spread-sheets"; +import "@mescius/spread-sheets-resources-ko"; +import { SpreadSheets } from "@mescius/spread-sheets-react"; + +GC.Spread.Common.CultureManager.culture("ko-kr"); +GC.Spread.Sheets.LicenseKey = process.env.NEXT_PUBLIC_SPREADJS_KEY +GC.Spread.Sheets.Designer.LicenseKey = process.env.NEXT_PUBLIC_SPREADJS_KEY + +const DataBinding = () => { + let spread = null; + let dataSource1 = null; + let dataSource2 = null; + + const changeDataSource = () => { + if (!spread) return; + let sheet = spread.getActiveSheet(); + if (sheet.getDataSource() === dataSource1) { + sheet.setDataSource(dataSource2); + } else { + sheet.setDataSource(dataSource1); + } + }; + const initSpread = (currSpread) => { + spread = currSpread; + + if(currSpread){ + let company1 = new Company( + "Baidu", + null, + "We know everything!", + "Beijing 1st road", + "Beijing", + "010-12345678", + "baidu@baidu.com" + ), + company2 = new Company( + "Tecent", + null, + "We have everything!", + "Shenzhen 2st road", + "Shenzhen", + "0755-12345678", + "tecent@qq.com" + ), + company3 = new Company( + "Alibaba", + null, + "We sale everything!", + "Hangzhou 3rd road", + "Hangzhou", + "0571-12345678", + "alibaba@alibaba.com" + ), + customer1 = new Customer("A1", "employee 1", company2), + customer2 = new Customer("A2", "employee 2", company3), + records1 = [ + new Record("Finance charge on overdue balance at 1.5%", 1, 150), + new Record("Invoice #100 for $1000 on 2014/1/1", 1, 150), + ], + records2 = [ + new Record("Purchase server device", 2, 15000), + new Record("Company travel", 100, 1500), + new Record("Company Dinner", 100, 200), + new Record("Company Dinner", 100, 200), + new Record("Company Dinner", 100, 200), + new Record("Company Dinner", 100, 200), + new Record("Company Dinner", 100, 200), + new Record("Company Dinner", 100, 200), + ], + invoice1 = new Invoice( + company1, + "00001", + new Date(2014, 0, 1), + customer1, + customer1, + records1 + ), + invoice2 = new Invoice( + company2, + "00002", + new Date(2014, 6, 6), + customer2, + customer2, + records2 + ); + + dataSource1 = new GC.Spread.Sheets.Bindings.CellBindingSource(invoice1); + dataSource2 = new GC.Spread.Sheets.Bindings.CellBindingSource(invoice2); + + //Get sheet instance + spread.suspendPaint(); + let sheet = spread.sheets[0]; + sheet.name("FINANCE CHARGE"); + + //Set value or bindingPath and style + let bindingPathCellType = new BindingPathCellType(); + sheet + .getCell(1, 2) + .bindingPath("company.slogan") + .cellType(bindingPathCellType) + .vAlign(GC.Spread.Sheets.VerticalAlign.bottom); + sheet + .getCell(1, 4) + .value("INVOICE") + .foreColor("#58B6C0") + .font("33px Arial"); + sheet + .getCell(3, 1) + .bindingPath("company.name") + .cellType(bindingPathCellType) + .foreColor("#58B6C0") + .font("bold 20px Arial"); + sheet + .getCell(5, 1) + .bindingPath("company.address") + .cellType(bindingPathCellType); + sheet.getCell(5, 3).value("INVOICE NO.").font("bold 15px Arial"); + sheet.getCell(5, 4).bindingPath("number").cellType(bindingPathCellType); + sheet + .getCell(6, 1) + .bindingPath("company.city") + .cellType(bindingPathCellType); + sheet.getCell(6, 3).value("DATE").font("bold 15px Arial"); + sheet + .getCell(6, 4) + .bindingPath("date") + .cellType(bindingPathCellType) + .formatter("MM/dd/yyyy") + .hAlign(GC.Spread.Sheets.HorizontalAlign.left); + sheet + .getCell(7, 1) + .bindingPath("company.phone") + .cellType(bindingPathCellType); + sheet.getCell(7, 3).value("CUSTOMER ID").font("bold 15px Arial"); + sheet + .getCell(7, 4) + .bindingPath("customer.id") + .cellType(bindingPathCellType); + sheet + .getCell(8, 1) + .bindingPath("company.email") + .cellType(bindingPathCellType); + sheet.getCell(10, 1).value("TO").font("bold 15px Arial"); + sheet.getCell(10, 3).value("SHIP TO").font("bold 15px Arial"); + sheet + .getCell(11, 1) + .bindingPath("customer.name") + .cellType(bindingPathCellType) + .textIndent(10); + sheet + .getCell(12, 1) + .bindingPath("customer.company.name") + .cellType(bindingPathCellType) + .textIndent(10); + sheet + .getCell(13, 1) + .bindingPath("customer.company.address") + .cellType(bindingPathCellType) + .textIndent(10); + sheet + .getCell(14, 1) + .bindingPath("customer.company.city") + .cellType(bindingPathCellType) + .textIndent(10); + sheet + .getCell(15, 1) + .bindingPath("customer.company.phone") + .cellType(bindingPathCellType) + .textIndent(10); + sheet + .getCell(11, 4) + .bindingPath("receiverCustomer.name") + .cellType(bindingPathCellType); + sheet + .getCell(12, 4) + .bindingPath("receiverCustomer.company.name") + .cellType(bindingPathCellType); + sheet + .getCell(13, 4) + .bindingPath("receiverCustomer.company.address") + .cellType(bindingPathCellType); + sheet + .getCell(14, 4) + .bindingPath("receiverCustomer.company.city") + .cellType(bindingPathCellType); + sheet + .getCell(15, 4) + .bindingPath("receiverCustomer.company.phone") + .cellType(bindingPathCellType); + sheet.addSpan(17, 1, 1, 2); + sheet + .getCell(17, 1) + .value("JOB") + .foreColor("#58B6C0") + .font("bold 12px Arial"); + sheet.addSpan(17, 3, 1, 2); + sheet + .getCell(17, 3) + .value("PAYMENT TERMS") + .foreColor("#58B6C0") + .font("bold 12px Arial"); + sheet.addSpan(18, 1, 1, 2); + sheet.getCell(18, 1).backColor("#DDF0F2"); + sheet.addSpan(18, 3, 1, 2); + sheet + .getCell(18, 3) + .value("Due on receipt") + .backColor("#DDF0F2") + .foreColor("#58B6C0") + .font("12px Arial"); + sheet + .getRange(17, 1, 2, 4) + .setBorder( + new GC.Spread.Sheets.LineBorder( + "#58B6C0", + GC.Spread.Sheets.LineStyle.thin + ), + { top: true, bottom: true, innerHorizontal: true } + ); + let table = sheet.tables.add( + "tableRecordds", + 20, + 1, + 1, + 4, + GC.Spread.Sheets.Tables.TableThemes.light6 + ); + table.autoGenerateColumns(false); + let tableColumn1 = new GC.Spread.Sheets.Tables.TableColumn(0); + tableColumn1.name("DESCRIPTION"); + tableColumn1.dataField("description"); + let tableColumn2 = new GC.Spread.Sheets.Tables.TableColumn(1); + tableColumn2.name("QUANTITY"); + tableColumn2.dataField("quantity"); + let tableColumn3 = new GC.Spread.Sheets.Tables.TableColumn(2); + tableColumn3.name("AMOUNT"); + tableColumn3.dataField("amount"); + table.bindColumns([tableColumn1, tableColumn2, tableColumn3]); + table.bindingPath("records"); + table.showFooter(true); + table.setColumnName(3, "TOTAL"); + table.setColumnValue(2, "TOTAL DUE"); + table.setColumnDataFormula(3, "=[@QUANTITY]*[@AMOUNT]"); + table.setColumnFormula(3, "=SUBTOTAL(109,[TOTAL])"); + sheet + .getCell(26, 1) + .formula( + '="Make all checks payable to "&B4&". THANK YOU FOR YOUR BUSINESS!"' + ) + .foreColor("gray") + .font("italic 14px Arial"); + sheet.options.allowCellOverflow = true; + //Adjust row height and column width + sheet.setColumnWidth(0, 5); + sheet.setColumnWidth(1, 300); + sheet.setColumnWidth(2, 115); + sheet.setColumnWidth(3, 125); + sheet.setColumnWidth(4, 155); + sheet.setRowHeight(0, 5); + sheet.setRowHeight(1, 40); + sheet.setRowHeight(2, 10); + sheet.setRowHeight(3, 28); + sheet.setRowHeight(17, 0); + sheet.setRowHeight(18, 0); + sheet.setRowHeight(19, 0); + sheet.setRowHeight(25, 10); + sheet.options.gridline = { + showHorizontalGridline: false, + showVerticalGridline: false, + }; + + spread.resumePaint(); + } + }; + + return ( + <div className="sample-tutorial"> + <div className="sample-spreadsheets"> + <SpreadSheets workbookInitialized={(spread) => initSpread(spread)} /> + </div> + <div className="options-container"> + <div className="option-row"> + <label style={{ backgroundColor: "#F4F8EB" }}> + Click this button to set the data source for the data-bound table. + </label> + </div> + <input + type="button" + onClick={() => { + changeDataSource(); + }} + id="changeDataSource" + value="Set DataSource" + title="Toggle table binding's data source" + /> + <div className="option-row"> + <label style={{ backgroundColor: "#F4F8EB" }}> + 데이터 바인딩 위치 확인 + </label> + </div> + <input + type="button" + onClick={() => { + extractBindingPaths(spread); + }} + id="changeDataSource" + value="데이터 바인딩 위치 확인" + title="Toggle table binding's data source" + /> + <div className="option-row"> + <label style={{ backgroundColor: "#F4F8EB" }}> + 테이블 데이터 바인딩 위치 확인 + </label> + </div> + <input + type="button" + onClick={() => { + extractTableBindingPaths(spread); + }} + id="changeDataSource" + value="테이블 데이터 바인딩 위치 확인" + title="Toggle table binding's data source" + /> + <div className="option-row"> + <label style={{ backgroundColor: "#F4F8EB" }}>값 가져오기</label> + </div> + <input + type="button" + onClick={() => { + extractAllCellsWithValues(spread); + }} + id="changeDataSource" + value="테이블 데이터 바인딩 위치 확인" + title="Toggle table binding's data source" + /> + </div> + </div> + ); +}; + +export default DataBinding; + +class Company { + constructor( + public name?: string | null, + public logo?: string | null, + public slogan?: string | null, + public address?: string | null, + public city?: string | null, + public phone?: string | null, + public email?: string | null + ) {} +} + +class Customer { + constructor( + public id?: string, + public name?: string, + public company?: Company + ) {} +} + +class Record { + constructor( + public description?: string, + public quantity?: number, + public amount?: number + ) {} +} + +class Invoice { + constructor( + public company: Company, + public number: string, + public date: Date, + public customer: Customer, + public receiverCustomer: Customer, + public records: Record[] | [] + ) {} +} + +class BindingPathCellType extends GC.Spread.Sheets.CellTypes.Text { + constructor() { + super(); + } + + paint(ctx, value, x, y, w, h, style, context) { + if (value === null || value === undefined) { + let sheet = context.sheet, + row = context.row, + col = context.col; + if (sheet && (row === 0 || !!row) && (col === 0 || !!col)) { + let bindingPath = sheet.getBindingPath(context.row, context.col); + if (bindingPath) { + value = "[" + bindingPath + "]"; + } + } + } + super.paint(ctx, value, x, y, w, h, style, context); + } +} + +const extractBindingPaths = (spread) => { + let sheet = spread.getActiveSheet(); + let bindingPaths = []; + + for (let row = 0; row < sheet.getRowCount(); row++) { + for (let col = 0; col < sheet.getColumnCount(); col++) { + let bindingPath = sheet.getBindingPath(row, col); + if (bindingPath) { + bindingPaths.push({ row, col, bindingPath }); + } + } + } + + console.log( + "Extracted Binding Paths:", + JSON.stringify(bindingPaths, null, 2) + ); + return bindingPaths; +}; + +const extractTableBindingPaths = (spread) => { + let sheet = spread.getActiveSheet(); + let tables = sheet.tables.all(); + let tableBindings = []; + + tables.forEach((table) => { + let range = table.range(); // 테이블의 위치 정보 가져오기 + let tableInfo = { + tableName: table.name(), + bindingPath: table.bindingPath(), + tablePosition: { + startRow: range.row, + startCol: range.col, + rowCount: range.rowCount, + colCount: range.colCount, + }, + columns: [], + }; + + // 🔹 컬럼 바인딩 정보 직접 추출 (bindColumns() 사용 안함) + for (let c = range.col; c < range.col + range.colCount; c++) { + let bindingPath = sheet.getBindingPath(range.row, c); + let headerValue = sheet.getValue(range.row, c); + + if (bindingPath) { + tableInfo.columns.push({ + colIndex: c, + columnName: headerValue || `Column ${c - range.col + 1}`, + dataField: bindingPath, + }); + } + } + + tableBindings.push(tableInfo); + }); + + console.log( + "📌 바인딩된 위치 및 컬럼 정보:", + JSON.stringify(tableBindings, null, 2) + ); + return tableBindings; +}; + +const extractAllCellsWithValues = (spread) => { + let sheet = spread.getActiveSheet(); + let rowCount = sheet.getRowCount(); + let colCount = sheet.getColumnCount(); + let cellData = []; + + for (let row = 0; row < rowCount; row++) { + for (let col = 0; col < colCount; col++) { + let value = sheet.getValue(row, col); + if (value !== null && value !== undefined && value !== "") { + cellData.push({ + row: row, + col: col, + value: value, + }); + } + } + } + + console.log("📌 모든 값이 있는 셀 정보:", JSON.stringify(cellData, null, 2)); + return cellData; +}; diff --git a/components/spread-js/testSheet.tsx b/components/spread-js/testSheet.tsx new file mode 100644 index 00000000..0d69798e --- /dev/null +++ b/components/spread-js/testSheet.tsx @@ -0,0 +1,90 @@ +// @ts-nocheck +"use client"; + +import React, { useState } from "react"; +import "@mescius/spread-sheets-print"; +import "@mescius/spread-sheets-io"; +import "@mescius/spread-sheets-shapes"; +import "@mescius/spread-sheets-charts"; +import "@mescius/spread-sheets-slicers"; +import "@mescius/spread-sheets-pivot-addon"; +import "@mescius/spread-sheets-reportsheet-addon"; +import "@mescius/spread-sheets-tablesheet"; +import "@mescius/spread-sheets-ganttsheet"; +import "@mescius/spread-sheets-resources-ko"; +import "@mescius/spread-sheets-formula-panel"; +import "@mescius/spread-sheets-designer-resources-ko"; +import '@mescius/spread-sheets-datacharts-addon'; +import * as GC from "@mescius/spread-sheets"; +import { Designer } from "@mescius/spread-sheets-designer-react"; +import { + addSheet, + clearSheet, + createSampleReportForm, + removeSheet, + setSampleReportData, + exportJSON,handleFileImport +} from "@/lib/spread-js/fns"; +import { Button } from "@/components/ui/button"; + +// SpreadJS 라이선싱 +// var SpreadJSKey = "xxx"; // 라이선스 키 입력 +// GC.Spread.Sheets.LicenseKey = SpreadJSKey; +GC.Spread.Common.CultureManager.culture("ko-kr"); +GC.Spread.Sheets.LicenseKey = process.env.NEXT_PUBLIC_SPREADJS_KEY +GC.Spread.Sheets.Designer.LicenseKey = process.env.NEXT_PUBLIC_SPREADJS_KEY + +export default function SpreadSheet() { + const [spread, setSpread] = useState(null); + + function initSpread(spread) { + setSpread(spread); + //init Status Bar + var statusBar = new GC.Spread.Sheets.StatusBar.StatusBar( + document.getElementById("statusBar") + ); + statusBar.bind(spread); + } + + return ( + <div className="relative h-full overflow-hidden"> + <div className="sample-container"> + <div className="w-[calc(100%-280px)] h-full overflow-hidden float-left"> + <Designer + styleInfo={{ height: "100%" }} + designerInitialized={async (designer: any) => { + initSpread(designer.getWorkbook()); + designer.refresh(); + }} + spreadOptions={{ allowDragHeaderToMove: 3 }} + /> + </div> + <div id="statusBar"></div> + </div> + <div className="float-right w-[280px] p-[12px] h-full box-border bg-[#fbfbfb]"> + <div className="p-[5px] mt-[10px]"> + + <div className="flex flex-col gap-2"> + <Button onClick={() => addSheet(spread)}>Add Sheet</Button> + <Button onClick={() => removeSheet(spread)}>Remove Sheet</Button> + <Button onClick={() => clearSheet(spread)}>Clear Sheet</Button> + <Button onClick={() => createSampleReportForm(spread)}> + Create Report Form + </Button> + <Button onClick={() => setSampleReportData(spread)}> + Set Report Data + </Button> + <Button onClick={() => exportJSON(spread)}> + Export JSON + </Button> + <Button onClick={() => handleFileImport(spread)}> + Import JSON + </Button> + </div> + </div> + </div> + </div> + ); +} + + 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 |
