summaryrefslogtreecommitdiff
path: root/lib/bidding/selection/actions.ts
blob: 915509609e6d1ec6d796ac45d3bbbe0e394271a7 (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
"use server"

import db from "@/db/db"
import { eq, and, sql, isNull } from "drizzle-orm"
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
// @ts-ignore - Next.js cache import issue in server actions
const { revalidatePath } = require("next/cache")
import {
  biddings,
  biddingCompanies,
  prItemsForBidding,
  companyPrItemBids,
  vendors,
  generalContracts,
  generalContractItems,
  vendorSelectionResults,
  biddingDocuments
} from "@/db/schema"
import { saveFile } from '@/lib/file-stroage'

interface SaveSelectionResultData {
  biddingId: number
  summary: string
  attachments?: File[]
}

export async function saveSelectionResult(data: SaveSelectionResultData) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return {
        success: false,
        error: '인증되지 않은 사용자입니다.'
      }
    }

    // 기존 선정결과 확인 (selectedCompanyId가 null인 레코드)
    // 타입 에러를 무시하고 전체 조회 후 필터링
    const allResults = await db
      .select()
      .from(vendorSelectionResults)
      .where(eq(vendorSelectionResults.biddingId, data.biddingId))

    // @ts-ignore
    const existingResult = allResults.filter((result: any) => result.selectedCompanyId === null).slice(0, 1)

    const resultData = {
      biddingId: data.biddingId,
      selectedCompanyId: null, // 전체 선정결과
      selectionReason: '전체 선정결과',
      evaluationSummary: data.summary,
      hasResultDocuments: data.attachments && data.attachments.length > 0,
      selectedBy: session.user.id
    }

    let resultId: number

    if (existingResult.length > 0) {
      // 업데이트
      await db
        .update(vendorSelectionResults)
        .set({
          ...resultData,
          updatedAt: new Date()
        })
        .where(eq(vendorSelectionResults.id, existingResult[0].id))
      resultId = existingResult[0].id
    } else {
      // 새로 생성
      const insertResult = await db.insert(vendorSelectionResults).values(resultData).returning({ id: vendorSelectionResults.id })
      resultId = insertResult[0].id
    }

    // 첨부파일 처리
    if (data.attachments && data.attachments.length > 0) {
      // 기존 첨부파일 삭제 (documentType이 'selection_result'인 것들)
      await db
        .delete(biddingDocuments)
        .where(and(
          eq(biddingDocuments.biddingId, data.biddingId),
          eq(biddingDocuments.documentType, 'selection_result')
        ))

      // 새 첨부파일 저장
      const documentInserts: Array<typeof biddingDocuments.$inferInsert> = []
      
      for (const file of data.attachments) {
        // saveFile을 사용하여 파일 저장
        const saveResult = await saveFile({
          file,
          directory: `bidding/${data.biddingId}/selection`,
          originalName: file.name,
          userId: session.user.id
        })

        if (saveResult.success && saveResult.publicPath) {
          documentInserts.push({
            biddingId: data.biddingId,
            companyId: null,
            documentType: 'selection_result' as const,
            fileName: saveResult.fileName || file.name,
            originalFileName: saveResult.originalName || file.name,
            fileSize: saveResult.fileSize || file.size,
            mimeType: file.type,
            filePath: saveResult.publicPath,
            uploadedBy: session.user.id
          })
        } else {
          console.error('Failed to save file:', saveResult.error)
        }
      }

      if (documentInserts.length > 0) {
        await db.insert(biddingDocuments).values(documentInserts)
      }
    }

    revalidatePath(`/evcp/bid-selection/${data.biddingId}/detail`)

    return {
      success: true,
      message: '선정결과가 성공적으로 저장되었습니다.'
    }
  } catch (error) {
    console.error('Failed to save selection result:', error)
    return {
      success: false,
      error: '선정결과 저장 중 오류가 발생했습니다.'
    }
  }
}

