summaryrefslogtreecommitdiff
path: root/lib/dolce/dialogs/detail-drawing-dialog.tsx
blob: d9df58db20fa80f6c5ea6ea1164a44847f33090c (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
"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Plus, RefreshCw, Upload, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "@/i18n/client";
import {
  UnifiedDwgReceiptItem,
  DetailDwgReceiptItem,
  FileInfoItem,
  fetchDetailDwgReceiptList,
  fetchFileInfoList,
} from "../actions";
import { DrawingListTable } from "../table/drawing-list-table";
import { createDetailDrawingColumns } from "../table/detail-drawing-columns";
import { createFileListColumns } from "../table/file-list-columns";
import { AddDetailDrawingDialog } from "./add-detail-drawing-dialog";
import { UploadFilesToDetailDialog } from "./upload-files-to-detail-dialog";

interface DetailDrawingDialogProps {
  drawing: UnifiedDwgReceiptItem | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  vendorCode: string;
  userId: string;
  userName: string;
  userEmail: string;
  drawingKind: "B3" | "B4";
  lng: string;
}

export function DetailDrawingDialog({
  drawing,
  open,
  onOpenChange,
  vendorCode,
  userId,
  userName,
  userEmail,
  drawingKind,
  lng,
}: DetailDrawingDialogProps) {
  const { t } = useTranslation(lng, "dolce");
  const [detailDrawings, setDetailDrawings] = useState<DetailDwgReceiptItem[]>([]);
  const [selectedDetail, setSelectedDetail] = useState<DetailDwgReceiptItem | null>(null);
  const [files, setFiles] = useState<FileInfoItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingFiles, setIsLoadingFiles] = useState(false);
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [uploadFilesDialogOpen, setUploadFilesDialogOpen] = useState(false);

  // 상세도면 목록 로드
  const loadDetailDrawings = useCallback(async () => {
    if (!drawing) return;

    try {
      setIsLoading(true);
      const data = await fetchDetailDwgReceiptList({
        project: drawing.ProjectNo,
        drawingNo: drawing.DrawingNo,
        discipline: drawing.Discipline,
        drawingKind: drawing.DrawingKind,
        userId: "", // 조회 시 모든 사용자의 상세도면을 보기 위해 빈 문자열 전달
      });
      setDetailDrawings(data);
      
      // 첫 번째 상세도면 자동 선택
      if (data.length > 0 && !selectedDetail) {
        setSelectedDetail(data[0]);
      }
    } catch (error) {
      console.error("상세도면 로드 실패:", error);
      toast.error(t("detailDialog.detailLoadError"));
    } finally {
      setIsLoading(false);
    }
  }, [drawing, selectedDetail, t]);

  // 파일 목록 로드
  const loadFiles = useCallback(async () => {
    if (!selectedDetail) {
      setFiles([]);
      return;
    }

    try {
      setIsLoadingFiles(true);
      const data = await fetchFileInfoList(selectedDetail.UploadId);
      setFiles(data);
    } catch (error) {
      console.error("파일 목록 로드 실패:", error);
      toast.error(t("detailDialog.fileLoadError"));
    } finally {
      setIsLoadingFiles(false);
    }
  }, [selectedDetail, t]);

  // 다이얼로그 열릴 때 데이터 로드
  useEffect(() => {
    if (open && drawing) {
      loadDetailDrawings();
    } else {
      setDetailDrawings([]);
      setSelectedDetail(null);
      setFiles([]);
    }
  }, [open, drawing, loadDetailDrawings]);

  // 선택된 상세도면 변경 시 파일 목록 로드
  useEffect(() => {
    if (selectedDetail) {
      loadFiles();
    }
  }, [selectedDetail, loadFiles]);

  const handleDownload = async (file: FileInfoItem) => {
    try {
      toast.info(t("detailDialog.downloadPreparing"));
      
      // 파일 생성자의 userId를 사용하여 다운로드
      const response = await fetch("/api/dolce/download", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          fileId: file.FileId,
          userId: file.CreateUserId, // 파일 생성자의 ID 사용
          fileName: file.FileName,
        }),
      });

      if (!response.ok) {
        throw new Error(t("detailDialog.downloadError"));
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = file.FileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      toast.success(t("detailDialog.downloadSuccess"));
    } catch (error) {
      console.error("파일 다운로드 실패:", error);
      toast.error(t("detailDialog.downloadError"));
    }
  };

  const handleRefresh = () => {
    loadDetailDrawings();
  };

  const handleAddComplete = () => {
    setAddDialogOpen(false);
    loadDetailDrawings();
  };

  const handleUploadComplete = () => {
    setUploadFilesDialogOpen(false);
    loadFiles();
  };

  const fileColumns = createFileListColumns({ onDownload: handleDownload, lng });

  // RegisterId + UploadId 조합으로 고유 ID 생성
  const getDetailDrawingId = (detail: DetailDwgReceiptItem) => {
    return `${detail.RegisterId}_${detail.UploadId}`;
  };

  // B4인 경우 "도면입수"인 건만 상세도면 추가 및 파일 첨부 가능
  // B3인 경우 모든 건에 대해 가능
  const canAddDetailDrawing = drawingKind === "B3" || 
    (drawingKind === "B4" && drawing && 'DrawingMoveGbn' in drawing && drawing.DrawingMoveGbn === "도면입수");

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-[95vw] h-[90vh] flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex flex-col gap-1">
              <span>{t("detailDialog.title")}</span>
              {drawing && (
                <span className="text-sm font-normal text-muted-foreground">
                  {t("detailDialog.subtitle", {
                    drawingNo: drawing.DrawingNo,
                    projectNo: drawing.ProjectNo,
                    discipline: drawing.Discipline,
                    drawingKind: drawing.DrawingKind
                  })}
                </span>
              )}
            </DialogTitle>
          </DialogHeader>

          <div className="flex-1 overflow-hidden flex flex-col gap-4">
            {/* 상단: 상세도면 리스트 */}
            <Card className="flex-1 overflow-hidden flex flex-col">
              <CardHeader className="flex-row items-center justify-between py-3">
                <CardTitle className="text-base">{t("detailDialog.detailListTitle")}</CardTitle>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleRefresh}
                    disabled={isLoading}
                  >
                    <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
                    {t("detailDialog.refreshButton")}
                  </Button>
                  {canAddDetailDrawing && (
                    <Button
                      variant="default"
                      size="sm"
                      onClick={() => setAddDialogOpen(true)}
                    >
                      <Plus className="h-4 w-4 mr-2" />
                      {t("detailDialog.addDetailButton")}
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent className="flex-1 overflow-y-auto p-4">
                <DrawingListTable<DetailDwgReceiptItem, unknown>
                  columns={createDetailDrawingColumns(lng, t)}
                  data={detailDrawings}
                  onRowClick={setSelectedDetail}
                  selectedRow={selectedDetail || undefined}
                  getRowId={(row) => getDetailDrawingId(row)}
                />
              </CardContent>
            </Card>

            {/* 하단: 첨부파일 리스트 */}
            <Card className="flex-1 overflow-hidden flex flex-col">
              <CardHeader className="flex-row items-center justify-between py-3">
                <CardTitle className="text-base">
                  {t("detailDialog.fileListTitle")}
                  {selectedDetail && t("detailDialog.fileListSubtitle", { revNo: selectedDetail.DrawingRevNo })}
                </CardTitle>
                {selectedDetail && canAddDetailDrawing && (
                  <Button
                    variant="default"
                    size="sm"
                    onClick={() => setUploadFilesDialogOpen(true)}
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    {t("detailDialog.uploadFilesButton")}
                  </Button>
                )}
              </CardHeader>
              <CardContent className="flex-1 overflow-y-auto p-4">
                {!selectedDetail ? (
                  <div className="h-full flex items-center justify-center text-muted-foreground">
                    {t("detailDialog.selectDetailDrawing")}
                  </div>
                ) : isLoadingFiles ? (
                  <div className="space-y-4">
                    <div className="flex items-center justify-center gap-2 text-muted-foreground py-8">
                      <Loader2 className="h-5 w-5 animate-spin" />
                      <span>{t("detailDialog.loadingFiles")}</span>
                    </div>
                    <div className="space-y-2">
                      <Skeleton className="h-10 w-full" />
                      <Skeleton className="h-10 w-full" />
                      <Skeleton className="h-10 w-full" />
                    </div>
                  </div>
                ) : (
                  <DrawingListTable
                    columns={fileColumns}
                    data={files}
                  />
                )}
              </CardContent>
            </Card>
          </div>
        </DialogContent>
      </Dialog>

      <AddDetailDrawingDialog
        open={addDialogOpen}
        onOpenChange={setAddDialogOpen}
        drawing={drawing}
        vendorCode={vendorCode}
        userId={userId}
        userName={userName}
        userEmail={userEmail}
        onComplete={handleAddComplete}
        drawingKind={drawingKind}
        lng={lng}
      />

      {selectedDetail && (
        <UploadFilesToDetailDialog
          open={uploadFilesDialogOpen}
          onOpenChange={setUploadFilesDialogOpen}
          uploadId={selectedDetail.UploadId}
          drawingNo={selectedDetail.DrawingNo}
          revNo={selectedDetail.DrawingRevNo}
          userId={userId}
          onUploadComplete={handleUploadComplete}
          lng={lng}
        />
      )}
    </>
  );
}