summaryrefslogtreecommitdiff
path: root/components/form-data/sedp-compare-dialog.tsx
blob: 37fe18edc4420b17e9518effb585fd0add263985 (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
import * as React from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Loader, RefreshCw, AlertCircle, CheckCircle, Info, EyeOff } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { DataTableColumnJSON } from "./form-data-table-columns";
import { ExcelDownload } from "./sedp-excel-download";
import { Switch } from "../ui/switch";

interface SEDPCompareDialogProps {
  isOpen: boolean;
  onClose: () => void;
  tableData: any[];
  columnsJSON: DataTableColumnJSON[];
  projectCode: string;
  formCode: string;
  fetchTagDataFromSEDP: (projectCode: string, formCode: string) => Promise<any>;
}

interface ComparisonResult {
  tagNo: string;
  tagDesc: string;
  isMatching: boolean;
  attributes: {
    key: string;
    label: string;
    localValue: any;
    sedpValue: any;
    isMatching: boolean;
    uom?: string;
  }[];
}

// Component for formatting display value with UOM
const DisplayValue = ({ value, uom, isSedp = false }: { value: any; uom?: string; isSedp?: boolean }) => {
  if (value === "" || value === null || value === undefined) {
    return <span>(empty)</span>;
  }

  // SEDP 값은 UOM을 표시하지 않음 (이미 포함되어 있다고 가정)
  if (isSedp) {
    return <span>{value}</span>;
  }

  // 로컬 값은 UOM과 함께 표시
  return (
    <span>
      {value}
      {uom && <span className="text-xs text-muted-foreground ml-1">{uom}</span>}
    </span>
  );
};

// 범례 컴포넌트 추가
const ColorLegend = () => {
  return (
    <div className="flex items-center gap-4 text-sm p-2 bg-muted/20 rounded">
      <div className="flex items-center gap-1.5">
        <Info className="h-4 w-4 text-muted-foreground" />
        <span className="font-medium">범례:</span>
      </div>
      <div className="flex items-center gap-3">
        <div className="flex items-center gap-1.5">
          <div className="h-3 w-3 rounded-full bg-red-500"></div>
          <span className="line-through text-red-500">로컬 값</span>
        </div>
        <div className="flex items-center gap-1.5">
          <div className="h-3 w-3 rounded-full bg-green-500"></div>
          <span className="text-green-500">SEDP 값</span>
        </div>
      </div>
    </div>
  );
};

