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
|
"use client";
import * as React from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Check, ChevronsUpDown, Loader, LockIcon } from "lucide-react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Form,
FormField,
FormItem,
FormLabel,
FormControl,
FormMessage,
FormDescription,
} from "@/components/ui/form";
import {
Popover,
PopoverTrigger,
PopoverContent,
} from "@/components/ui/popover"
import {
Command,
CommandInput,
CommandList,
CommandGroup,
CommandItem,
CommandEmpty,
} from "@/components/ui/command"
import { DataTableColumnJSON } from "./form-data-table-columns";
import { updateFormDataInDB } from "@/lib/forms/services";
import { cn } from "@/lib/utils";
interface UpdateTagSheetProps
extends React.ComponentPropsWithoutRef<typeof Sheet> {
open: boolean;
onOpenChange: (open: boolean) => void;
columns: DataTableColumnJSON[];
rowData: Record<string, any> | null;
formCode: string;
contractItemId: number;
editableFieldsMap?: Map<string, string[]>; // 새로 추가
/** 업데이트 성공 시 호출될 콜백 */
onUpdateSuccess?: (updatedValues: Record<string, any>) => void;
}
export function UpdateTagSheet({
open,
onOpenChange,
columns,
rowData,
formCode,
contractItemId,
editableFieldsMap = new Map(), // 기본값 설정
onUpdateSuccess,
...props
}: UpdateTagSheetProps) {
const [isPending, startTransition] = React.useTransition();
const router = useRouter();
// 현재 TAG의 편집 가능한 필드 목록 가져오기
const editableFields = React.useMemo(() => {
if (!rowData?.TAG_NO || !editableFieldsMap.has(rowData.TAG_NO)) {
return [];
}
return editableFieldsMap.get(rowData.TAG_NO) || [];
}, [rowData?.TAG_NO, editableFieldsMap]);
// 필드가 편집 가능한지 판별하는 함수
const isFieldEditable = React.useCallback((column: DataTableColumnJSON) => {
// 1. SHI-only 필드는 편집 불가
if (column.shi === true) {
return false;
}
// 2. TAG_NO와 TAG_DESC는 기본적으로 편집 가능 (필요에 따라 수정 가능)
if (column.key === "TAG_NO" || column.key === "TAG_DESC") {
return true;
}
//3. editableFieldsMap이 있으면 해당 리스트에 있는지 확인
// if (rowData?.TAG_NO && editableFieldsMap.has(rowData.TAG_NO)) {
// return editableFields.includes(column.key);
// }
// 4. editableFieldsMap 정보가 없으면 기본적으로 편집 불가 (안전한 기본값)
return true;
}, []);
// 읽기 전용 필드인지 판별하는 함수 (편집 가능의 반대)
const isFieldReadOnly = React.useCallback((column: DataTableColumnJSON) => {
return !isFieldEditable(column);
}, [isFieldEditable]);
// 읽기 전용 사유를 반환하는 함수
const getReadOnlyReason = React.useCallback((column: DataTableColumnJSON) => {
if (column.shi === true) {
return "SHI-only field (managed by SHI system)";
}
if (column.key !== "TAG_NO" && column.key !== "TAG_DESC") {
if (!rowData?.TAG_NO || !editableFieldsMap.has(rowData.TAG_NO)) {
return "No editable fields information for this TAG";
}
if (!editableFields.includes(column.key)) {
return "Not editable for this TAG class";
}
}
return "Read-only field";
}, [rowData?.TAG_NO, editableFieldsMap, editableFields]);
// 1) zod 스키마
const dynamicSchema = React.useMemo(() => {
const shape: Record<string, z.ZodType<any>> = {};
for (const col of columns) {
if (col.type === "NUMBER") {
shape[col.key] = z
.union([z.coerce.number(), z.nan()])
.transform((val) => (isNaN(val) ? undefined : val))
.optional();
} else {
shape[col.key] = z.string().optional();
}
}
return z.object(shape);
}, [columns]);
// 2) form init
const form = useForm({
resolver: zodResolver(dynamicSchema),
defaultValues: React.useMemo(() => {
if (!rowData) return {};
const defaults: Record<string, any> = {};
for (const col of columns) {
defaults[col.key] = rowData[col.key] ?? "";
}
return defaults;
}, [rowData, columns]),
});
React.useEffect(() => {
if (!rowData) {
form.reset({});
return;
}
const defaults: Record<string, any> = {};
for (const col of columns) {
defaults[col.key] = rowData[col.key] ?? "";
}
form.reset(defaults);
}, [rowData, columns, form]);
async function onSubmit(values: Record<string, any>) {
startTransition(async () => {
try {
// 제출 전에 읽기 전용 필드를 원본 값으로 복원
const finalValues = { ...values };
for (const col of columns) {
if (isFieldReadOnly(col)) {
// 읽기 전용 필드는 원본 값으로 복원
finalValues[col.key] = rowData?.[col.key] ?? "";
}
}
const { success, message } = await updateFormDataInDB(
formCode,
contractItemId,
finalValues
);
if (!success) {
toast.error(message);
return;
}
// Success handling
toast.success("Updated successfully!");
// Create a merged object of original rowData and new values
const updatedData = {
...rowData,
...finalValues,
TAG_NO: rowData?.TAG_NO,
};
// Call the success callback
onUpdateSuccess?.(updatedData);
// Refresh the entire route to get fresh data
router.refresh();
// Close the sheet
onOpenChange(false);
} catch (error) {
console.error("Error updating form data:", error);
toast.error("An unexpected error occurred while updating");
}
});
}
// 편집 가능한 필드 개수 계산
const editableFieldCount = React.useMemo(() => {
return columns.filter(col => isFieldEditable(col)).length;
}, [columns, isFieldEditable]);
return (
<Sheet open={open} onOpenChange={onOpenChange} {...props}>
<SheetContent className="sm:max-w-xl md:max-w-3xl lg:max-w-4xl xl:max-w-5xl flex flex-col">
<SheetHeader className="text-left">
<SheetTitle>Update Row - {rowData?.TAG_NO || 'Unknown TAG'}</SheetTitle>
<SheetDescription>
Modify the fields below and save changes. Fields with <LockIcon className="inline h-3 w-3" /> are read-only.
<br />
<span className="text-sm text-green-600">
{editableFieldCount} of {columns.length} fields are editable for this TAG.
</span>
</SheetDescription>
</SheetHeader>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col gap-4"
>
<div className="overflow-y-auto max-h-[80vh] flex-1 pr-4 -mr-4">
<div className="flex flex-col gap-4 pt-2">
{columns.map((col) => {
const isReadOnly = isFieldReadOnly(col);
const readOnlyReason = isReadOnly ? getReadOnlyReason(col) : "";
return (
<FormField
key={col.key}
control={form.control}
name={col.key}
render={({ field }) => {
switch (col.type) {
case "NUMBER":
return (
<FormItem>
<FormLabel className="flex items-center">
{col.displayLabel || col.label}
{isReadOnly && (
<LockIcon className="ml-1 h-3 w-3 text-gray-400" />
)}
</FormLabel>
<FormControl>
<Input
type="number"
readOnly={isReadOnly}
onChange={(e) => {
const num = parseFloat(e.target.value);
field.onChange(isNaN(num) ? "" : num);
}}
value={field.value ?? ""}
className={cn(
isReadOnly && "bg-gray-100 text-gray-600 cursor-not-allowed border-gray-300"
)}
/>
</FormControl>
{isReadOnly && (
<FormDescription className="text-xs text-gray-500">
{readOnlyReason}
</FormDescription>
)}
<FormMessage />
</FormItem>
);
case "LIST":
return (
<FormItem>
<FormLabel className="flex items-center">
{col.label}
{isReadOnly && (
<LockIcon className="ml-1 h-3 w-3 text-gray-400" />
)}
</FormLabel>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
disabled={isReadOnly}
className={cn(
"w-full justify-between",
!field.value && "text-muted-foreground",
isReadOnly && "bg-gray-100 text-gray-600 cursor-not-allowed border-gray-300"
)}
>
{field.value
? col.options?.find((opt) => opt === field.value)
: "Select an option"}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
<CommandInput placeholder="Search options..." />
<CommandEmpty>No option found.</CommandEmpty>
<CommandList>
<CommandGroup>
{col.options?.map((opt) => (
<CommandItem
key={opt}
value={opt}
onSelect={() => {
field.onChange(opt);
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
field.value === opt ? "opacity-100" : "opacity-0"
)}
/>
{opt}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
{isReadOnly && (
<FormDescription className="text-xs text-gray-500">
{readOnlyReason}
</FormDescription>
)}
<FormMessage />
</FormItem>
);
case "STRING":
default:
return (
<FormItem>
<FormLabel className="flex items-center">
{col.label}
{isReadOnly && (
<LockIcon className="ml-1 h-3 w-3 text-gray-400" />
)}
</FormLabel>
<FormControl>
<Input
readOnly={isReadOnly}
{...field}
className={cn(
isReadOnly && "bg-gray-100 text-gray-600 cursor-not-allowed border-gray-300"
)}
/>
</FormControl>
{isReadOnly && (
<FormDescription className="text-xs text-gray-500">
{readOnlyReason}
</FormDescription>
)}
<FormMessage />
</FormItem>
);
}
}}
/>
);
})}
</div>
</div>
<SheetFooter className="gap-2 pt-2">
<SheetClose asChild>
<Button type="button" variant="outline">
Cancel
</Button>
</SheetClose>
<Button type="submit" disabled={isPending}>
{isPending && <Loader className="mr-2 h-4 w-4 animate-spin" />}
Save
</Button>
</SheetFooter>
</form>
</Form>
</SheetContent>
</Sheet>
);
}
|