summaryrefslogtreecommitdiff
path: root/lib/rfqs/table/add-rfq-dialog.tsx
blob: 45390cd068a66410d464b53752995f36c7a29f5f (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
"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Check, ChevronsUpDown } from "lucide-react"
import { toast } from "sonner"

import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from "@/components/ui/command"

import { useSession } from "next-auth/react"
import { createRfqSchema, type CreateRfqSchema, RfqType } from "../validations"
import { createRfq, getBudgetaryRfqs } from "../service"
import { ProjectSelector } from "@/components/ProjectSelector"
import { type Project } from "../service"
import { cn } from "@/lib/utils"
import { BudgetaryRfqSelector } from "./BudgetaryRfqSelector"
import { type BudgetaryRfq as ServiceBudgetaryRfq } from "../service";

// 부모 RFQ 정보 타입 정의
interface BudgetaryRfq {
  id: number;
  rfqCode: string;
  description: string | null;
}

interface AddRfqDialogProps {
  rfqType?: RfqType;
}

export function AddRfqDialog({ rfqType = RfqType.PURCHASE }: AddRfqDialogProps) {
  const [open, setOpen] = React.useState(false)
  const { data: session, status } = useSession()
  const [budgetaryRfqs, setBudgetaryRfqs] = React.useState<BudgetaryRfq[]>([])
  const [isLoadingBudgetary, setIsLoadingBudgetary] = React.useState(false)
  const [budgetarySearchOpen, setBudgetarySearchOpen] = React.useState(false)
  const [budgetarySearchTerm, setBudgetarySearchTerm] = React.useState("")
  const [selectedBudgetaryRfq, setSelectedBudgetaryRfq] = React.useState<BudgetaryRfq | null>(null)

  // Get the user ID safely, ensuring it's a valid number
  const userId = React.useMemo(() => {
    const id = session?.user?.id ? Number(session.user.id) : null;
    
    // Debug logging - remove in production
    console.log("Session status:", status);
    console.log("Session data:", session);
    console.log("User ID:", id);
    
    return id;
  }, [session, status]);

  // RfqType에 따른 타이틀 생성
  const getTitle = () => {
    return rfqType === RfqType.PURCHASE
      ? "Purchase RFQ"
      : "Budgetary RFQ";
  };

  // RHF + Zod
  const form = useForm<CreateRfqSchema>({
    resolver: zodResolver(createRfqSchema),
    defaultValues: {
      rfqCode: "",
      description: "",
      projectId: undefined,
      parentRfqId: undefined,
      dueDate: new Date(),
      status: "DRAFT",
      rfqType: rfqType,
      // Don't set createdBy yet - we'll set it when the form is submitted
      createdBy: undefined,
    },
  });

  // Update form values when session loads
  React.useEffect(() => {
    if (status === "authenticated" && userId) {
      form.setValue("createdBy", userId);
    }
  }, [status, userId, form]);

  // Budgetary RFQ 목록 로드 (Purchase RFQ 생성 시만)
  React.useEffect(() => {
    if (rfqType === RfqType.PURCHASE && open) {
      const loadBudgetaryRfqs = async () => {
        setIsLoadingBudgetary(true);
        try {
          const result = await getBudgetaryRfqs();
          if ('rfqs' in result) {
            setBudgetaryRfqs(result.rfqs as unknown as BudgetaryRfq[]);
          } else if ('error' in result) {
            console.error("Budgetary RFQs 로드 오류:", result.error);
          }
        } catch (error) {
          console.error("Budgetary RFQs 로드 오류:", error);
        } finally {
          setIsLoadingBudgetary(false);
        }
      };

      loadBudgetaryRfqs();
    }
  }, [rfqType, open]);

  // 검색어로 필터링된 Budgetary RFQ 목록
  const filteredBudgetaryRfqs = React.useMemo(() => {
    if (!budgetarySearchTerm.trim()) return budgetaryRfqs;

    const lowerSearch = budgetarySearchTerm.toLowerCase();
    return budgetaryRfqs.filter(
      rfq =>
        rfq.rfqCode.toLowerCase().includes(lowerSearch) ||
        (rfq.description && rfq.description.toLowerCase().includes(lowerSearch))
    );
  }, [budgetaryRfqs, budgetarySearchTerm]);

  // 프로젝트 선택 처리
  const handleProjectSelect = (project: Project | null) => {
    if (project === null) {
      return;
    }

    form.setValue("projectId", project.id);
  };

  // Budgetary RFQ 선택 처리
  const handleBudgetaryRfqSelect = (rfq: BudgetaryRfq) => {
    setSelectedBudgetaryRfq(rfq);
    form.setValue("parentRfqId", rfq.id);
    setBudgetarySearchOpen(false);
  };

  async function onSubmit(data: CreateRfqSchema) {
    // Check if user is authenticated before submitting
    if (status !== "authenticated" || !userId) {
      toast.error("사용자 인증이 필요합니다. 다시 로그인해주세요.");
      return;
    }

    // Make sure createdBy is set with the current user ID
    const submitData = {
      ...data,
      createdBy: userId
    };

    console.log("Submitting form data:", submitData);

    const result = await createRfq(submitData);
    if (result.error) {
      toast.error(`에러: ${result.error}`);
      return;
    }
    
    toast.success("RFQ가 성공적으로 생성되었습니다.");
    form.reset();
    setSelectedBudgetaryRfq(null);
    setOpen(false);
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    if (!nextOpen) {
      form.reset();
      setSelectedBudgetaryRfq(null);
    }
    setOpen(nextOpen);
  }

  // Return a message or disabled state if user is not authenticated
  if (status === "loading") {
    return <Button variant="outline" size="sm" disabled>Loading...</Button>;
  }

  return (
    <Dialog open={open} onOpenChange={handleDialogOpenChange}>
      {/* 모달을 열기 위한 버튼 */}
      <DialogTrigger asChild>
        <Button variant="default" size="sm">
          Add {getTitle()}
        </Button>
      </DialogTrigger>

      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create New {getTitle()}</DialogTitle>
          <DialogDescription>
            새 {getTitle()} 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="space-y-4 py-4">
              {/* rfqType - hidden field */}
              <FormField
                control={form.control}
                name="rfqType"
                render={({ field }) => (
                  <input type="hidden" {...field} />
                )}
              />

              {/* Project Selector */}
              <FormField
                control={form.control}
                name="projectId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Project</FormLabel>
                    <FormControl>
                      <ProjectSelector
                        selectedProjectId={field.value}
                        onProjectSelect={handleProjectSelect}
                        placeholder="프로젝트 선택..."
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Budgetary RFQ Selector - 구매용 RFQ 생성 시에만 표시 */}
              {rfqType === RfqType.PURCHASE && (
                <FormField
                  control={form.control}
                  name="parentRfqId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Budgetary RFQ (Optional)</FormLabel>
                      <FormControl>
                        <BudgetaryRfqSelector
                          selectedRfqId={field.value as number | undefined}
                          onRfqSelect={(rfq) => {
                            setSelectedBudgetaryRfq(rfq as any);
                            form.setValue("parentRfqId", rfq?.id);
                          }}
                          placeholder="Budgetary RFQ 선택..."
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}

              {/* rfqCode */}
              <FormField
                control={form.control}
                name="rfqCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>RFQ Code</FormLabel>
                    <FormControl>
                      <Input placeholder="e.g. RFQ-2025-001" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* description */}
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>RFQ Description</FormLabel>
                    <FormControl>
                      <Input placeholder="e.g. 설명을 입력하세요" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* dueDate */}
              <FormField
                control={form.control}
                name="dueDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Due Date</FormLabel>
                    <FormControl>
                      <Input
                        type="date"
                        value={field.value ? field.value.toISOString().slice(0, 10) : ""}
                        onChange={(e) => {
                          const val = e.target.value
                          if (val) {
                            field.onChange(new Date(val + "T00:00:00"))
                          }
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* status (Read-only) */}
              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Status</FormLabel>
                    <FormControl>
                      <Input
                        disabled
                        className="capitalize"
                        {...field}
                        onChange={() => {}} // Prevent changes
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setOpen(false)}
              >
                Cancel
              </Button>
              <Button 
                type="submit" 
                disabled={form.formState.isSubmitting || status !== "authenticated"}
              >
                Create
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}