summaryrefslogtreecommitdiff
path: root/lib/bidding/bidding-notice-editor.tsx
blob: 8d0f1e35f85ec175d076ff6b831d0786e02caac5 (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
'use client'

import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useToast } from '@/hooks/use-toast'
import { Save, RefreshCw } from 'lucide-react'
import { BiddingNoticeTemplate } from '@/db/schema/bidding'
import { saveBiddingNoticeTemplate, saveBiddingNotice } from './service'
import TiptapEditor from '@/components/qna/tiptap-editor'

interface BiddingNoticeEditorProps {
  initialData: BiddingNoticeTemplate | null
  biddingId?: number // 입찰 ID (있으면 일반 입찰공고, 없으면 템플릿)
  templateType?: string // 템플릿 타입 (템플릿 저장 시 사용)
  onSaveSuccess?: () => void // 저장 성공 시 콜백
  onTemplateUpdate?: (template: BiddingNoticeTemplate) => void // 템플릿 업데이트 콜백
}

export function BiddingNoticeEditor({ initialData, biddingId, templateType, onSaveSuccess, onTemplateUpdate }: BiddingNoticeEditorProps) {
  const getDefaultTitle = (type?: string) => {
    switch (type) {
      case 'facility':
        return '시설재 입찰공고문'
      case 'unit_price':
        return '단가계약 입찰공고문'
      default:
        return '표준 입찰공고문'
    }
  }

  const [title, setTitle] = useState(initialData?.title || getDefaultTitle(templateType))
  const [content, setContent] = useState(initialData?.content || getDefaultTemplate())
  const [isPending, startTransition] = useTransition()
  const { toast } = useToast()
  const router = useRouter()

  const handleSave = () => {
    if (!title.trim()) {
      toast({
        title: '오류',
        description: '제목을 입력해주세요.',
        variant: 'destructive',
      })
      return
    }

    if (!content.trim()) {
      toast({
        title: '오류',
        description: '내용을 입력해주세요.',
        variant: 'destructive',
      })
      return
    }

    startTransition(async () => {
      try {
        if (biddingId) {
          // 일반 입찰공고 저장
          await saveBiddingNotice(biddingId, { title, content })
          toast({
            title: '성공',
            description: '입찰공고문이 저장되었습니다.',
          })
        } else {
          // 템플릿 저장
          if (!templateType) {
            toast({
              title: '오류',
              description: '템플릿 타입이 지정되지 않았습니다.',
              variant: 'destructive',
            })
            return
          }

          const savedTemplate = await saveBiddingNoticeTemplate({ title, content, type: templateType })
          toast({
            title: '성공',
            description: '입찰공고문 템플릿이 저장되었습니다.',
          })

          // 템플릿 업데이트 콜백 호출
          if (onTemplateUpdate && savedTemplate) {
            // 저장된 템플릿 데이터를 가져와서 콜백 호출
            const updatedTemplate = {
              ...initialData,
              title,
              content,
              type: templateType,
              updatedAt: new Date(),
            } as BiddingNoticeTemplate
            onTemplateUpdate(updatedTemplate)
          }
        }
        router.refresh()
        
        // 저장 성공 시 콜백 호출
        onSaveSuccess?.()
      } catch (error) {
        toast({
          title: '오류',
          description: error instanceof Error ? error.message : '저장에 실패했습니다.',
          variant: 'destructive',
        })
      }
    })
  }

  // const handleReset = () => {
  //   if (confirm('기본 템플릿으로 초기화하시겠습니까? 현재 내용은 삭제됩니다.')) {
  //     setTitle(getDefaultTitle(templateType))
  //     setContent(getDefaultTemplate())
  //     toast({
  //       title: '초기화 완료',
  //       description: '기본 템플릿으로 초기화되었습니다.',
  //     })
  //   }
  // }

  return (
    <div className="space-y-6">
      {/* 제목 입력 */}
      <div className="space-y-2">
        <Label htmlFor="title">템플릿 제목</Label>
        <Input
          id="title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder="입찰공고문 제목을 입력하세요"
          disabled={isPending}
        />
      </div>

      {/* 에디터 */}
      <div className="space-y-2">
        <Label>공고문 내용</Label>
        <div className="border rounded-lg">
          <TiptapEditor
            content={content}
            setContent={setContent}
            disabled={isPending}
            height="500px"
          />
        </div>
      </div>

      {/* 액션 버튼 */}
      <div className="flex items-center gap-4 pt-4">
        <Button 
          onClick={handleSave} 
          disabled={isPending}
          className="min-w-[120px]"
        >
          {isPending ? (
            <>
              <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
              저장 중...
            </>
          ) : (
            <>
              <Save className="w-4 h-4 mr-2" />
              저장
            </>
          )}
        </Button>
        
        {/* <Button 
          variant="outline" 
          onClick={handleReset}
          disabled={isPending}
        >
          기본 템플릿으로 초기화
        </Button> */}

        {initialData && (
          <div className="ml-auto text-sm text-muted-foreground">
            마지막 업데이트: {new Date(initialData.updatedAt).toLocaleString('ko-KR')}
          </div>
        )}
      </div>
    </div>
  )
}

