summaryrefslogtreecommitdiff
path: root/lib/bidding/failure/biddings-closure-dialog.tsx
blob: 93ba0eda3223f55f2a5c079b7325939b18ba65d7 (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
// 폐찰하기 다이얼로그
"use client"

import { useState } from "react"
import { useSession } from "next-auth/react"
import { toast } from "sonner"
import { requestBiddingClosureWithApproval } from "@/lib/bidding/approval-actions"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { FileXIcon } from "lucide-react"

interface BiddingsClosureDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    bidding: {
      id: number;
      title: string;
      biddingNumber: string;
    } | null;
    onSuccess?: () => void;
    onApprovalPreview?: (data: {
      templateName: string
      variables: Record<string, string>
      title: string
      description: string
      files?: File[]
    }) => void
  }

interface ClosureFormData {
  description: string;
  files: File[];
}
  
  export function BiddingsClosureDialog({
    open,
    onOpenChange,
    bidding,
    onSuccess,
    onApprovalPreview
  }: BiddingsClosureDialogProps) {
    const { data: session } = useSession()
    const [description, setDescription] = useState('')
    const [files, setFiles] = useState<File[]>([])
    const [isSubmitting, setIsSubmitting] = useState(false)
  
    const handleSubmit = async (e: React.FormEvent) => {
      e.preventDefault()
  
      if (!bidding || !description.trim()) {
        toast.error('폐찰 사유를 입력해주세요.')
        return
      }
  
      // 결재 템플릿 변수 준비
      const { mapBiddingClosureToTemplateVariables } = await import('@/lib/bidding/handlers')

      try {
        const variables = await mapBiddingClosureToTemplateVariables({
          biddingId: bidding.id,
          description: description.trim(),
          requestedAt: new Date()
        })

        // 상위 컴포넌트로 결재 미리보기 데이터 전달
        if (onApprovalPreview) {
          onApprovalPreview({
            templateName: '폐찰 품의 요청서',
            variables,
            title: `폐찰 - ${bidding.title}`,
            description: description.trim(),
            files
          })
        }

        onOpenChange(false)
        // 폼 초기화
        setDescription('')
        setFiles([])
      } catch (error) {
        console.error('폐찰 템플릿 변수 준비 실패:', error)
        toast.error('결재 문서 준비 중 오류가 발생했습니다.')
      }
    }

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files) {
        setFiles(Array.from(e.target.files))
      }
    }


    if (!bidding) return null
  
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileXIcon className="h-5 w-5 text-destructive" />
              폐찰하기
            </DialogTitle>
            <DialogDescription>
              {bidding.title} ({bidding.biddingNumber})를 폐찰합니다.
            </DialogDescription>
          </DialogHeader>
  
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="description">폐찰 사유 <span className="text-destructive">*</span></Label>
              <Textarea
                id="description"
                placeholder="폐찰 사유를 입력해주세요..."
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="min-h-[100px]"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="files">첨부파일</Label>
              <Input
                id="files"
                type="file"
                multiple
                onChange={handleFileChange}
                className="cursor-pointer"
                accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.jpg,.jpeg,.png"
              />
              {files.length > 0 && (
                <div className="text-sm text-muted-foreground">
                  선택된 파일: {files.map(f => f.name).join(', ')}
                </div>
              )}
            </div>

            <div className="flex justify-end gap-2 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isSubmitting}
              >
                취소
              </Button>
              <Button
                type="submit"
                variant="destructive"
                disabled={isSubmitting || !description.trim()}
              >
                {isSubmitting ? '상신 중...' : '결재 상신'}
              </Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </>
  )