summaryrefslogtreecommitdiff
path: root/lib/pq/pq-review-table-new/request-investigation-dialog.tsx
blob: f5a7ff918fa20a7de32a67f5e6e77ed4a6b31a0c (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
"use client"

import * as React from "react"
import { CalendarIcon } from "lucide-react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { z } from "zod"

import { Button } from "@/components/ui/button"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"
import { Calendar } from "@/components/ui/calendar"
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover"
import { UserCombobox } from "./user-combobox"
import { getQMManagers } from "@/lib/pq/service"

// QM 사용자 타입
interface QMUser {
    id: number
    name: string
    email: string
    department?: string
}

const requestInvestigationFormSchema = z.object({
    qmManagerId: z.number({
        required_error: "QM 담당자를 선택해주세요.",
    }),
    forecastedAt: z.date({
        required_error: "실사 수행 예정일을 선택해주세요.",
    }),
    investigationAddress: z.string().min(1, "실사 장소를 입력해주세요."),
    investigationMethod: z.string().optional(),
    investigationNotes: z.string().min(1, "실사 목적을 입력해주세요."),
})

type RequestInvestigationFormValues = z.infer<typeof requestInvestigationFormSchema>

interface RequestInvestigationDialogProps {
    isOpen: boolean
    onClose: () => void
    onSubmit: (data: {
        qmManagerId: number,
        forecastedAt: Date,
        investigationAddress: string,
        investigationMethod?: string,
        investigationNotes?: string
    }) => Promise<void>
    selectedCount: number
    // 선택된 행에서 가져온 초기값
    initialData?: {
        qmManagerId?: number,
        forecastedAt?: Date,
        investigationAddress?: string,
        investigationMethod?: string,
        investigationNotes?: string
    }
}

export function RequestInvestigationDialog({
    isOpen,
    onClose,
    onSubmit,
    selectedCount,
    initialData,
}: RequestInvestigationDialogProps) {
    const [isPending, setIsPending] = React.useState(false)
    const [qmManagers, setQMManagers] = React.useState<QMUser[]>([])
    const [isLoadingManagers, setIsLoadingManagers] = React.useState(false)

    // form 객체 생성 시 initialData 활용
    const form = useForm<RequestInvestigationFormValues>({
        resolver: zodResolver(requestInvestigationFormSchema),
        defaultValues: {
            qmManagerId: initialData?.qmManagerId || undefined,
            forecastedAt: initialData?.forecastedAt || undefined,
            investigationAddress: initialData?.investigationAddress || "",
            investigationMethod: initialData?.investigationMethod || "",
            investigationNotes: initialData?.investigationNotes || "",
        },
    })

    // Dialog가 열릴 때마다 초기값으로 폼 재설정
    React.useEffect(() => {
        if (isOpen) {
            form.reset({
                qmManagerId: initialData?.qmManagerId || undefined,
                forecastedAt: initialData?.forecastedAt || undefined,
                investigationAddress: initialData?.investigationAddress || "",
                investigationMethod: initialData?.investigationMethod || "",
                investigationNotes: initialData?.investigationNotes || "",
            });
        }
    }, [isOpen, initialData, form]);

    // Dialog가 열릴 때 QM 담당자 목록 로드
    React.useEffect(() => {
        if (isOpen && qmManagers.length === 0) {
            const loadQMManagers = async () => {
                setIsLoadingManagers(true)
                try {
                    const result = await getQMManagers()
                    if (result.success && result.data) {
                        setQMManagers(result.data)
                    }
                } catch (error) {
                    console.error("QM 담당자 로드 오류:", error)
                } finally {
                    setIsLoadingManagers(false)
                }
            }

            loadQMManagers()
        }
    }, [isOpen, qmManagers.length])

    async function handleSubmit(data: RequestInvestigationFormValues) {
        setIsPending(true)
        try {
            await onSubmit(data)
        } finally {
            setIsPending(false)
            form.reset()
        }
    }

    return (
        <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
            <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                    <DialogTitle>실사 의뢰</DialogTitle>
                    <DialogDescription>
                        {selectedCount}개 협력업체에 대한 실사를 의뢰합니다. 실사 관련 정보를 입력해주세요.
                    </DialogDescription>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">

                        <FormField
                            control={form.control}
                            name="qmManagerId"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>QM 담당자</FormLabel>
                                    <FormControl>
                                        <UserCombobox
                                            users={qmManagers}
                                            value={field.value}
                                            onChange={field.onChange}
                                            placeholder={isLoadingManagers ? "담당자 로딩 중..." : "담당자 선택..."}
                                            disabled={isPending || isLoadingManagers}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="forecastedAt"
                            render={({ field }) => (
                                <FormItem className="flex flex-col">
                                    <FormLabel>실사 수행 예정일</FormLabel>
                                    <Popover>
                                        <PopoverTrigger asChild>
                                            <FormControl>
                                                <Button
                                                    variant={"outline"}
                                                    className={`w-full pl-3 text-left font-normal ${!field.value && "text-muted-foreground"}`}
                                                    disabled={isPending}
                                                >
                                                    {field.value ? (
                                                        format(field.value, "yyyy년 MM월 dd일")
                                                    ) : (
                                                        <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}
                                                onSelect={field.onChange}
                                                disabled={(date) => date < new Date()}
                                                initialFocus
                                            />
                                        </PopoverContent>
                                    </Popover>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="investigationAddress"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>실사 장소</FormLabel>
                                    <FormControl>
                                        <Textarea 
                                            placeholder="실사가 진행될 주소를 입력하세요" 
                                            {...field} 
                                            disabled={isPending}
                                            className="min-h-[60px]"
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        {/* <FormField
                            control={form.control}
                            name="investigationMethod"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>실사 방법 (선택사항)</FormLabel>
                                    <FormControl>
                                        <Input 
                                            placeholder="실사 방법을 입력하세요" 
                                            {...field} 
                                            disabled={isPending} 
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        /> */}

                        <FormField
                            control={form.control}
                            name="investigationNotes"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>실사목적</FormLabel>
                                    <FormControl>
                                        <Textarea
                                            placeholder="실사 목적을 입력하세요"
                                            className="resize-none min-h-[60px]"
                                            {...field}
                                            disabled={isPending}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <DialogFooter>
                            <Button
                                type="button"
                                variant="outline"
                                onClick={onClose}
                                disabled={isPending}
                            >
                                취소
                            </Button>
                            <Button type="submit" disabled={isPending || isLoadingManagers}>
                                {isPending ? "처리 중..." : "실사 의뢰"}
                            </Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    )
}