From 10f90dc68dec42e9a64e081cc0dce6a484447290 Mon Sep 17 00:00:00 2001
From: dujinkim <dujin.kim@dtsolution.co.kr>
Date: Tue, 29 Jul 2025 11:48:59 +0000
Subject: (대표님, 박서영, 최겸) document-list-only, gtc, vendorDocu,
 docu-list-rule
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../status/create-gtc-document-dialog.tsx          | 98 +++++++++++++++++-----
 1 file changed, 75 insertions(+), 23 deletions(-)

(limited to 'lib/gtc-contract/status/create-gtc-document-dialog.tsx')

diff --git a/lib/gtc-contract/status/create-gtc-document-dialog.tsx b/lib/gtc-contract/status/create-gtc-document-dialog.tsx
index 003e4d51..174bb8dd 100644
--- a/lib/gtc-contract/status/create-gtc-document-dialog.tsx
+++ b/lib/gtc-contract/status/create-gtc-document-dialog.tsx
@@ -41,28 +41,45 @@ import { cn } from "@/lib/utils"
 import { toast } from "sonner"
 
 import { createGtcDocumentSchema, type CreateGtcDocumentSchema } from "@/lib/gtc-contract/validations"
-import { createGtcDocument, getProjectsForSelect } from "@/lib/gtc-contract/service"
-import { type Project } from "@/db/schema/projects"
+import { createGtcDocument, getAvailableProjectsForGtc, hasStandardGtcDocument } from "@/lib/gtc-contract/service"
+import { type ProjectForFilter } from "@/lib/gtc-contract/service"
 import { useSession } from "next-auth/react"
 import { Input } from "@/components/ui/input"
-import { useRouter } from "next/navigation";
+import { useRouter } from "next/navigation"
 
 export function CreateGtcDocumentDialog() {
   const [open, setOpen] = React.useState(false)
-  const [projects, setProjects] = React.useState<Project[]>([])
+  const [projects, setProjects] = React.useState<ProjectForFilter[]>([])
   const [isCreatePending, startCreateTransition] = React.useTransition()
+  const [defaultType, setDefaultType] = React.useState<"standard" | "project">("standard")
   const { data: session } = useSession()
-  const router = useRouter();
+  const router = useRouter()
 
   const currentUserId = React.useMemo(() => {
     return session?.user?.id ? Number(session.user.id) : null;
-  }, [session]);
-
+  }, [session])
 
   React.useEffect(() => {
     if (open) {
-      getProjectsForSelect().then((res) => {
-        setProjects(res)
+      // 표준 GTC 존재 여부와 사용 가능한 프로젝트 동시 조회
+      Promise.all([
+        hasStandardGtcDocument(),
+        getAvailableProjectsForGtc()
+      ]).then(([hasStandard, availableProjects]) => {
+        const initialType = hasStandard ? "project" : "standard"
+        setDefaultType(initialType)
+        setProjects(availableProjects)
+        
+        // 폼 기본값 설정 (setTimeout으로 다음 틱에 실행)
+        setTimeout(() => {
+          form.reset({
+            type: initialType,
+            projectId: null,
+            title: "",
+            revision: 0,
+            editReason: "",
+          })
+        }, 0)
       })
     }
   }, [open])
@@ -78,11 +95,21 @@ export function CreateGtcDocumentDialog() {
     },
   })
 
