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
|
"use client"
import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Loader } from "lucide-react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Textarea } from "@/components/ui/textarea"
import { VendorWithCbeFields } from "@/config/vendorCbeColumnsConfig"
import { getCommercialResponseByResponseId, updateCommercialResponse } from "../service"
// Define schema for form validation (client-side)
const commercialResponseFormSchema = z.object({
responseStatus: z.enum(["PENDING", "IN_PROGRESS", "SUBMITTED", "REJECTED", "ACCEPTED"]),
totalPrice: z.coerce.number().optional(),
currency: z.string().default("USD"),
paymentTerms: z.string().optional(),
incoterms: z.string().optional(),
deliveryPeriod: z.string().optional(),
warrantyPeriod: z.string().optional(),
validityPeriod: z.string().optional(),
priceBreakdown: z.string().optional(),
commercialNotes: z.string().optional(),
})
type CommercialResponseFormInput = z.infer<typeof commercialResponseFormSchema>
interface CommercialResponseSheetProps
extends React.ComponentPropsWithRef<typeof Sheet> {
rfq: VendorWithCbeFields | null
responseId: number | null // This is the vendor_responses.id
onSuccess?: () => void
}
export function CommercialResponseSheet({
rfq,
responseId,
onSuccess,
...props
}: CommercialResponseSheetProps) {
const [isSubmitting, startSubmitTransition] = React.useTransition()
const [isLoading, setIsLoading] = React.useState(true)
const form = useForm<CommercialResponseFormInput>({
resolver: zodResolver(commercialResponseFormSchema),
defaultValues: {
responseStatus: "PENDING",
totalPrice: undefined,
currency: "USD",
paymentTerms: "",
incoterms: "",
deliveryPeriod: "",
warrantyPeriod: "",
validityPeriod: "",
priceBreakdown: "",
commercialNotes: "",
},
})
// Load existing commercial response data when sheet opens
React.useEffect(() => {
async function loadCommercialResponse() {
if (!responseId) return
setIsLoading(true)
try {
// Use the helper function to get existing data
const existingResponse = await getCommercialResponseByResponseId(responseId)
if (existingResponse) {
// If we found existing data, populate the form
form.reset({
responseStatus: existingResponse.responseStatus,
totalPrice: existingResponse.totalPrice,
currency: existingResponse.currency || "USD",
paymentTerms: existingResponse.paymentTerms || "",
incoterms: existingResponse.incoterms || "",
deliveryPeriod: existingResponse.deliveryPeriod || "",
warrantyPeriod: existingResponse.warrantyPeriod || "",
validityPeriod: existingResponse.validityPeriod || "",
priceBreakdown: existingResponse.priceBreakdown || "",
commercialNotes: existingResponse.commercialNotes || "",
})
} else if (rfq) {
// If no existing data but we have rfq data with some values already
form.reset({
responseStatus: rfq.commercialResponseStatus as any || "PENDING",
totalPrice: rfq.totalPrice || undefined,
currency: rfq.currency || "USD",
paymentTerms: rfq.paymentTerms || "",
incoterms: rfq.incoterms || "",
deliveryPeriod: rfq.deliveryPeriod || "",
warrantyPeriod: rfq.warrantyPeriod || "",
validityPeriod: rfq.validityPeriod || "",
priceBreakdown: "",
commercialNotes: "",
})
}
} catch (error) {
console.error("Failed to load commercial response data:", error)
toast.error("상업 응답 데이터를 불러오는데 실패했습니다")
} finally {
setIsLoading(false)
}
}
loadCommercialResponse()
}, [responseId, rfq, form])
function onSubmit(formData: CommercialResponseFormInput) {
if (!responseId) {
toast.error("응답 ID를 찾을 수 없습니다")
return
}
if (!rfq?.vendorId) {
toast.error("협력업체 ID를 찾을 수 없습니다")
return
}
startSubmitTransition(async () => {
try {
// Pass both responseId and vendorId to the server action
const result = await updateCommercialResponse({
responseId,
vendorId: rfq.vendorId, // Include vendorId for revalidateTag
...formData,
})
if (!result.success) {
toast.error(result.error || "응답 제출 중 오류가 발생했습니다")
return
}
toast.success("Commercial response successfully submitted")
props.onOpenChange?.(false)
if (onSuccess) {
onSuccess()
}
} catch (error) {
console.error("Error submitting response:", error)
toast.error("응답 제출 중 오류가 발생했습니다")
}
})
}
return (
<Sheet {...props}>
<SheetContent className="flex flex-col gap-6 sm:max-w-md">
<SheetHeader className="text-left">
<SheetTitle>Commercial Response</SheetTitle>
<SheetDescription>
{rfq?.rfqCode && <span className="font-medium">{rfq.rfqCode}</span>}
<div className="mt-1">Please provide your commercial response for this RFQ</div>
</SheetDescription>
</SheetHeader>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col gap-4 overflow-y-auto max-h-[calc(100vh-200px)] pr-2"
>
<FormField
control={form.control}
name="responseStatus"
render={({ field }) => (
<FormItem>
<FormLabel>Response Status</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger className="capitalize">
<SelectValue placeholder="Select response status" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectGroup>
<SelectItem value="PENDING">Pending</SelectItem>
<SelectItem value="IN_PROGRESS">In Progress</SelectItem>
<SelectItem value="SUBMITTED">Submitted</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="totalPrice"
render={({ field }) => (
<FormItem>
<FormLabel>Total Price</FormLabel>
<FormControl>
<Input
type="number"
placeholder="0.00"
{...field}
value={field.value || ''}
onChange={(e) => {
const value = e.target.value === '' ? undefined : parseFloat(e.target.value);
field.onChange(value);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="currency"
render={({ field }) => (
<FormItem>
<FormLabel>Currency</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select currency" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectGroup>
<SelectItem value="USD">USD</SelectItem>
<SelectItem value="EUR">EUR</SelectItem>
<SelectItem value="GBP">GBP</SelectItem>
<SelectItem value="KRW">KRW</SelectItem>
<SelectItem value="JPY">JPY</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Other form fields remain the same */}
<FormField
control={form.control}
name="paymentTerms"
render={({ field }) => (
<FormItem>
<FormLabel>Payment Terms</FormLabel>
<FormControl>
<Input placeholder="e.g. Net 30" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="incoterms"
render={({ field }) => (
<FormItem>
<FormLabel>Incoterms</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value || ''}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select incoterms" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectGroup>
<SelectItem value="EXW">EXW (Ex Works)</SelectItem>
<SelectItem value="FCA">FCA (Free Carrier)</SelectItem>
<SelectItem value="FOB">FOB (Free On Board)</SelectItem>
<SelectItem value="CIF">CIF (Cost, Insurance & Freight)</SelectItem>
<SelectItem value="DAP">DAP (Delivered At Place)</SelectItem>
<SelectItem value="DDP">DDP (Delivered Duty Paid)</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="deliveryPeriod"
render={({ field }) => (
<FormItem>
<FormLabel>Delivery Period</FormLabel>
<FormControl>
<Input placeholder="e.g. 4-6 weeks" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="warrantyPeriod"
render={({ field }) => (
<FormItem>
<FormLabel>Warranty Period</FormLabel>
<FormControl>
<Input placeholder="e.g. 12 months" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="validityPeriod"
render={({ field }) => (
<FormItem>
<FormLabel>Validity Period</FormLabel>
<FormControl>
<Input placeholder="e.g. 30 days" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="priceBreakdown"
render={({ field }) => (
<FormItem>
<FormLabel>Price Breakdown (Optional)</FormLabel>
<FormControl>
<Textarea
placeholder="Enter price breakdown details here"
className="min-h-[100px]"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="commercialNotes"
render={({ field }) => (
<FormItem>
<FormLabel>Additional Notes (Optional)</FormLabel>
<FormControl>
<Textarea
placeholder="Any additional comments or notes"
className="min-h-[100px]"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<SheetFooter className="gap-2 pt-4 sm:space-x-0">
<SheetClose asChild>
<Button type="button" variant="outline">
Cancel
</Button>
</SheetClose>
<Button disabled={isSubmitting} type="submit">
{isSubmitting && (
<Loader
className="mr-2 size-4 animate-spin"
aria-hidden="true"
/>
)}
Submit Response
</Button>
</SheetFooter>
</form>
</Form>
)}
</SheetContent>
</Sheet>
)
}
|