summaryrefslogtreecommitdiff
path: root/lib/techsales-rfq/table/detail-table/quotation-history-dialog.tsx
blob: 7d972b918464d4d3025abc648f299493031cad7f (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
"use client"
import * as React from "react"
import { useState, useEffect } from "react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Separator } from "@/components/ui/separator"
import { Skeleton } from "@/components/ui/skeleton"
import { Clock, User, AlertCircle, Paperclip } from "lucide-react"
import { formatDate } from "@/lib/utils"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import { updateSHIComment } from "@/lib/techsales-rfq/service";

interface QuotationAttachment {
  id: number
  quotationId: number
  revisionId: number
  fileName: string
  originalFileName: string
  fileSize: number
  fileType: string | null
  filePath: string
  description: string | null
  isVendorUpload: boolean
  createdAt: Date
  updatedAt: Date
}

interface QuotationSnapshot {
  currency: string | null
  totalPrice: string | null
  validUntil: Date | null
  remark: string | null
  status: string
  quotationVersion: number | null
  submittedAt: Date | null
  acceptedAt: Date | null
  updatedAt: Date | null
}

interface QuotationRevision {
  id: number
  version: number
  snapshot: QuotationSnapshot
  changeReason: string | null
  revisionNote: string | null
  revisedBy: number | null
  revisedAt: Date
  revisedByName: string | null
  attachments: QuotationAttachment[]
}

interface QuotationHistoryData {
  current: {
    id: number
    currency: string | null
    totalPrice: string | null
    validUntil: Date | null
    remark: string | null
    status: string
    quotationVersion: number | null
    submittedAt: Date | null
    acceptedAt: Date | null
    updatedAt: Date | null
    attachments: QuotationAttachment[]
  }
  revisions: QuotationRevision[]
}

interface QuotationHistoryDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  quotationId: number | null
}

const statusConfig = {
  "Draft": { label: "초안", color: "bg-yellow-100 text-yellow-800" },
  "Submitted": { label: "제출됨", color: "bg-blue-100 text-blue-800" },
  "Revised": { label: "수정됨", color: "bg-purple-100 text-purple-800" },
  "Accepted": { label: "승인됨", color: "bg-green-100 text-green-800" },
  "Rejected": { label: "거절됨", color: "bg-red-100 text-red-800" },
}