// 선정결과 조회
export async function getSelectionResult(biddingId: number) {
  try {
    // 선정결과 조회 (selectedCompanyId가 null인 레코드)
    const allResults = await db
      .select()
      .from(vendorSelectionResults)
      .where(eq(vendorSelectionResults.biddingId, biddingId))

    // @ts-ignore
    const existingResult = allResults.filter((result: any) => result.selectedCompanyId === null).slice(0, 1)

    if (existingResult.length === 0) {
      return {
        success: true,
        data: {
          summary: '',
          attachments: []
        }
      }
    }

    const result = existingResult[0]

    // 첨부파일 조회
    const documents = await db
      .select({
        id: biddingDocuments.id,
        fileName: biddingDocuments.fileName,
        originalFileName: biddingDocuments.originalFileName,
        fileSize: biddingDocuments.fileSize,
        mimeType: biddingDocuments.mimeType,
        filePath: biddingDocuments.filePath,
        uploadedAt: biddingDocuments.uploadedAt
      })
      .from(biddingDocuments)
      .where(and(
        eq(biddingDocuments.biddingId, biddingId),
        eq(biddingDocuments.documentType, 'selection_result')
      ))

    return {
      success: true,
      data: {
        summary: result.evaluationSummary || '',
        attachments: documents.map(doc => ({
          id: doc.id,
          fileName: doc.fileName || doc.originalFileName || '',
          originalFileName: doc.originalFileName || '',
          fileSize: doc.fileSize || 0,
          mimeType: doc.mimeType || '',
          filePath: doc.filePath || '',
          uploadedAt: doc.uploadedAt
        }))
      }
    }
  } catch (error) {
    console.error('Failed to get selection result:', error)
    return {
      success: false,
      error: '선정결과 조회 중 오류가 발생했습니다.',
      data: {
        summary: '',
        attachments: []
      }
    }
  }
}