// 기본 템플릿 함수
function getDefaultTemplate(): string {
  return `
<h1>입찰공고</h1>

<h2>1. 입찰 개요</h2>
<ul>
  <li><strong>공고명:</strong> [입찰 공고명을 입력하세요]</li>
  <li><strong>입찰방식:</strong> [일반경쟁입찰/제한경쟁입찰]</li>
  <li><strong>입찰공고번호:</strong> [공고번호]</li>
  <li><strong>공고일자:</strong> [YYYY년 MM월 DD일]</li>
</ul>

<h2>2. 입찰 참가자격</h2>
<ul>
  <li>관련 업종의 사업자등록증을 보유한 업체</li>
  <li>부가가치세법에 의한 사업자등록증을 보유한 업체</li>
  <li>기타 관련 법령에 따른 자격 요건을 갖춘 업체</li>
</ul>

<h2>3. 입찰 일정</h2>
<table>
  <thead>
    <tr>
      <th>구분</th>
      <th>일시</th>
      <th>장소</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>입찰 공고</td>
      <td>[YYYY.MM.DD]</td>
      <td>-</td>
    </tr>
    <tr>
      <td>현장설명</td>
      <td>[YYYY.MM.DD HH:MM]</td>
      <td>[현장 주소]</td>
    </tr>
    <tr>
      <td>입찰서 접수</td>
      <td>[YYYY.MM.DD HH:MM까지]</td>
      <td>[접수 장소]</td>
    </tr>
    <tr>
      <td>개찰</td>
      <td>[YYYY.MM.DD HH:MM]</td>
      <td>[개찰 장소]</td>
    </tr>
  </tbody>
</table>

<h2>4. 입찰 대상</h2>
<ul>
  <li><strong>사업명:</strong> [사업명을 입력하세요]</li>
  <li><strong>사업내용:</strong> [상세 사업내용]</li>
  <li><strong>사업기간:</strong> [계약일로부터 OO일 이내]</li>
  <li><strong>사업장소:</strong> [사업 수행 장소]</li>
</ul>

<h2>5. 제출 서류</h2>
<ul>
  <li>입찰서 및 투찰서</li>
  <li>사업자등록증 사본</li>
  <li>법인등기부등본 (법인의 경우)</li>
  <li>업체현황서</li>
  <li>기타 입찰 참가자격 증명서류</li>
</ul>

<h2>6. 기타 사항</h2>
<ul>
  <li>본 입찰공고에 명시되지 않은 사항은 관련 법령에 따릅니다.</li>
  <li>기타 문의사항은 아래 연락처로 문의하시기 바랍니다.</li>
</ul>

<blockquote>
<p><strong>문의처:</strong><br>
담당자: [담당자명]<br>
전화: [전화번호]<br>
이메일: [이메일주소]</p>
</blockquote>
  `.trim()
}