File size: 16,149 Bytes
3aeb97e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect, useCallback } from "react";
import { Save, X, Loader2, HelpCircle } from "lucide-react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Label } from "./ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Checkbox } from "./ui/checkbox";
import { toast } from "sonner";
import { getDataCatalogSource, saveDataDictionary } from "../../services/orchestrationApi";

export interface DataDictionaryColumn {
  column_id: string;
  name: string;
  data_type: string;
  nullable: boolean;
  pii_flag: boolean;
  sample_values?: any[];
  stats?: {
    min?: any;
    max?: any;
    mean?: number | null;
    median?: number | null;
    distinct_count?: number;
  };
  description?: string;
  aggregation?: string; // sum, avg, min, max, count
  classify?: string; // dimension or measure
  business_meaning?: string;
  data_classification?: string;
  is_key?: boolean;
}

export interface DataDictionaryTable {
  table_id: string;
  name: string;
  row_count?: number;
  columns: DataDictionaryColumn[];
}

export interface DataDictionarySource {
  source_id: string;
  source_type: "schema" | "tabular" | "unstructured";
  name: string;
  tables: DataDictionaryTable[];
}

interface DataDictionaryFormProps {
  open: boolean;
  onClose: () => void;
  sourceId: string;
  sourceName: string;
  userId: string;
  selectedTableId?: string;
  onTableChange?: (tableId: string) => void;
}

const AGGREGATION_OPTIONS = [
  { value: "none", label: "None" },
  { value: "sum", label: "Sum" },
  { value: "avg", label: "Average" },
  { value: "min", label: "Min" },
  { value: "max", label: "Max" },
  { value: "count", label: "Count" },
];

const CLASSIFY_OPTIONS = [
  { value: "none", label: "Select..." },
  { value: "dimension", label: "Dimension" },
  { value: "measure", label: "Measure" },
];

