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
|
"use client";
import * as React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { format } from "date-fns";
import { ko } from "date-fns/locale/ko";
import { toast } from "sonner";
import { Loader2, CalendarIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetFooter, SheetClose } from "@/components/ui/sheet";
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { cn } from "@/lib/utils";
import { updateTechSalesRfq, getTechSalesRfqById } from "@/lib/techsales-rfq/service";
import { getProjectSeriesForProject } from "@/lib/bidding-projects/service";
import { type ProjectSeries } from "@/db/schema/projects";
// Zod schema for form validation
const updateRfqSchema = z.object({
rfqId: z.number().min(1, "RFQ ID is required"),
description: z.string(),
remark: z.string(),
dueDate: z.string(),
});
type UpdateRfqSchema = z.infer<typeof updateRfqSchema>;
interface UpdateSheetProps {
open: boolean;
onOpenChange?: (open: boolean) => void;
rfqId: number;
onUpdated?: () => void;
}
export default function UpdateSheet({ open, onOpenChange, rfqId, onUpdated }: UpdateSheetProps) {
const [isPending, startTransition] = React.useTransition();
const [projectInfo, setProjectInfo] = React.useState({
projNm: "",
sector: "",
projMsrm: "",
ptypeNm: "",
rfqNo: "",
pspid: "",
});
const [rfqInfo, setRfqInfo] = React.useState({
status: "",
createdAt: "",
updatedAt: "",
createdByName: "",
updatedByName: "",
sentByName: "",
rfqSendDate: "",
});
const [seriesInfo, setSeriesInfo] = React.useState<ProjectSeries[]>([]);
const [isLoading, setIsLoading] = React.useState(false);
const [isLoadingSeries, setIsLoadingSeries] = React.useState(false);
// K/L 날짜를 4분기로 변환하는 함수
const convertKLToQuarter = React.useCallback((klDate: string | null): string => {
if (!klDate) return "정보 없음"
try {
// YYYYMMDD 형식의 날짜를 파싱
const year = parseInt(klDate.substring(0, 4))
const month = parseInt(klDate.substring(4, 6))
// 4분기 계산 (1-3월: 1Q, 4-6월: 2Q, 7-9월: 3Q, 10-12월: 4Q)
const quarter = Math.ceil(month / 3)
return `${year} ${quarter}Q`
} catch (error) {
console.error("K/L 날짜 변환 오류:", error)
return "날짜 오류"
}
}, [])
// Initialize form with React Hook Form and Zod
const form = useForm<UpdateRfqSchema>({
resolver: zodResolver(updateRfqSchema),
defaultValues: {
rfqId,
description: "",
remark: "",
dueDate: "",
},
});
// Load RFQ data when sheet opens
React.useEffect(() => {
if (open && rfqId) {
loadRfqData();
}
}, [open, rfqId]);
const loadRfqData = async () => {
try {
setIsLoading(true);
const result = await getTechSalesRfqById(rfqId);
if (result.error) {
toast.error(result.error);
onOpenChange?.(false);
return;
}
if (result.data) {
form.reset({
rfqId,
description: result.data.description || "",
remark: result.data.remark || "",
dueDate: result.data.dueDate ? new Date(result.data.dueDate).toISOString().slice(0, 10) : "",
});
const pspid = result.data.project[0].pspid || "";
setProjectInfo({
projNm: result.data.project[0].projectName || "",
sector: result.data.project[0].pjtType || "",
projMsrm: result.data.project[0].projMsrm || "",
ptypeNm: result.data.project[0].ptypeNm || "",
rfqNo: result.data.rfqCode || "",
pspid: pspid,
});
setRfqInfo({
status: result.data.status || "",
createdAt: result.data.createdAt ? format(new Date(result.data.createdAt), "yyyy-MM-dd HH:mm") : "",
updatedAt: result.data.updatedAt ? format(new Date(result.data.updatedAt), "yyyy-MM-dd HH:mm") : "",
createdByName: (result.data as any).createdByName || (result.data as any).createdBy || "",
updatedByName: (result.data as any).updatedByName || (result.data as any).updatedBy || "",
sentByName: (result.data as any).sentByName || (result.data as any).sentBy || "",
rfqSendDate: result.data.rfqSendDate ? format(new Date(result.data.rfqSendDate), "yyyy-MM-dd HH:mm") : "",
});
// 시리즈 정보 로드
if (pspid) {
setIsLoadingSeries(true);
try {
const seriesResult = await getProjectSeriesForProject(pspid);
setSeriesInfo(seriesResult);
} catch (error) {
console.error("시리즈 정보 로드 오류:", error);
setSeriesInfo([]);
} finally {
setIsLoadingSeries(false);
}
} else {
setSeriesInfo([]);
}
}
} catch (error: any) {
toast.error("RFQ 정보를 불러오는 중 오류가 발생했습니다: " + error.message);
onOpenChange?.(false);
} finally {
setIsLoading(false);
}
};
// Form submission handler with debug logs
async function onSubmit(values: UpdateRfqSchema) {
console.log("Form submitted with values:", values);
startTransition(async () => {
try {
console.log("Submitting RFQ update for ID:", values.rfqId);
const result = await updateTechSalesRfq({
id: values.rfqId,
description: values.description,
remark: values.remark,
dueDate: new Date(values.dueDate),
updatedBy: 1, // Replace with actual user ID
});
if (result.error) {
console.error("Update error:", result.error);
toast.error(result.error);
} else {
console.log("RFQ updated successfully");
toast.success("RFQ가 성공적으로 업데이트되었습니다!");
onUpdated?.();
onOpenChange?.(false);
form.reset();
}
} catch (error: any) {
console.error("Update failed with error:", error.message);
toast.error("업데이트 중 오류 발생: " + error.message);
}
});
}
// Debug form errors on change
React.useEffect(() => {
const subscription = form.watch(() => {
console.log("Form values changed:", form.getValues());
console.log("Form errors:", form.formState.errors);
});
return () => subscription.unsubscribe();
}, [form]);
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="flex flex-col h-full sm:max-w-xl bg-gray-50">
<SheetHeader className="text-left flex-shrink-0">
<SheetTitle className="text-2xl font-bold">RFQ 미리보기</SheetTitle>
<SheetDescription className="">
RFQ 정보를 확인하고 필요한 항목을 수정하세요. RFQ Title, Context, 마감일만 수정 가능합니다.
</SheetDescription>
</SheetHeader>
<div className="flex-1 overflow-y-auto py-4">
{isLoading ? (
<div className="flex justify-center items-center py-12">
<Loader2 className="h-10 w-10 animate-spin" />
</div>
) : (
<div className="space-y-6">
{/* 프로젝트 정보 */}
<div className="bg-white shadow-sm rounded-lg p-5 border border-gray-200">
<h3 className="text-lg font-semibold mb-3 text-gray-800">프로젝트 정보</h3>
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="font-semibold text-gray-700">프로젝트명:</span> {projectInfo.projNm}
</div>
<div>
<span className="font-semibold text-gray-700">섹터:</span> {projectInfo.sector}
</div>
<div>
<span className="font-semibold text-gray-700">척수:</span> {projectInfo.projMsrm}
</div>
<div>
<span className="font-semibold text-gray-700">선종:</span> {projectInfo.ptypeNm}
</div>
<div>
<span className="font-semibold text-gray-700">RFQ No:</span> {projectInfo.rfqNo}
</div>
</div>
</div>
{/* 시리즈 정보 - 프로젝트 정보 아래에 배치 */}
<div className="bg-white shadow-sm rounded-lg p-5 border border-gray-200">
<h3 className="text-lg font-semibold mb-3 text-gray-800">시리즈 정보</h3>
{isLoadingSeries ? (
<div className="text-center py-4 text-gray-500">
시리즈 정보 로딩 중...
</div>
) : seriesInfo && seriesInfo.length > 0 ? (
<div className="grid grid-cols-1 gap-3">
{seriesInfo.map((series) => (
<div key={series.sersNo} className="bg-gray-50 rounded border p-3">
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 text-sm">
<div>
<span className="font-medium text-gray-700">시리즈번호:</span>
<div className="text-gray-900">{series.sersNo}</div>
</div>
<div>
<span className="font-medium text-gray-700">K/L (Keel Laying):</span>
<div className="text-gray-900">{convertKLToQuarter(series.klDt)}</div>
</div>
<div>
<span className="font-medium text-gray-700">도크코드:</span>
<div className="text-gray-900">{series.dockNo || "N/A"}</div>
</div>
<div>
<span className="font-medium text-gray-700">도크명:</span>
<div className="text-gray-900">{series.dockNm || "N/A"}</div>
</div>
</div>
</div>
))}
</div>
) : (
<div className="text-center py-4 text-gray-500">
시리즈 데이터가 없습니다.
</div>
)}
</div>
{/* RFQ 정보 */}
{/* <div className="bg-white shadow-sm rounded-lg p-5 border border-gray-200">
<h3 className="text-lg font-semibold mb-3 text-gray-800">RFQ 정보</h3>
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="font-semibold text-gray-700">상태:</span> {rfqInfo.status}
</div>
<div>
<span className="font-semibold text-gray-700">생성자:</span> {rfqInfo.createdByName}
</div>
<div>
<span className="font-semibold text-gray-700">생성일:</span> {rfqInfo.createdAt}
</div>
<div>
<span className="font-semibold text-gray-700">수정자:</span> {rfqInfo.updatedByName}
</div>
<div>
<span className="font-semibold text-gray-700">수정일:</span> {rfqInfo.updatedAt}
</div>
<div>
<span className="font-semibold text-gray-700">발송자:</span> {rfqInfo.sentByName}
</div>
<div>
<span className="font-semibold text-gray-700">발송일:</span> {rfqInfo.rfqSendDate}
</div>
</div>
</div> */}
<Form {...form}>
<form id="update-rfq-form" onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel className="text-sm font-medium text-gray-700">RFQ Title</FormLabel>
<FormControl>
<Input
{...field}
placeholder="RFQ Title을 입력하세요"
className="border-gray-300 rounded-md"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="remark"
render={({ field }) => (
<FormItem>
<FormLabel className="text-sm font-medium text-gray-700">RFQ Context</FormLabel>
<FormControl>
<Textarea
{...field}
placeholder="RFQ Context를 입력하세요"
className="border-gray-300 rounded-md min-h-[100px]"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dueDate"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>마감일</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant="outline"
className={cn(
"w-full pl-3 text-left font-normal",
!field.value && "text-muted-foreground"
)}
>
{field.value ? (
format(new Date(field.value), "PPP", { locale: ko })
) : (
<span>마감일을 선택하세요</span>
)}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={field.value ? new Date(field.value) : undefined}
onSelect={(date) => {
// date-fns format을 사용해 yyyy-MM-dd로 변환하여 string 저장
if (date) {
field.onChange(format(date, "yyyy-MM-dd"));
}
}}
disabled={(date) =>
date < new Date() || date < new Date("1900-01-01")
}
initialFocus
/>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</div>
)}
</div>
<SheetFooter className="gap-2 pt-2 sm:space-x-0 flex-shrink-0">
<SheetClose asChild>
<Button
type="button"
variant="outline"
disabled={isPending}
className="border-gray-300 text-gray-700 hover:bg-gray-100 rounded-md"
>
취소
</Button>
</SheetClose>
<Button
type="submit"
form="update-rfq-form"
disabled={isPending}
className="bg-blue-600 hover:bg-blue-700 text-white rounded-md"
onClick={() => console.log("Save button clicked")}
>
{isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
저장
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}
|