+  const resetForm = React.useCallback((type: "standard" | "project") => {
+    form.reset({
+      type,
+      projectId: null,
+      title: "",
+      revision: 0,
+      editReason: "",
+    })
+  }, [form])
+
+
   const watchedType = form.watch("type")
 
   async function onSubmit(data: CreateGtcDocumentSchema) {
     startCreateTransition(async () => {
-
       if (!currentUserId) {
         toast.error("로그인이 필요합니다")
         return
@@ -99,9 +126,9 @@ export function CreateGtcDocumentDialog() {
           return
         }
 
-        form.reset()
+        resetForm(defaultType)
         setOpen(false)
-        router.refresh();
+        router.refresh()
 
         toast.success("GTC 문서가 생성되었습니다.")
       } catch (error) {
@@ -112,7 +139,7 @@ export function CreateGtcDocumentDialog() {
 
   function handleDialogOpenChange(nextOpen: boolean) {
     if (!nextOpen) {
-      form.reset()
+      resetForm(defaultType)
     }
     setOpen(nextOpen)
   }
@@ -122,15 +149,15 @@ export function CreateGtcDocumentDialog() {
       <DialogTrigger asChild>
         <Button variant="default" size="sm">
           <Plus className="mr-2 h-4 w-4" />
-          Add GTC Document
+          GTC 추가
         </Button>
       </DialogTrigger>
 
       <DialogContent className="max-w-md">
         <DialogHeader>
-          <DialogTitle>Create New GTC Document</DialogTitle>
+          <DialogTitle>새 GTC 만들기</DialogTitle>
           <DialogDescription>
-            새 GTC 문서 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
+            새 GTC 문서 정보를 입력하고 <b>생성</b> 버튼을 누르세요.
           </DialogDescription>
         </DialogHeader>
 
@@ -159,11 +186,26 @@ export function CreateGtcDocumentDialog() {
                           <SelectValue placeholder="구분을 선택하세요" />
                         </SelectTrigger>
                         <SelectContent>
-                          <SelectItem value="standard">표준</SelectItem>
-                          <SelectItem value="project">프로젝트</SelectItem>
+                          {/* 기본값에 따라 순서 조정 */}
+                          {defaultType === "project" ? (
+                            <>
+                              <SelectItem value="project">프로젝트</SelectItem>
+                              <SelectItem value="standard">표준</SelectItem>
+                            </>
+                          ) : (
+                            <>
+                              <SelectItem value="standard">표준</SelectItem>
+                              <SelectItem value="project">프로젝트</SelectItem>
+                            </>
+                          )}
                         </SelectContent>
                       </Select>
                     </FormControl>
+                    {defaultType === "project" && (
+                      <FormDescription>
+                        표준 GTC 문서가 이미 존재합니다. 새 문서는 프로젝트 타입을 권장합니다.
+                      </FormDescription>
+                    )}
                     <FormMessage />
                   </FormItem>
                 )}
@@ -198,7 +240,9 @@ export function CreateGtcDocumentDialog() {
                               >
                                 {selectedProject
                                   ? `${selectedProject.name} (${selectedProject.code})`
-                                  : "프로젝트를 선택하세요..."}
+                                  : projects.length === 0 
+                                    ? "사용 가능한 프로젝트가 없습니다"
+                                    : "프로젝트를 선택하세요..."}
                                 <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                               </Button>
                             </PopoverTrigger>
@@ -210,7 +254,12 @@ export function CreateGtcDocumentDialog() {
                                   className="h-9"
                                 />
                                 <CommandList>
-                                  <CommandEmpty>프로젝트를 찾을 수 없습니다.</CommandEmpty>
+                                  <CommandEmpty>
+                                    {projects.length === 0 
+                                      ? "모든 프로젝트에 이미 GTC 문서가 있습니다."
+                                      : "프로젝트를 찾을 수 없습니다."
+                                    }
+                                  </CommandEmpty>
                                   <CommandGroup>
                                     {projects.map((project) => {
                                       const label = `${project.name} (${project.code})`
@@ -241,6 +290,9 @@ export function CreateGtcDocumentDialog() {
                             </PopoverContent>
                           </Popover>
                         </FormControl>
+                        <FormDescription>
+                          {projects.length === 0 && "이미 GTC 문서가 있는 프로젝트는 표시되지 않습니다."}
+                        </FormDescription>
                         <FormMessage />
                       </FormItem>
                     )
@@ -256,7 +308,7 @@ export function CreateGtcDocumentDialog() {
                     <FormLabel>GTC 제목 (선택사항)</FormLabel>
                     <FormControl>
                       <Input
-                        placeholder="GTC 제목를 입력하세요..."
+                        placeholder="GTC 제목을 입력하세요..."
                         {...field}
                       />
                     </FormControl>
@@ -295,7 +347,7 @@ export function CreateGtcDocumentDialog() {
                 onClick={() => setOpen(false)}
                 disabled={isCreatePending}
               >
-                Cancel
+                취소
               </Button>
               <Button type="submit" disabled={isCreatePending}>
                 {isCreatePending && (
@@ -304,7 +356,7 @@ export function CreateGtcDocumentDialog() {
                     aria-hidden="true"
                   />
                 )}
-                Create
+                생성
               </Button>
             </DialogFooter>
           </form>
-- 
cgit v1.2.3