export default function DataDictionaryForm({
  open,
  onClose,
  sourceId,
  sourceName,
  userId,
  selectedTableId,
  onTableChange,
}: DataDictionaryFormProps) {
  const [sources, setSources] = useState<DataDictionarySource[]>([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [activeTableId, setActiveTableId] = useState<string | undefined>(selectedTableId);
  const [editedColumns, setEditedColumns] = useState<Record<string, Partial<DataDictionaryColumn>>>({});

  useEffect(() => {
    if (open) {
      loadCatalog();
    }
  }, [open, sourceId, userId]);

  useEffect(() => {
    if (selectedTableId) {
      setActiveTableId(selectedTableId);
    }
  }, [selectedTableId]);

  const loadCatalog = async () => {
    setLoading(true);
    try {
      const source = await getDataCatalogSource(userId, sourceId);
      if (source) {
        // Transform to our type - source now contains full tables/columns
        const transformed: DataDictionarySource = {
          source_id: source.source_id,
          source_type: source.source_type as "schema" | "tabular" | "unstructured",
          name: source.name,
          tables: (source.tables || []).map((t: any) => ({
            table_id: t.table_id || t.name,
            name: t.name,
            row_count: t.row_count,
            columns: (t.columns || []).map((c: any) => ({
              column_id: c.column_id,
              name: c.name,
              data_type: c.data_type,
              nullable: c.nullable,
              pii_flag: c.pii_flag,
              sample_values: c.sample_values,
              stats: c.stats,
              description: c.description,
              business_meaning: c.business_meaning,
              data_classification: c.data_classification,
              is_key: c.is_key,
            })),
          })),
        };
        setSources([transformed]);
        // Auto-select first table if none selected
        if (!activeTableId && transformed.tables.length > 0) {
          setActiveTableId(transformed.tables[0].table_id);
          onTableChange?.(transformed.tables[0].table_id);
        }
      }
    } catch (err) {
      console.error("Failed to load catalog:", err);
      toast.error("Failed to load data dictionary");
    } finally {
      setLoading(false);
    }
  };

  const handleColumnChange = useCallback(
    (columnId: string, field: keyof DataDictionaryColumn, value: any) => {
      setEditedColumns((prev) => ({
        ...prev,
        [columnId]: {
          ...prev[columnId],
          [field]: value,
        },
      }));
    },
    []
  );

  const handleSave = async () => {
    if (saving) return;
    setSaving(true);
    try {
      const source = sources[0];
      if (!source) throw new Error("Source not found");

      // Prepare updated tables - apply edits to ALL tables
      const updatedTables = source.tables.map((table) => {
        const updatedColumns = table.columns.map((col) => {
          const edits = editedColumns[col.column_id] || {};
          return {
            ...col,
            ...edits,
          };
        });
        return { ...table, columns: updatedColumns };
      });

      // Update the source in catalog
      const updatedSource = {
        ...source,
        tables: updatedTables,
      };

      await saveDataDictionary(userId, sourceId, updatedSource);
      toast.success("Data dictionary saved successfully");
      onClose();
    } catch (err) {
      console.error("Failed to save data dictionary:", err);
      toast.error(err instanceof Error ? err.message : "Failed to save data dictionary");
    } finally {
      setSaving(false);
    }
  };

  if (!open) return null;

  const source = sources[0];
  const activeTable = source?.tables.find((t) => t.table_id === activeTableId);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-sm">
      <div className="flex max-h-[90vh] w-full max-w-5xl flex-col rounded-2xl bg-white shadow-xl">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
          <div className="flex items-center gap-3">
            <button onClick={onClose} className="p-1.5 -ml-1 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition">
              <X className="w-4 h-4" />
            </button>
            <div className="w-7 h-7 rounded-lg bg-orange-100 flex items-center justify-center">
              <HelpCircle className="w-4 h-4 text-[#FF8F00]" />
            </div>
            <div>
              <h2 className="text-sm font-semibold text-slate-900">Data Dictionary</h2>
              <p className="text-xs text-slate-400">{sourceName}</p>
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto px-5 py-4">
          {loading ? (
            <div className="flex justify-center py-10">
              <Loader2 className="w-5 h-5 animate-spin text-slate-300" />
            </div>
          ) : source ? (
            <div className="space-y-4">
              {/* Table selector for multi-table sources */}
              {source.tables.length > 1 && (
                <div className="flex items-center gap-2 px-3 py-2.5 rounded-xl border border-slate-100">
                  <Label htmlFor="table-select" className="text-xs font-medium text-slate-500 mr-2">
                    Select Table/Worksheet:
                  </Label>
                  <Select value={activeTableId} onValueChange={setActiveTableId}>
                    <SelectTrigger id="table-select" className="w-64">
                      <SelectValue placeholder="Choose a table..." />
                    </SelectTrigger>
                    <SelectContent>
                      {source.tables.map((table) => (
                        <SelectItem key={table.table_id} value={table.table_id}>
                          {table.name} ({table.columns.length} columns)
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}

              {/* Columns Table */}
              {activeTable && (
                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-base">
                      {activeTable.name} ({activeTable.columns.length} columns)
                      {activeTable.row_count && (
                        <span className="ml-2 text-xs text-slate-400 font-normal">
                          {activeTable.row_count.toLocaleString()} rows
                        </span>
                      )}
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-0">
                    <div className="overflow-x-auto">
                      <table className="w-full">
                        <thead>
                          <tr className="border-b border-slate-100 bg-slate-50">
                            <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-8">
                              #
                            </th>
                            <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">
                              Column
                            </th>
                            <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-24">
                              Type
                            </th>
                            <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-16">
                              Nullable
                            </th>
                            <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">
                              Description
                            </th>
                            <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-32">
                              Classify
                            </th>
                            <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-32">
                              Aggregation
                            </th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                          {activeTable.columns.map((col, index) => {
                            const edits = editedColumns[col.column_id] || {};
                            const classify = (edits.classify ?? col.classify ?? "") as string;
                            const isMeasure = classify === "measure";
                            return (
                              <tr key={col.column_id} className="hover:bg-slate-50/50">
                                <td className="px-3 py-2 text-xs text-slate-400 font-mono">{index + 1}</td>
                                <td className="px-3 py-2">
                                  <div className="flex items-center gap-2">
                                    <span className="text-sm font-medium text-slate-800 truncate max-w-[150px]">
                                      {col.name}
                                    </span>
                                  </div>
                                </td>
                                <td className="px-3 py-2 text-xs text-slate-500 font-mono">{col.data_type}</td>
                                <td className="px-3 py-2">
                                  <Checkbox
                                    checked={col.nullable}
                                    disabled
                                    className="text-slate-400"
                                  />
                                </td>
                                <td className="px-3 py-2">
                                  <Input
                                    value={edits.description ?? col.description ?? ""}
                                    onChange={(e) => handleColumnChange(col.column_id, "description", e.target.value)}
                                    placeholder="Add description..."
                                    className="text-xs h-7 px-2"
                                  />
                                </td>
                                <td className="px-3 py-2">
                                  <Select
                                    value={classify || undefined}
                                    onValueChange={(v) => handleColumnChange(col.column_id, "classify", v)}
                                  >
                                    <SelectTrigger className="text-xs h-7 px-2">
                                      <SelectValue placeholder="Select..." />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {CLASSIFY_OPTIONS.map((opt) => (
                                        <SelectItem key={opt.value} value={opt.value}>
                                          {opt.label}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                </td>
                                <td className="px-3 py-2">
                                  <Select
                                    value={isMeasure ? ((edits.aggregation ?? col.aggregation) === "none" ? undefined : (edits.aggregation ?? col.aggregation)) : undefined}
                                    onValueChange={(v) => handleColumnChange(col.column_id, "aggregation", v === "none" ? "" : v)}
                                    disabled={!isMeasure}
                                  >
                                    <SelectTrigger className="text-xs h-7 px-2">
                                      <SelectValue placeholder="None" />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {AGGREGATION_OPTIONS.map((opt) => (
                                        <SelectItem key={opt.value} value={opt.value}>
                                          {opt.label}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  </CardContent>
                </Card>
              )}

              {!source && (
                <div className="text-center py-8">
                  <p className="text-sm text-slate-400">No catalog data found for this source.</p>
                </div>
              )}
            </div>
          ) : (
            <div className="text-center py-8">
              <p className="text-sm text-slate-400">No catalog data found for this source.</p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-5 py-3 border-t border-slate-100 flex justify-end gap-2">
          <Button variant="ghost" onClick={onClose} disabled={saving}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={saving}>
            {saving ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
                Saving...
              </>
            ) : (
              <>
                <Save className="w-4 h-4 mr-2" />
                Save Data Dictionary
              </>
            )}
          </Button>
        </div>
      </div>
    </div>
  );
}

export { DataDictionaryForm };