function QuotationCard({ 
  data, 
  version, 
  isCurrent = false, 
  revisedBy, 
  revisedAt,
  attachments,
  revisionId,
  revisionNote,
}: {
  data: QuotationSnapshot | QuotationHistoryData["current"]
  version: number
  isCurrent?: boolean
  revisedBy?: string | null
  revisedAt?: Date
  attachments?: QuotationAttachment[]
  revisionId?: number
  revisionNote?: string | null
}) {
  const statusInfo = statusConfig[data.status as keyof typeof statusConfig] || 
    { label: data.status || "알 수 없음", color: "bg-gray-100 text-gray-800" }
  
  const [editValue, setEditValue] = React.useState(revisionNote || "");
  const [isSaving, setIsSaving] = React.useState(false);
  
  React.useEffect(() => {
    setEditValue(revisionNote || "");
  }, [revisionNote]);
  
  const handleSave = async () => {
    if (!revisionId) return;
    
    setIsSaving(true);
    try {
      const result = await updateSHIComment(revisionId, editValue);
      if (result.error) {
        toast.error(result.error);
      } else {
        toast.success("저장 완료");
      }
    } catch (error) {
      toast.error("저장 중 오류가 발생했습니다");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <Card className={`${isCurrent ? "border-blue-500 shadow-md" : "border-gray-200"}`}>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg flex items-center gap-2">
            <span>버전 {version}</span>
            {isCurrent && <Badge variant="default">현재</Badge>}
          </CardTitle>
          <Badge className={statusInfo.color}>
            {statusInfo.label}
          </Badge>
        </div>
      </CardHeader>
      <CardContent className="space-y-3">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <p className="text-sm font-medium text-muted-foreground">견적 금액</p>
            <p className="text-lg font-semibold">
              {data.totalPrice ? `${data.currency} ${Number(data.totalPrice).toLocaleString()}` : "미입력"}
            </p>
          </div>
          <div>
            <p className="text-sm font-medium text-muted-foreground">유효 기한</p>
            <p className="text-sm">
              {data.validUntil ? formatDate(data.validUntil) : "미설정"}
            </p>
          </div>
        </div>
        
        {data.remark && (
          <div>
            <p className="text-sm font-medium text-muted-foreground">비고</p>
            <p className="text-sm bg-gray-50 p-2 rounded">{data.remark}</p>
          </div>
        )}
        
        {revisionId && (
  <div>
    <p className="text-sm font-medium text-muted-foreground mt-2">SHI Comment</p>
    <textarea
      className="w-full min-h-[60px] p-2 border rounded bg-gray-50 text-sm"
      value={editValue}
      onChange={e => setEditValue(e.target.value)}
      disabled={isSaving}
    />
    <Button size="sm" onClick={handleSave} disabled={isSaving} className="mt-2">
      저장
    </Button>
  </div>
)}
        
        {/* 첨부파일 섹션 */}
        {attachments && attachments.length > 0 && (
          <div>
            <p className="text-sm font-medium text-muted-foreground mb-2 flex items-center gap-1">
              <Paperclip className="size-3" />
              첨부파일 ({attachments.length}개)
            </p>
            <div className="space-y-1">
              {attachments.map((attachment) => (
                <div key={attachment.id} className="flex items-center justify-between p-2 bg-gray-50 rounded text-xs">
                  <div className="flex items-center gap-2 min-w-0 flex-1">
                    <div className="min-w-0 flex-1">
                      <p className="font-medium truncate" title={attachment.originalFileName}>
                        {attachment.originalFileName}
                      </p>
                      {attachment.description && (
                        <p className="text-muted-foreground truncate" title={attachment.description}>
                          {attachment.description}
                        </p>
                      )}
                    </div>
                  </div>
                  <div className="text-muted-foreground whitespace-nowrap ml-2">
                    {(attachment.fileSize / 1024 / 1024).toFixed(2)} MB
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
        
        <Separator />
        
        <div className="flex items-center justify-between text-xs text-muted-foreground">
          <div className="flex items-center gap-1">
            <Clock className="size-3" />
            <span>
              {isCurrent 
                ? `수정: ${data.updatedAt ? formatDate(data.updatedAt) : "N/A"}` 
                : `변경: ${revisedAt ? formatDate(revisedAt) : "N/A"}`
              }
            </span>
          </div>
          {revisedBy && (
            <div className="flex items-center gap-1">
              <User className="size-3" />
              <span>{revisedBy}</span>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  )
}

export function QuotationHistoryDialog({ 
  open, 
  onOpenChange, 
  quotationId 
}: QuotationHistoryDialogProps) {
  const [data, setData] = useState<QuotationHistoryData | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  
  useEffect(() => {
    if (open && quotationId) {
      loadQuotationHistory()
    }
  }, [open, quotationId])
  
  const loadQuotationHistory = async () => {
    if (!quotationId) return
    try {
      setIsLoading(true)
      const { getTechSalesVendorQuotationWithRevisions } = await import("@/lib/techsales-rfq/service")
      
      const result = await getTechSalesVendorQuotationWithRevisions(quotationId)
      
      if (result.error) {
        toast.error(result.error)
        return
      }
      
      setData(result.data as QuotationHistoryData)
    } catch (error) {
      console.error("견적 히스토리 로드 오류:", error)
      toast.error("견적 히스토리를 불러오는 중 오류가 발생했습니다")
    } finally {
      setIsLoading(false)
    }
  }
  
  const handleOpenChange = (newOpen: boolean) => {
    onOpenChange(newOpen)
    if (!newOpen) {
      setData(null) // 다이얼로그 닫을 때 데이터 초기화
    }
  }
  
  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="w-[80vw] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>견적서 수정 히스토리</DialogTitle>
          <DialogDescription>
            견적서의 변경 이력을 확인할 수 있습니다. 최신 버전부터 순서대로 표시됩니다.
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-4 overflow-x-auto">
        {isLoading ? (
          <div className="space-y-4">
            {[1, 2, 3].map((i) => (
              <div key={i} className="space-y-3">
                <Skeleton className="h-6 w-32" />
                <Skeleton className="h-32 w-full" />
              </div>
            ))}
          </div>
        ) : data ? (
          <>
            {/* 현재 버전 - SHI Comment 없이 표시 */}
            <QuotationCard
              data={data.current}
              version={data.current.quotationVersion || 1}
              isCurrent={true}
              attachments={data.current.attachments}
            />
            
            {/* 이전 버전들 (스냅샷) - SHI Comment 포함 */}
            {data.revisions.length > 0 ? (
              data.revisions.map((revision) => (
                <QuotationCard
                  key={revision.id}
                  data={revision.snapshot}
                  version={revision.version}
                  revisedBy={revision.revisedByName}
                  revisedAt={revision.revisedAt}
                  attachments={revision.attachments}
                  revisionId={revision.id}
                  revisionNote={revision.revisionNote}
                />
              ))
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                <AlertCircle className="size-12 mx-auto mb-2 opacity-50" />
                <p>수정 이력이 없습니다.</p>
                <p className="text-sm">이 견적서는 아직 수정되지 않았습니다.</p>
              </div>
            )}
          </>
        ) : (
          <div className="text-center py-8 text-muted-foreground">
            <AlertCircle className="size-12 mx-auto mb-2 opacity-50" />
            <p>견적서 정보를 불러올 수 없습니다.</p>
          </div>
        )}
      </div>
      </DialogContent>
    </Dialog>
  )
}