// 견적 히스토리 조회
export async function getQuotationHistory(biddingId: number, vendorId: number) {
  try {
    // 현재 bidding의 biddingNumber와 originalBiddingNumber 조회
    const currentBiddingInfo = await db
      .select({
        biddingNumber: biddings.biddingNumber,
        originalBiddingNumber: biddings.originalBiddingNumber
      })
      .from(biddings)
      .where(eq(biddings.id, biddingId))
      .limit(1)

    if (!currentBiddingInfo.length) {
      return {
        success: true,
        data: {
          history: []
        }
      }
    }

    const baseNumber = currentBiddingInfo[0].originalBiddingNumber || currentBiddingInfo[0].biddingNumber.split('-')[0]

    // 동일한 originalBiddingNumber를 가진 모든 bidding 조회
    const relatedBiddings = await db
      .select({
        id: biddings.id,
        biddingNumber: biddings.biddingNumber,
        targetPrice: biddings.targetPrice,
        currency: biddings.currency,
        createdAt: biddings.createdAt
      })
      .from(biddings)
      .where(eq(biddings.originalBiddingNumber, baseNumber))
      .orderBy(biddings.createdAt)

    // 각 bidding에 대한 벤더의 견적 정보 조회
    const historyPromises = relatedBiddings.map(async (bidding) => {
      const biddingCompanyData = await db
        .select({
          finalQuoteAmount: biddingCompanies.finalQuoteAmount,
          responseSubmittedAt: biddingCompanies.responseSubmittedAt,
          isFinalSubmission: biddingCompanies.isFinalSubmission
        })
        .from(biddingCompanies)
        .where(and(
          eq(biddingCompanies.biddingId, bidding.id),
          eq(biddingCompanies.companyId, vendorId)
        ))
        .limit(1)

      if (!biddingCompanyData.length || !biddingCompanyData[0].finalQuoteAmount || !biddingCompanyData[0].responseSubmittedAt) {
        return null
      }

      return {
        biddingId: bidding.id,
        biddingNumber: bidding.biddingNumber,
        finalQuoteAmount: biddingCompanyData[0].finalQuoteAmount,
        responseSubmittedAt: biddingCompanyData[0].responseSubmittedAt,
        isFinalSubmission: biddingCompanyData[0].isFinalSubmission,
        targetPrice: bidding.targetPrice,
        currency: bidding.currency
      }
    })

    const historyData = (await Promise.all(historyPromises)).filter(Boolean)

    // biddingNumber의 suffix를 기준으로 정렬 (-01, -02, -03 등)
    const sortedHistory = historyData.sort((a, b) => {
      const aSuffix = a!.biddingNumber.split('-')[1] ? parseInt(a!.biddingNumber.split('-')[1]) : 0
      const bSuffix = b!.biddingNumber.split('-')[1] ? parseInt(b!.biddingNumber.split('-')[1]) : 0
      return aSuffix - bSuffix
    })

    // PR 항목 정보 조회 (현재 bidding 기준)
    const prItems = await db
      .select({
        id: prItemsForBidding.id,
        itemNumber: prItemsForBidding.itemNumber,
        itemInfo: prItemsForBidding.itemInfo,
        quantity: prItemsForBidding.quantity,
        quantityUnit: prItemsForBidding.quantityUnit,
        requestedDeliveryDate: prItemsForBidding.requestedDeliveryDate
      })
      .from(prItemsForBidding)
      .where(eq(prItemsForBidding.biddingId, biddingId))

    // 각 히스토리 항목에 대한 PR 아이템 견적 조회
    const history = await Promise.all(sortedHistory.map(async (item, index) => {
      // 각 bidding에 대한 PR 아이템 견적 조회
      const prItemBids = await db
        .select({
          prItemId: companyPrItemBids.prItemId,
          bidUnitPrice: companyPrItemBids.bidUnitPrice,
          bidAmount: companyPrItemBids.bidAmount,
          proposedDeliveryDate: companyPrItemBids.proposedDeliveryDate
        })
        .from(companyPrItemBids)
        .where(and(
          eq(companyPrItemBids.biddingId, item!.biddingId),
          eq(companyPrItemBids.companyId, vendorId)
        ))

      const targetPrice = item!.targetPrice ? parseFloat(item!.targetPrice.toString()) : null
      const totalAmount = parseFloat(item!.finalQuoteAmount.toString())

      const vsTargetPrice = targetPrice && targetPrice > 0
        ? ((totalAmount - targetPrice) / targetPrice) * 100
        : 0

      const items = prItemBids.map(bid => {
        const prItem = prItems.find(p => p.id === bid.prItemId)
        return {
          itemCode: prItem?.itemNumber || `ITEM${bid.prItemId}`,
          itemName: prItem?.itemInfo || '품목 정보 없음',
          quantity: prItem?.quantity || 0,
          unit: prItem?.quantityUnit || 'EA',
          unitPrice: parseFloat(bid.bidUnitPrice.toString()),
          totalPrice: parseFloat(bid.bidAmount.toString()),
          deliveryDate: bid.proposedDeliveryDate ? new Date(bid.proposedDeliveryDate) : prItem?.requestedDeliveryDate ? new Date(prItem.requestedDeliveryDate) : new Date()
        }
      })

      return {
        id: item!.biddingId,
        round: index + 1, // 1차, 2차, 3차...
        submittedAt: new Date(item!.responseSubmittedAt),
        totalAmount,
        currency: item!.currency || 'KRW',
        vsTargetPrice: parseFloat(vsTargetPrice.toFixed(2)),
        items
      }
    }))

    return {
      success: true,
      data: {
        history
      }
    }
  } catch (error) {
    console.error('Failed to get quotation history:', error)
    return {
      success: false,
      error: '견적 히스토리 조회 중 오류가 발생했습니다.'
    }
  }
}