export function SEDPCompareDialog({
  isOpen,
  onClose,
  tableData,
  columnsJSON,
  projectCode,
  formCode,
  fetchTagDataFromSEDP,
}: SEDPCompareDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false);
  const [comparisonResults, setComparisonResults] = React.useState<ComparisonResult[]>([]);
  const [activeTab, setActiveTab] = React.useState("all");
  const [isExporting, setIsExporting] = React.useState(false);
  const [missingTags, setMissingTags] = React.useState<{
    localOnly: { tagNo: string; tagDesc: string }[];
    sedpOnly: { tagNo: string; tagDesc: string }[];
  }>(
    { localOnly: [], sedpOnly: [] }
  );
  // 추가: 차이점만 표시하는 옵션
  const [showOnlyDifferences, setShowOnlyDifferences] = React.useState(true);

  // Stats for summary
  const totalTags = comparisonResults.length;
  const matchingTags = comparisonResults.filter(r => r.isMatching).length;
  const nonMatchingTags = totalTags - matchingTags;
  const totalMissingTags = missingTags.localOnly.length + missingTags.sedpOnly.length;

  // Get column label map and UOM map for better display
  const { columnLabelMap, columnUomMap } = React.useMemo(() => {
    const labelMap: Record<string, string> = {};
    const uomMap: Record<string, string> = {};

    columnsJSON.forEach(col => {
      labelMap[col.key] = col.displayLabel || col.label;
      if (col.uom) {
        uomMap[col.key] = col.uom;
      }
    });

    return { columnLabelMap: labelMap, columnUomMap: uomMap };
  }, [columnsJSON]);

  // Filter results based on active tab
  const filteredResults = React.useMemo(() => {
    switch (activeTab) {
      case "matching":
        return comparisonResults.filter(r => r.isMatching);
      case "differences":
        return comparisonResults.filter(r => !r.isMatching);
      case "all":
      default:
        return comparisonResults;
    }
  }, [comparisonResults, activeTab]);

  // 변경: 표시할 컬럼 결정 (차이가 있는 컬럼만 or 모든 컬럼)
  const columnsToDisplay = React.useMemo(() => {
    // 기본 컬럼 (TAG_NO, TAG_DESC 제외)
    const columns = columnsJSON.filter(col => col.key !== "TAG_NO" && col.key !== "TAG_DESC");

    if (!showOnlyDifferences) {
      return columns; // 모든 컬럼 표시
    }

    // 하나라도 차이가 있는 속성만 필터링
    const columnsWithDifferences = new Set<string>();
    comparisonResults.forEach(result => {
      result.attributes.forEach(attr => {
        if (!attr.isMatching) {
          columnsWithDifferences.add(attr.key);
        }
      });
    });

    // 차이가 있는 컬럼만 반환
    return columns.filter(col => columnsWithDifferences.has(col.key));
  }, [columnsJSON, comparisonResults, showOnlyDifferences]);

  const fetchAndCompareData = React.useCallback(async () => {
    if (!projectCode || !formCode) {
      toast.error("Project code or form code is missing");
      return;
    }

    try {
      setIsLoading(true);

      // Fetch data from SEDP API
      const sedpData = await fetchTagDataFromSEDP(projectCode, formCode);

      // Get the table name from the response
      const tableName = Object.keys(sedpData)[0];
      const sedpTagEntries = sedpData[tableName] || [];

      // Create a map of SEDP data by TAG_NO for quick lookup
      const sedpTagMap = new Map();
      sedpTagEntries.forEach((entry: any) => {
        const tagNo = entry.TAG_NO;
        const attributesMap = new Map();

        // Convert attributes array to map for easier access
        if (Array.isArray(entry.ATTRIBUTES)) {
          entry.ATTRIBUTES.forEach((attr: any) => {
            attributesMap.set(attr.ATT_ID, attr.VALUE);
          });
        }

        sedpTagMap.set(tagNo, {
          tagDesc: entry.TAG_DESC,
          attributes: attributesMap
        });
      });

      // Create sets for finding missing tags
      const localTagNos = new Set(tableData.map(item => item.TAG_NO));
      const sedpTagNos = new Set(sedpTagMap.keys());

      // Find missing tags
      const localOnlyTags = tableData
        .filter(item => !sedpTagMap.has(item.TAG_NO))
        .map(item => ({ tagNo: item.TAG_NO, tagDesc: item.TAG_DESC || "" }));

      const sedpOnlyTags = Array.from(sedpTagMap.entries())
        .filter(([tagNo]) => !localTagNos.has(tagNo))
        .map(([tagNo, data]) => ({ tagNo, tagDesc: data.tagDesc || "" }));

      setMissingTags({
        localOnly: localOnlyTags,
        sedpOnly: sedpOnlyTags
      });

      // Compare with local table data (only for tags that exist in both systems)
      const results: ComparisonResult[] = tableData
        .filter(localItem => sedpTagMap.has(localItem.TAG_NO))
        .map(localItem => {
          const tagNo = localItem.TAG_NO;
          const sedpItem = sedpTagMap.get(tagNo);

          // Compare attributes
          const attributeComparisons = columnsJSON
            .filter(col => col.key !== "TAG_NO" && col.key !== "TAG_DESC")
            .map(col => {
              const localValue = localItem[col.key];
              const sedpValue = sedpItem.attributes.get(col.key);
              const uom = columnUomMap[col.key];

              // Compare values (with type handling)
              let isMatching = false;

              // Special case: Empty SEDP value and 0 local value
              if ((sedpValue === "" || sedpValue === null || sedpValue === undefined) &&
                (localValue === 0 || localValue === "0")) {
                isMatching = true;
              } else {
                // Standard string comparison for other cases
                const normalizedLocal = localValue === undefined || localValue === null ? "" : String(localValue).trim();
                const normalizedSedp = sedpValue === undefined || sedpValue === null ? "" : String(sedpValue).trim();
                isMatching = normalizedLocal === normalizedSedp;
              }

              return {
                key: col.key,
                label: columnLabelMap[col.key] || col.key,
                localValue,
                sedpValue,
                isMatching,
                uom
              };
            });

          // Item is matching if all attributes match
          const isItemMatching = attributeComparisons.every(attr => attr.isMatching);

          return {
            tagNo,
            tagDesc: localItem.TAG_DESC || "",
            isMatching: isItemMatching,
            attributes: attributeComparisons
          };
        });

      setComparisonResults(results);

      // Show summary in toast
      const matchCount = results.filter(r => r.isMatching).length;
      const nonMatchCount = results.length - matchCount;
      const missingCount = localOnlyTags.length + sedpOnlyTags.length;

      if (missingCount > 0) {
        toast.error(`Found ${missingCount} missing tags between systems`);
      }

      if (nonMatchCount > 0) {
        toast.warning(`Found ${nonMatchCount} tags with differences`);
      } else if (results.length > 0 && missingCount === 0) {
        toast.success(`All ${results.length} tags match with SEDP data`);
      } else if (results.length === 0 && missingCount === 0) {
        toast.info("No tags to compare");
      }

    } catch (error) {
      console.error("SEDP comparison error:", error);
      toast.error(`Failed to compare with SEDP: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsLoading(false);
    }
  }, [projectCode, formCode, tableData, columnsJSON, fetchTagDataFromSEDP, columnLabelMap, columnUomMap]);

  // Fetch data when dialog opens
  React.useEffect(() => {
    if (isOpen) {
      fetchAndCompareData();
    }
  }, [isOpen, fetchAndCompareData]);

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-5xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="mb-2">SEDP 데이터 비교</DialogTitle>
          <div className="flex items-center justify-between gap-2 pr-8">
            <div className="flex items-center gap-2">
              <Switch
                checked={showOnlyDifferences}
                onCheckedChange={setShowOnlyDifferences}
                id="show-differences"
              />
              <label htmlFor="show-differences" className="text-sm cursor-pointer">
                차이가 있는 항목만 표시
              </label>
            </div>
            <div className="flex items-center gap-2">
              <Badge variant={matchingTags === totalTags && totalMissingTags === 0 ? "default" : "destructive"}>
                {matchingTags} / {totalTags} 일치 {totalMissingTags > 0 ? `(${totalMissingTags} 누락)` : ''}
              </Badge>
              <Button
                variant="outline"
                size="sm"
                onClick={fetchAndCompareData}
                disabled={isLoading}
              >
                {isLoading ? (
                  <Loader className="h-4 w-4 animate-spin" />
                ) : (
                  <RefreshCw className="h-4 w-4" />
                )}
                <span className="ml-2">새로고침</span>
              </Button>
            </div>
          </div>
        </DialogHeader>

        {/* 범례 추가 */}
        <div className="mb-4">
          <ColorLegend />
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col overflow-hidden">
          <TabsList>
            <TabsTrigger value="all">전체 태그 ({totalTags})</TabsTrigger>
            <TabsTrigger value="differences">차이 있음 ({nonMatchingTags})</TabsTrigger>
            <TabsTrigger value="matching">일치함 ({matchingTags})</TabsTrigger>
            <TabsTrigger value="missing" className={totalMissingTags > 0 ? "text-red-500" : ""}>
              누락된 태그 ({totalMissingTags})
            </TabsTrigger>
          </TabsList>

          <TabsContent value={activeTab} className="flex-1 overflow-auto">
            {isLoading ? (
              <div className="flex items-center justify-center h-full">
                <Loader className="h-8 w-8 animate-spin mr-2" />
                <span>데이터 비교 중...</span>
              </div>
            ) : activeTab === "missing" ? (
              // Missing tags tab content
              <div className="space-y-6">
                {missingTags.localOnly.length > 0 && (
                  <div>
                    <h3 className="text-sm font-medium mb-2">로컬에만 있는 태그 ({missingTags.localOnly.length})</h3>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-[180px]">Tag Number</TableHead>
                          <TableHead>Tag Description</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {missingTags.localOnly.map((tag) => (
                          <TableRow key={tag.tagNo} className="bg-yellow-50 dark:bg-yellow-950/20">
                            <TableCell className="font-medium">{tag.tagNo}</TableCell>
                            <TableCell>{tag.tagDesc}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                )}

                {missingTags.sedpOnly.length > 0 && (
                  <div>
                    <h3 className="text-sm font-medium mb-2">SEDP에만 있는 태그 ({missingTags.sedpOnly.length})</h3>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-[180px]">Tag Number</TableHead>
                          <TableHead>Tag Description</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {missingTags.sedpOnly.map((tag) => (
                          <TableRow key={tag.tagNo} className="bg-blue-50 dark:bg-blue-950/20">
                            <TableCell className="font-medium">{tag.tagNo}</TableCell>
                            <TableCell>{tag.tagDesc}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                )}

                {totalMissingTags === 0 && (
                  <div className="flex items-center justify-center h-full text-muted-foreground">
                    모든 태그가 양쪽 시스템에 존재합니다
                  </div>
                )}
              </div>
            ) : filteredResults.length > 0 ? (
              // 개선된 테이블 구조
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="sticky left-0 z-10 bg-background w-[180px]">Tag Number</TableHead>
                      <TableHead className="sticky left-[180px] z-10 bg-background w-[200px]">Tag Description</TableHead>
                      <TableHead className="sticky left-[380px] z-10 bg-background w-[100px]">상태</TableHead>
                      
                      {/* 동적으로 속성 열 헤더 생성 */}
                      {columnsToDisplay.length > 0 ? (
                        columnsToDisplay.map(col => (
                          <TableHead key={col.key} className="min-w-[150px]">
                            {columnLabelMap[col.key] || col.key}
                            {columnUomMap[col.key] && (
                              <span className="text-xs text-muted-foreground ml-1">
                                ({columnUomMap[col.key]})
                              </span>
                            )}
                          </TableHead>
                        ))
                      ) : (
                        <TableHead>
                          <div className="flex items-center justify-center text-muted-foreground">
                            <EyeOff className="h-4 w-4 mr-2" />
                            <span>차이가 있는 항목이 없습니다</span>
                          </div>
                        </TableHead>
                      )}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredResults.map((result) => (
                      <TableRow key={result.tagNo} className={!result.isMatching ? "bg-muted/30" : ""}>
                        <TableCell className="sticky left-0 z-10 bg-background font-medium">
                          {result.tagNo}
                        </TableCell>
                        <TableCell className="sticky left-[180px] z-10 bg-background">
                          {result.tagDesc}
                        </TableCell>
                        <TableCell className="sticky left-[380px] z-10 bg-background">
                          {result.isMatching ? (
                            <Badge variant="default" className="flex items-center gap-1">
                              <CheckCircle className="h-3 w-3" />
                              <span>일치</span>
                            </Badge>
                          ) : (
                            <Badge variant="destructive" className="flex items-center gap-1">
                              <AlertCircle className="h-3 w-3" />
                              <span>차이 있음</span>
                            </Badge>
                          )}
                        </TableCell>
                        
                        {/* 각 속성에 대한 셀 동적 생성 */}
                        {columnsToDisplay.length > 0 ? (
                          columnsToDisplay.map(col => {
                            const attr = result.attributes.find(a => a.key === col.key);
                            
                            if (!attr) return <TableCell key={col.key}>-</TableCell>;
                            
                            return (
                              <TableCell 
                                key={col.key} 
                                className={!attr.isMatching ? "bg-muted/50" : ""}
                              >
                                {attr.isMatching ? (
                                  <DisplayValue value={attr.localValue} uom={attr.uom} />
                                ) : (
                                  <div className="flex flex-col gap-1">
                                    <div className="line-through text-red-500">
                                      <DisplayValue value={attr.localValue} uom={attr.uom} isSedp={false} />
                                    </div>
                                    <div className="text-green-500">
                                      <DisplayValue value={attr.sedpValue} uom={attr.uom} isSedp={true} />
                                    </div>
                                  </div>
                                )}
                              </TableCell>
                            );
                          })
                        ) : (
                          <TableCell>
                            <span className="text-muted-foreground">모든 값이 일치합니다</span>
                          </TableCell>
                        )}
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="flex items-center justify-center h-full text-muted-foreground">
                현재 필터에 맞는 태그가 없습니다
              </div>
            )}
          </TabsContent>
        </Tabs>

        <DialogFooter className="flex justify-between items-center gap-4 pt-4 border-t">
          <ExcelDownload
            comparisonResults={comparisonResults}
            missingTags={missingTags}
            formCode={formCode}
            disabled={isLoading || (nonMatchingTags === 0 && totalMissingTags === 0)}
          />
          <Button onClick={onClose}>닫기</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}