summaryrefslogtreecommitdiff
path: root/lib/swp/table/swp-inbox-document-detail-dialog.tsx
blob: 7f8142671a891b5c993df11ff32363ae0703e741 (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
"use client";

import React, { useState, useMemo } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { 
  ChevronDown, 
  ChevronRight, 
  Download, 
  FileIcon,
  XCircle,
  AlertCircle,
} from "lucide-react";
import { 
  cancelVendorFile,
  downloadVendorFile,
} from "@/lib/swp/vendor-actions";
import type { SwpFileApiResponse } from "@/lib/swp/api-client";
import type { InboxDocumentItem } from "./swp-inbox-table";
import { toast } from "sonner";

interface SwpInboxDocumentDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  document: InboxDocumentItem | null;
  projNo: string;
  vendorCode: string;
  userId: string;
}

// Group type by revision
interface RevisionGroup {
  revNo: string;
  stage: string;
  activities: ActivityGroup[];
  totalFiles: number;
}

// Group type by Activity (activity can be null)
interface ActivityGroup {
  actvNo: string | null;
  files: SwpFileApiResponse[];
}

export function SwpInboxDocumentDetailDialog({
  open,
  onOpenChange,
  document,
  projNo,
}: SwpInboxDocumentDetailDialogProps) {
  const [expandedRevisions, setExpandedRevisions] = useState<Set<string>>(new Set());
  const [expandedActivities, setExpandedActivities] = useState<Set<string>>(new Set());
  const [isAllExpanded, setIsAllExpanded] = useState(true);

  // Group files into Revision > Activity structure
  const revisionGroups = useMemo(() => {
    if (!document) return [];

    const revMap = new Map<string, SwpFileApiResponse[]>();

    document.files.forEach((file) => {
      const revKey = `${file.REV_NO}|${file.STAGE}`;
      if (!revMap.has(revKey)) {
        revMap.set(revKey, []);
      }
      revMap.get(revKey)!.push(file);
    });

    const result: RevisionGroup[] = [];

    revMap.forEach((revFiles, revKey) => {
      const [revNo, stage] = revKey.split("|");

      // Group by Activity (nullable)
      const actMap = new Map<string | null, SwpFileApiResponse[]>();
      
      revFiles.forEach((file) => {
        const actvNo = file.ACTV_NO || null;
        if (!actMap.has(actvNo)) {
          actMap.set(actvNo, []);
        }
        actMap.get(actvNo)!.push(file);
      });

      const activities: ActivityGroup[] = [];
      actMap.forEach((files, actvNo) => {
        activities.push({ actvNo, files });
      });

      // Sort: No Activity first, then with Activity
      activities.sort((a, b) => {
        if (a.actvNo === null && b.actvNo !== null) return -1;
        if (a.actvNo !== null && b.actvNo === null) return 1;
        if (a.actvNo === null && b.actvNo === null) return 0;
        return (a.actvNo || "").localeCompare(b.actvNo || "");
      });

      result.push({
        revNo,
        stage,
        activities,
        totalFiles: revFiles.length,
      });
    });

    // Sort by revision number (newest first)
    return result.sort((a, b) => b.revNo.localeCompare(a.revNo));
  }, [document]);

  // Expand all when dialog opens
  React.useEffect(() => {
    if (open && revisionGroups.length > 0) {
      const allRevKeys = new Set<string>();
      const allActKeys = new Set<string>();
      
      revisionGroups.forEach((revision) => {
        const revKey = revision.revNo;
        allRevKeys.add(revKey);
        
        revision.activities.forEach((activity) => {
          const actKey = `${revKey}|${activity.actvNo || "NO_ACTIVITY"}`;
          allActKeys.add(actKey);
        });
      });
      
      setExpandedRevisions(allRevKeys);
      setExpandedActivities(allActKeys);
      setIsAllExpanded(true);
    }
  }, [open, revisionGroups]);

  const toggleRevision = (revKey: string) => {
    setExpandedRevisions((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(revKey)) {
        newSet.delete(revKey);
      } else {
        newSet.add(revKey);
      }
      return newSet;
    });
  };

  const toggleActivity = (actKey: string) => {
    setExpandedActivities((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(actKey)) {
        newSet.delete(actKey);
      } else {
        newSet.add(actKey);
      }
      return newSet;
    });
  };

  // Toggle all
  const handleToggleAll = () => {
    if (isAllExpanded) {
      // Collapse all
      setExpandedRevisions(new Set());
      setExpandedActivities(new Set());
      setIsAllExpanded(false);
    } else {
      // Expand all
      const allRevKeys = new Set<string>();
      const allActKeys = new Set<string>();
      
      revisionGroups.forEach((revision) => {
        const revKey = revision.revNo;
        allRevKeys.add(revKey);
        
        revision.activities.forEach((activity) => {
          const actKey = `${revKey}|${activity.actvNo || "NO_ACTIVITY"}`;
          allActKeys.add(actKey);
        });
      });
      
      setExpandedRevisions(allRevKeys);
      setExpandedActivities(allActKeys);
      setIsAllExpanded(true);
    }
  };

  const handleCancelFile = async (boxSeq: string, actvSeq: string, fileName: string) => {
    try {
      await cancelVendorFile(boxSeq, actvSeq);
      toast.success(`File cancelled: ${fileName}`);
      
      // Close dialog and trigger parent refresh
      onOpenChange(false);
    } catch (error) {
      console.error("Failed to cancel file:", error);
      toast.error("Failed to cancel file");
    }
  };

  const handleDownloadFile = async (fileName: string, ownDocNo: string) => {
    try {
      toast.info("Downloading file...");
      const result = await downloadVendorFile(projNo, ownDocNo, fileName);
      
      if (!result.success || !result.data) {
        toast.error(result.error || "File download failed");
        return;
      }

      // Create Blob and download
      const blob = new Blob([Buffer.from(result.data)], { type: result.mimeType });
      const url = URL.createObjectURL(blob);
      const link = window.document.createElement("a");
      link.href = url;
      link.download = result.fileName || fileName;
      window.document.body.appendChild(link);
      link.click();
      window.document.body.removeChild(link);
      URL.revokeObjectURL(url);

      toast.success(`File downloaded: ${fileName}`);
    } catch (error) {
      console.error("File download failed:", error);
      toast.error("Failed to download file");
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Uploaded File Details</DialogTitle>
          {document && (
            <DialogDescription>
              {document.ownDocNo}
            </DialogDescription>
          )}
        </DialogHeader>

        {document && (
          <div className="space-y-4">
            {/* Document Info */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 p-4 bg-muted/30 rounded-lg">
              <div>
                <span className="text-sm font-semibold">OWN_DOC_NO:</span>
                <div className="text-sm font-mono">{document.ownDocNo}</div>
              </div>
              <div>
                <span className="text-sm font-semibold">Latest Stage:</span>
                <div className="text-sm">{document.latestStage || "-"}</div>
              </div>
              <div>
                <span className="text-sm font-semibold">Latest Revision:</span>
                <div className="text-sm">{document.latestRevNo || "-"}</div>
              </div>
              <div>
                <span className="text-sm font-semibold">Latest REV Files:</span>
                <div className="text-sm">{document.latestRevFileCount}</div>
              </div>
            </div>

            {/* Revision and Activity Tree */}
            {revisionGroups.length > 0 ? (
              <div className="space-y-2">
                {/* Toggle All Button */}
                <div className="flex justify-end">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleToggleAll}
                  >
                    {isAllExpanded ? (
                      <>
                        <ChevronDown className="h-4 w-4 mr-2" />
                        Collapse All
                      </>
                    ) : (
                      <>
                        <ChevronRight className="h-4 w-4 mr-2" />
                        Expand All
                      </>
                    )}
                  </Button>
                </div>
                {revisionGroups.map((revision) => {
                  const revKey = revision.revNo;
                  const isRevExpanded = expandedRevisions.has(revKey);

                  return (
                    <div key={revKey} className="border rounded-lg">
                      {/* Revision Header */}
                      <div
                        className="flex items-center justify-between p-3 bg-muted/50 cursor-pointer hover:bg-muted"
                        onClick={() => toggleRevision(revKey)}
                      >
                        <div className="flex items-center gap-3">
                          {isRevExpanded ? (
                            <ChevronDown className="h-4 w-4" />
                          ) : (
                            <ChevronRight className="h-4 w-4" />
                          )}
                          <Badge variant="secondary" className="font-mono">
                            REV {revision.revNo}
                          </Badge>
                          <Badge variant="outline" className={
                            revision.stage === "IFC" ? "bg-green-100 text-green-800" :
                            revision.stage === "IFA" ? "bg-blue-100 text-blue-800" :
                            "bg-gray-100 text-gray-800"
                          }>
                            {revision.stage}
                          </Badge>
                          <span className="text-sm text-muted-foreground">
                            {revision.activities.length} Groups / {revision.totalFiles} Files
                          </span>
                        </div>
                      </div>

                      {/* Activity List (or files without Activity) */}
                      {isRevExpanded && (
                        <div className="p-2 space-y-2">
                          {revision.activities.map((activity) => {
                            const actKey = `${revKey}|${activity.actvNo || "NO_ACTIVITY"}`;
                            const isActExpanded = expandedActivities.has(actKey);

                            return (
                              <div key={actKey} className="border rounded-md">
                                {/* Activity Header */}
                                <div
                                  className="flex items-center justify-between p-2 bg-muted/30 cursor-pointer hover:bg-muted/50"
                                  onClick={() => toggleActivity(actKey)}
                                >
                                  <div className="flex items-center gap-2">
                                    {isActExpanded ? (
                                      <ChevronDown className="h-4 w-4" />
                                    ) : (
                                      <ChevronRight className="h-4 w-4" />
                                    )}
                                    {activity.actvNo ? (
                                      <>
                                        <Badge variant="outline" className="bg-blue-100 text-blue-800">
                                          Activity
                                        </Badge>
                                        <span className="text-xs text-muted-foreground font-mono">
                                          {activity.actvNo}
                                        </span>
                                      </>
                                    ) : (
                                      <Badge variant="outline" className="bg-gray-100 text-gray-800">
                                        No Activity
                                      </Badge>
                                    )}
                                    <span className="text-xs text-muted-foreground">
                                      {activity.files.length} Files
                                    </span>
                                  </div>
                                </div>

                                {/* File List */}
                                {isActExpanded && (
                                  <div className="p-2 space-y-1">
                                    {activity.files.map((file, idx) => (
                                      <div
                                        key={idx}
                                        className="flex items-center justify-between p-2 border rounded bg-background hover:bg-muted/30"
                                      >
                                        <div className="flex items-center gap-2 flex-1">
                                          <FileIcon className="h-4 w-4 text-blue-500" />
                                          <span className="text-sm font-mono">{file.FILE_NM}</span>
                                          {file.FILE_SZ && (
                                            <span className="text-xs text-muted-foreground">
                                              ({formatFileSize(file.FILE_SZ)})
                                            </span>
                                          )}
                                          {file.STAT && (
                                            <Badge variant="outline" className={
                                              file.STAT === "SCW03" || file.STAT === "SCW08" ? "bg-green-100 text-green-800" :      // Complete, Checked
                                              file.STAT === "SCW02" ? "bg-blue-100 text-blue-800" :                                 // Processing
                                              file.STAT === "SCW01" ? "bg-yellow-100 text-yellow-800" :                             // Standby
                                              file.STAT === "SCW04" || file.STAT === "SCW05" || file.STAT === "SCW06" ? "bg-red-100 text-red-800" : // Reject, Error Zip, Error Meta
                                              file.STAT === "SCW07" ? "bg-purple-100 text-purple-800" :                             // Send for Eng Verification
                                              file.STAT === "SCW09" ? "bg-gray-100 text-gray-800" :                                 // Cancelled
                                              file.STAT === "SCW00" ? "bg-orange-100 text-orange-800" :                             // Upload
                                              "bg-gray-100 text-gray-800"
                                            }>
                                              {file.STAT_NM || file.STAT}
                                            </Badge>
                                          )}
                                        </div>
                                        <div className="flex items-center gap-1">
                                          {file.STAT === "SCW01" && file.BOX_SEQ && file.ACTV_SEQ && (
                                            <Button
                                              variant="outline"
                                              size="sm"
                                              onClick={() => handleCancelFile(file.BOX_SEQ!, file.ACTV_SEQ!, file.FILE_NM)}
                                            >
                                              <XCircle className="h-4 w-4 mr-1" />
                                              Cancel
                                            </Button>
                                          )}
                                          {file.FLD_PATH && (
                                            <Button
                                              variant="outline"
                                              size="sm"
                                              onClick={() => handleDownloadFile(file.FILE_NM, document.ownDocNo)}
                                            >
                                              <Download className="h-4 w-4 mr-1" />
                                              Download
                                            </Button>
                                          )}
                                        </div>
                                      </div>
                                    ))}
                                  </div>
                                )}
                              </div>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="p-8 text-center text-muted-foreground">
                <AlertCircle className="h-12 w-12 mx-auto mb-2 opacity-50" />
                <p>No file information available</p>
              </div>
            )}
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}

function formatFileSize(sizeStr: string): string {
  const bytes = parseInt(sizeStr, 10);
  if (isNaN(bytes)) return sizeStr;

  const kb = bytes / 1024;
  const mb = kb / 1024;

  return mb >= 1 ? `${mb.toFixed(2)} MB` : `${kb.toFixed(2)} KB`;
}