summaryrefslogtreecommitdiff
path: root/lib/contact-possible-items/table/add-contact-item-mapping-dialog.tsx
blob: e1f76bba594a9c7025c2f48d70ae71a535b4e2a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
"use client"

import * as React from "react"
import { Search, Loader2, CheckSquare, Square, ChevronDown, ChevronRight } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import { toast } from "sonner"
import {
  searchShipbuildingItems,
  searchOffshoreTopItems,
  searchOffshoreHullItems,
  searchTechVendors,
  getTechVendorsContactsForMapping,
  addContactItemMapping,
} from "../service-add-mapping"

interface AddContactItemMappingDialogProps {
  trigger?: React.ReactNode
}

interface Item {
  id: number
  itemCode: string
  itemList: string
  workType: string | null
  shipTypes?: string | null
  subItemList?: string | null
}

interface Vendor {
  id: number
  vendorCode: string | null
  vendorName: string
  email: string | null
  techVendorType: string
  status: string
}

interface Contact {
  id: number
  contactName: string
  contactPosition: string | null
  contactTitle: string | null
  contactEmail: string
  contactPhone: string | null
  isPrimary: boolean
}

export function AddContactItemMappingDialog({ trigger }: AddContactItemMappingDialogProps) {
  const [open, setOpen] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)

  const [selectedItemType, setSelectedItemType] = React.useState<'ship' | 'top' | 'hull'>('ship')
  const [itemSearch, setItemSearch] = React.useState("")
  const [items, setItems] = React.useState<Item[]>([])
  const [selectedItems, setSelectedItems] = React.useState<Set<number>>(new Set())
  const [isLoadingItems, setIsLoadingItems] = React.useState(false)
  
  // Section 2: 벤더 선택
  const [vendorSearch, setVendorSearch] = React.useState("")
  const [vendors, setVendors] = React.useState<Vendor[]>([])
  const [selectedVendors, setSelectedVendors] = React.useState<Set<number>>(new Set())
  const [isLoadingVendors, setIsLoadingVendors] = React.useState(false)

  // Section 3: 벤더별 담당자 선택
  const [vendorContacts, setVendorContacts] = React.useState<Record<number, Contact[]>>({})
  const [selectedContacts, setSelectedContacts] = React.useState<Record<number, Set<number>>>({})
  const [expandedVendors, setExpandedVendors] = React.useState<Set<number>>(new Set())
  const [isLoadingContacts, setIsLoadingContacts] = React.useState(false)

  // 아이템 타입 변경 시 아이템 로드
  React.useEffect(() => {
    loadItems()
  }, [selectedItemType, itemSearch])

  // 벤더 검색 디바운싱
  React.useEffect(() => {
    const timer = setTimeout(() => {
      loadVendors()
    }, 300)
    return () => clearTimeout(timer)
  }, [vendorSearch])

  // 선택된 벤더 변경 시 담당자 로드
  React.useEffect(() => {
    if (selectedVendors.size > 0) {
      loadContacts()
    }
  }, [selectedVendors])

  const loadItems = async () => {
    setIsLoadingItems(true)
    try {
      let result
      if (selectedItemType === 'ship') {
        result = await searchShipbuildingItems(itemSearch)
      } else if (selectedItemType === 'top') {
        result = await searchOffshoreTopItems(itemSearch)
      } else {
        result = await searchOffshoreHullItems(itemSearch)
      }
  
      setItems(result.data || [])
    } catch (err) {
      toast.error("아이템 로드 실패")
    } finally {
      setIsLoadingItems(false)
    }
  }

  const loadVendors = async () => {
    setIsLoadingVendors(true)
    try {
      const result = await searchTechVendors(vendorSearch)
      setVendors(result.data || [])
    } catch (err) {
      toast.error("벤더 로드 실패")
    } finally {
      setIsLoadingVendors(false)
    }
  }

  const loadContacts = async () => {
    setIsLoadingContacts(true)
    try {
      const vendorIds = Array.from(selectedVendors)
      const result = await getTechVendorsContactsForMapping(vendorIds)
      
      if (result.data) {
        const contacts: Record<number, Contact[]> = {}
        Object.entries(result.data).forEach(([vendorIdStr, vendorData]) => {
          const vendorId = parseInt(vendorIdStr)
          contacts[vendorId] = vendorData.contacts
        })
        setVendorContacts(contacts)
      }
    } catch (err) {
      toast.error("담당자 로드 실패")
    } finally {
      setIsLoadingContacts(false)
    }
  }
  const handleItemTypeChange = (type: 'ship' | 'top' | 'hull') => {
    setSelectedItemType(type)
    setSelectedItems(new Set()) // 타입 변경 시 선택 초기화
    setItemSearch("") // 검색어도 초기화
  }
  
  const handleItemSelect = (itemId: number) => {
    setSelectedItems(prev => {
      const newSet = new Set(prev)
      if (newSet.has(itemId)) {
        newSet.delete(itemId)
      } else {
        newSet.add(itemId)
      }
      return newSet
    })
  }

  const handleVendorSelect = (vendorId: number) => {
    setSelectedVendors(prev => {
      const newSet = new Set(prev)
      if (newSet.has(vendorId)) {
        newSet.delete(vendorId)
        // 벤더 선택 해제 시 해당 벤더의 담당자 선택도 초기화
        setSelectedContacts(prev => {
          const newContacts = { ...prev }
          delete newContacts[vendorId]
          return newContacts
        })
      } else {
        newSet.add(vendorId)
      }
      return newSet
    })
  }

  const handleContactSelect = (vendorId: number, contactId: number) => {
    setSelectedContacts(prev => {
      const vendorContacts = prev[vendorId] || new Set()
      const newSet = new Set(vendorContacts)
      if (newSet.has(contactId)) {
        newSet.delete(contactId)
      } else {
        newSet.add(contactId)
      }
      return { ...prev, [vendorId]: newSet }
    })
  }

  const toggleVendorExpand = (vendorId: number) => {
    setExpandedVendors(prev => {
      const newSet = new Set(prev)
      if (newSet.has(vendorId)) {
        newSet.delete(vendorId)
      } else {
        newSet.add(vendorId)
      }
      return newSet
    })
  }
  const handleSubmit = async () => {
    // 검증
    if (selectedItems.size === 0) {
      toast.error("최소 1개 이상의 아이템을 선택해주세요.")
      return
    }
  
    if (selectedVendors.size === 0) {
      toast.error("최소 1개 이상의 벤더를 선택해주세요.")
      return
    }
  
    const hasSelectedContacts = Object.values(selectedContacts).some(contacts => contacts.size > 0)
    if (!hasSelectedContacts) {
      toast.error("최소 1개 이상의 담당자를 선택해주세요.")
      return
    }
  
    setIsSubmitting(true)
    try {
      // 선택된 아이템 변환
      const itemType = selectedItemType === 'ship' ? 'SHIP' : selectedItemType === 'top' ? 'TOP' : 'HULL'
      const itemsToAdd: { id: number; type: 'SHIP' | 'TOP' | 'HULL' }[] = []
      selectedItems.forEach(id => itemsToAdd.push({ id, type: itemType }))
  

      // 벤더별 담당자 ID를 객체로 변환
      const contactsByVendor: Record<number, number[]> = {}
      Object.entries(selectedContacts).forEach(([vendorIdStr, contacts]) => {
        contactsByVendor[parseInt(vendorIdStr)] = Array.from(contacts)
      })

      const result = await addContactItemMapping({
        items: itemsToAdd,
        vendors: Array.from(selectedVendors),
        contactsByVendor,
      })

      if (result.error) {
        toast.error(result.error)
      } else {
        toast.success("담당자-아이템 매핑이 추가되었습니다.")
        setOpen(false)
        // 초기화
        resetForm()
      }
    } catch (err) {
      toast.error("매핑 추가 중 오류가 발생했습니다.")
    } finally {
      setIsSubmitting(false)
    }
  }

  const resetForm = () => {
    setSelectedItemType('ship')
    setItemSearch("")
    setSelectedItems(new Set())
    setVendorSearch("")
    setSelectedVendors(new Set())
    setSelectedContacts({})
    setExpandedVendors(new Set())
  }

  const getTotalSelectedContacts = () => {
    return Object.values(selectedContacts).reduce((sum, contacts) => sum + contacts.size, 0)
  }

  // 매핑 추가 버튼 활성화 조건
  const canSubmit = selectedItems.size > 0 && selectedVendors.size > 0 && getTotalSelectedContacts() > 0

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {trigger || (
          <Button variant="outline" size="sm">
            담당자-아이템 매핑 추가
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="max-w-6xl h-[90vh] flex flex-col overflow-hidden">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle>아이템별 협력업체별 담당자 설정</DialogTitle>
          <DialogDescription>
            아이템, 협력업체, 담당자를 선택하여 매핑을 추가합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="grid grid-cols-3 gap-4 flex-1 min-h-0 overflow-hidden">
          {/* Section 1: 아이템 선택 */}
          <div className="flex flex-col border rounded-lg p-3 min-h-0">
            <div className="space-y-2 flex-shrink-0">
              <Label className="text-sm font-semibold">
                1. 아이템 선택 ({selectedItems.size}개 선택)
              </Label>
              
              {/* 아이템 타입 필터 */}
              <RadioGroup value={selectedItemType} onValueChange={(value) => handleItemTypeChange(value as 'ship' | 'top' | 'hull')}>
                <div className="flex gap-3 text-sm">
                  <div className="flex items-center space-x-1">
                    <RadioGroupItem value="ship" id="type-ship" />
                    <Label htmlFor="type-ship" className="cursor-pointer font-normal">조선</Label>
                  </div>
                  <div className="flex items-center space-x-1">
                    <RadioGroupItem value="top" id="type-top" />
                    <Label htmlFor="type-top" className="cursor-pointer font-normal">해양 TOP</Label>
                  </div>
                  <div className="flex items-center space-x-1">
                    <RadioGroupItem value="hull" id="type-hull" />
                    <Label htmlFor="type-hull" className="cursor-pointer font-normal">해양 HULL</Label>
                  </div>
                </div>
              </RadioGroup>

              {/* 검색 */}
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="아이템코드, 이름, 공종, 선종 검색..."
                  className="pl-8 h-9 text-sm"
                  value={itemSearch}
                  onChange={(e) => setItemSearch(e.target.value)}
                />
              </div>
            </div>

            {/* 아이템 리스트 */}
            <ScrollArea className="flex-1 min-h-0 mt-2 -mx-3 px-3">
              {isLoadingItems ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="h-6 w-6 animate-spin" />
                </div>
              ) : (
                <div className="space-y-1">
                  {items.length > 0 && items.map(item => (
                    <div
                      key={item.id}
                      className="flex items-start space-x-2 p-2 rounded hover:bg-accent cursor-pointer text-sm"
                      onClick={() => handleItemSelect(item.id)}
                    >
                      {selectedItems.has(item.id) ? (
                        <CheckSquare className="h-4 w-4 text-primary flex-shrink-0 mt-0.5" />
                      ) : (
                        <Square className="h-4 w-4 flex-shrink-0 mt-0.5" />
                      )}
                      <div className="flex-1 min-w-0 overflow-hidden">
                        <div className="font-medium break-words">{item.itemCode}</div>
                        <div className="text-xs text-muted-foreground break-words">{item.itemList}</div>
                        <div className="text-xs text-muted-foreground break-words">
                          {item.workType}
                          {item.shipTypes && ` • ${item.shipTypes}`}
                          {item.subItemList && ` • ${item.subItemList}`}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </ScrollArea>
          </div>

          {/* Section 2: 벤더 선택 */}
          <div className="flex flex-col border rounded-lg p-3 min-h-0">
            <div className="space-y-2 flex-shrink-0">
              <Label className="text-sm font-semibold">
                2. 협력업체 선택 ({selectedVendors.size}개 선택)
              </Label>
              
              {/* 검색 */}
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="벤더코드, 벤더명, 이메일 검색..."
                  className="pl-8 h-9 text-sm"
                  value={vendorSearch}
                  onChange={(e) => setVendorSearch(e.target.value)}
                />
              </div>
            </div>

            {/* 벤더 리스트 */}
            <ScrollArea className="flex-1 min-h-0 mt-2 -mx-3 px-3">
              {isLoadingVendors ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="h-6 w-6 animate-spin" />
                </div>
              ) : (
                <div className="space-y-1">
                  {vendors.map(vendor => (
                    <div
                      key={vendor.id}
                      className="flex items-start space-x-2 p-2 rounded hover:bg-accent cursor-pointer text-sm"
                      onClick={() => handleVendorSelect(vendor.id)}
                    >
                      {selectedVendors.has(vendor.id) ? (
                        <CheckSquare className="h-4 w-4 text-primary flex-shrink-0 mt-0.5" />
                      ) : (
                        <Square className="h-4 w-4 flex-shrink-0 mt-0.5" />
                      )}
                      <div className="flex-1 min-w-0 overflow-hidden">
                        <div className="font-medium break-words">{vendor.vendorName}</div>
                        {vendor.vendorCode && (
                          <div className="text-xs text-muted-foreground break-words">{vendor.vendorCode}</div>
                        )}
                        <div className="text-xs text-muted-foreground break-words">
                          {vendor.techVendorType} • {vendor.status}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </ScrollArea>
          </div>

          {/* Section 3: 벤더별 담당자 선택 */}
          <div className="flex flex-col border rounded-lg p-3 min-h-0">
            <Label className="text-sm font-semibold flex-shrink-0">
              3. 담당자 선택 ({getTotalSelectedContacts()}명 선택)
            </Label>

            <ScrollArea className="flex-1 min-h-0 mt-2 -mx-3 px-3">
              {isLoadingContacts ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="h-6 w-6 animate-spin" />
                </div>
              ) : selectedVendors.size === 0 ? (
                <div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
                  협력업체를 먼저 선택해주세요
                </div>
              ) : (
                <div className="space-y-1">
                  {Array.from(selectedVendors).map(vendorId => {
                    const contacts = vendorContacts[vendorId] || []
                    const vendor = vendors.find(v => v.id === vendorId)
                    const isExpanded = expandedVendors.has(vendorId)

                    return (
                      <div key={vendorId} className="border rounded">
                        {/* 벤더 헤더 */}
                        <div
                          className="flex items-center space-x-2 p-2 cursor-pointer hover:bg-accent"
                          onClick={() => toggleVendorExpand(vendorId)}
                        >
                          {isExpanded ? (
                            <ChevronDown className="h-4 w-4 flex-shrink-0" />
                          ) : (
                            <ChevronRight className="h-4 w-4 flex-shrink-0" />
                          )}
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-medium truncate">{vendor?.vendorName}</div>
                            <div className="text-xs text-muted-foreground">
                              담당자 {contacts.length}명 • {selectedContacts[vendorId]?.size || 0}명 선택
                            </div>
                          </div>
                        </div>

                        {/* 담당자 리스트 */}
                        {isExpanded && (
                          <div className="border-t bg-muted/30">
                            {contacts.length === 0 ? (
                              <div className="p-2 text-xs text-muted-foreground text-center">
                                등록된 담당자가 없습니다
                              </div>
                            ) : (
                              contacts.map(contact => (
                                <div
                                  key={contact.id}
                                  className="flex items-start space-x-2 p-2 hover:bg-accent cursor-pointer text-sm"
                                  onClick={() => handleContactSelect(vendorId, contact.id)}
                                >
                                  {selectedContacts[vendorId]?.has(contact.id) ? (
                                    <CheckSquare className="h-4 w-4 text-primary flex-shrink-0 mt-0.5" />
                                  ) : (
                                    <Square className="h-4 w-4 flex-shrink-0 mt-0.5" />
                                  )}
                                  <div className="flex-1 min-w-0">
                                    <div className="font-medium truncate">
                                      {contact.contactName}
                                      {contact.isPrimary && (
                                        <span className="ml-1 text-xs text-primary">(주담당)</span>
                                      )}
                                    </div>
                                    <div className="text-xs text-muted-foreground truncate">
                                      {contact.contactPosition}
                                    </div>
                                    <div className="text-xs text-muted-foreground truncate">
                                      {contact.contactEmail}
                                    </div>
                                  </div>
                                </div>
                              ))
                            )}
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>
              )}
            </ScrollArea>
          </div>
        </div>

        <DialogFooter className="flex-shrink-0 mt-4">
          <Button variant="outline" onClick={() => setOpen(false)} disabled={isSubmitting}>
            취소
          </Button>
          <Button 
            onClick={handleSubmit} 
            disabled={!canSubmit || isSubmitting}
          >
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                추가 중...
              </>
            ) : (
              "매핑 추가"
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}