summaryrefslogtreecommitdiff
path: root/lib/tbe-last/vendor-tbe-service.ts
blob: 8335eb4f012707dcc51c92c1a3da266aac129ef1 (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
353
354
355
// lib/vendor-rfq-response/vendor-tbe-service-simplified.ts

'use server'

import { unstable_cache } from "next/cache"
import db from "@/db/db"
import { and, desc, asc, eq, sql, or } from "drizzle-orm"
import { tbeLastView, rfqLastTbeSessions } from "@/db/schema"
import { rfqPrItems } from "@/db/schema/rfqLast"
import { getServerSession } from "next-auth"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
import { revalidateTag } from "next/cache"
// ==========================================
// 간단한 벤더 Q&A 타입 정의
// ==========================================
export interface VendorQuestion {
  id: string // UUID
  category: "general" | "technical" | "commercial" | "delivery" | "quality" | "document" | "clarification"
  question: string
  askedAt: string
  askedBy: number
  askedByName?: string
  answer?: string
  answeredAt?: string
  answeredBy?: number
  answeredByName?: string
  status: "open" | "answered" | "closed"
  priority?: "high" | "normal" | "low"
  attachments?: string[] // 파일 경로들
}

// ==========================================
// 1. 벤더용 TBE 세션 목록 조회 (기존 뷰 활용)
// ==========================================
export async function getTBEforVendor(
  input: any,
  vendorId: number
) {
  return unstable_cache(
    async () => {
      const offset = ((input.page ?? 1) - 1) * (input.perPage ?? 10)
      const limit = input.perPage ?? 10

      // 벤더 필터링
      const vendorWhere = eq(tbeLastView.vendorId, vendorId)

      // 데이터 조회
      const [rows, total] = await db.transaction(async (tx) => {
        const data = await tx
          .select()
          .from(tbeLastView)
          .where(vendorWhere)
          .orderBy(desc(tbeLastView.createdAt))
          .offset(offset)
          .limit(limit)

        const [{ count }] = await tx
          .select({ count: sql<number>`count(*)`.as("count") })
          .from(tbeLastView)
          .where(vendorWhere)

        return [data, Number(count)]
      })

      const pageCount = Math.ceil(total / limit)
      return { data: rows, pageCount }
    },
    [`vendor-tbe-sessions-${vendorId}`, JSON.stringify(input)],
    {
      revalidate: 60,
      tags: [`vendor-tbe-sessions-${vendorId}`],
    }
  )()
}

// ==========================================
// 2. 벤더 질문/코멘트 추가 (기존 필드 활용)
// ==========================================
export async function addVendorQuestion(
  sessionId: number,
  vendorId: number,
  question: Omit<VendorQuestion, "id" | "askedAt">
) {
  const session = await getServerSession(authOptions)
  if (!session?.user) {
    throw new Error("인증이 필요합니다")
  }
  
  const userId = typeof session.user.id === 'string' ? parseInt(session.user.id) : session.user.id
  
  // 권한 체크
  const [tbeSession] = await db
    .select()
    .from(rfqLastTbeSessions)
    .where(
      and(
        eq(rfqLastTbeSessions.id, sessionId),
        eq(rfqLastTbeSessions.vendorId, vendorId)
      )
    )
    .limit(1)
  
  if (!tbeSession) {
    throw new Error("권한이 없습니다")
  }
  
  // 기존 질문 로그 가져오기
  const existingQuestions = tbeSession.vendorQuestionsLog || []
  
  // 새 질문 추가
  const newQuestion: VendorQuestion = {
    id: crypto.randomUUID(),
    ...question,
    askedAt: new Date().toISOString(),
    askedBy: userId,
    status: "open"
  }
  
  // 업데이트
  const [updated] = await db
    .update(rfqLastTbeSessions)
    .set({
      vendorQuestionsLog: [...existingQuestions, newQuestion],
      vendorRemarks: tbeSession.vendorRemarks 
        ? `${tbeSession.vendorRemarks}\n\n[${new Date().toLocaleString()}] ${question.question}`
        : `[${new Date().toLocaleString()}] ${question.question}`,
      updatedAt: new Date(),
      updatedBy: userId
    })
    .where(eq(rfqLastTbeSessions.id, sessionId))
    .returning()
  
  // 캐시 무효화
  revalidateTag(`vendor-tbe-sessions-${vendorId}`)
  revalidateTag(`tbe-session-${sessionId}`)
  
  return newQuestion
}

// ==========================================
// 3. 구매자가 답변 추가
// ==========================================
export async function answerVendorQuestion(
  sessionId: number,
  questionId: string,
  answer: string
) {
  const session = await getServerSession(authOptions)
  if (!session?.user) {
    throw new Error("인증이 필요합니다")
  }
  
  const userId = typeof session.user.id === 'string' ? parseInt(session.user.id) : session.user.id
  
  // TBE 세션 조회
  const [tbeSession] = await db
    .select()
    .from(rfqLastTbeSessions)
    .where(eq(rfqLastTbeSessions.id, sessionId))
    .limit(1)
  
  if (!tbeSession) {
    throw new Error("세션을 찾을 수 없습니다")
  }
  
  // 질문 로그 업데이트
  const questions = (tbeSession.vendorQuestionsLog || []) as VendorQuestion[]
  const updatedQuestions = questions.map(q => {
    if (q.id === questionId) {
      return {
        ...q,
        answer,
        answeredAt: new Date().toISOString(),
        answeredBy: userId,
        status: "answered" as const
      }
    }
    return q
  })
  
  // 업데이트
  const [updated] = await db
    .update(rfqLastTbeSessions)
    .set({
      vendorQuestionsLog: updatedQuestions,
      updatedAt: new Date(),
      updatedBy: userId
    })
    .where(eq(rfqLastTbeSessions.id, sessionId))
    .returning()
  
  // 캐시 무효화
  revalidateTag(`tbe-session-${sessionId}`)
  
  return updated
}

// ==========================================
// 4. 벤더 질문 목록 조회
// ==========================================
export async function getVendorQuestions(
  sessionId: number,
  vendorId: number
): Promise<VendorQuestion[]> {
  // 권한 체크
  const [tbeSession] = await db
    .select()
    .from(rfqLastTbeSessions)
    .where(
      and(
        eq(rfqLastTbeSessions.id, sessionId),
        eq(rfqLastTbeSessions.vendorId, vendorId)
      )
    )
    .limit(1)
  
  if (!tbeSession) {
    return []
  }
  
  return (tbeSession.vendorQuestionsLog || []) as VendorQuestion[]
}

// ==========================================
// 5. 벤더 의견 업데이트 (간단한 텍스트)
// ==========================================
export async function updateVendorRemarks(
  sessionId: number,
  vendorId: number,
  remarks: string
) {
  const session = await getServerSession(authOptions)
  if (!session?.user) {
    throw new Error("인증이 필요합니다")
  }
  
  const userId = typeof session.user.id === 'string' ? parseInt(session.user.id) : session.user.id
  
  // 권한 체크
  const [tbeSession] = await db
    .select()
    .from(rfqLastTbeSessions)
    .where(
      and(
        eq(rfqLastTbeSessions.id, sessionId),
        eq(rfqLastTbeSessions.vendorId, vendorId)
      )
    )
    .limit(1)
  
  if (!tbeSession) {
    throw new Error("권한이 없습니다")
  }
  
  // 업데이트
  const [updated] = await db
    .update(rfqLastTbeSessions)
    .set({
      vendorRemarks: remarks,
      updatedAt: new Date(),
      updatedBy: userId
    })
    .where(eq(rfqLastTbeSessions.id, sessionId))
    .returning()
  
  // 캐시 무효화
  revalidateTag(`vendor-tbe-sessions-${vendorId}`)
  revalidateTag(`tbe-session-${sessionId}`)
  
  return updated
}

// ==========================================
// 6. 통계 조회
// ==========================================
export async function getVendorQuestionStats(sessionId: number) {
  const [tbeSession] = await db
    .select()
    .from(rfqLastTbeSessions)
    .where(eq(rfqLastTbeSessions.id, sessionId))
    .limit(1)
  
  if (!tbeSession) {
    return {
      total: 0,
      open: 0,
      answered: 0,
      closed: 0
    }
  }
  
  const questions = (tbeSession.vendorQuestionsLog || []) as VendorQuestion[]
  
  return {
    total: questions.length,
    open: questions.filter(q => q.status === "open").length,
    answered: questions.filter(q => q.status === "answered").length,
    closed: questions.filter(q => q.status === "closed").length,
    highPriority: questions.filter(q => q.priority === "high").length
  }
}


// ==========================================
// 6. PR 아이템 조회 (벤더용)
// ==========================================
export async function getVendorPrItems(
    rfqId: number
  ) {

    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
        throw new Error("로그인이 필요합니다.");
      }

    const vendorId = session.user.companyId

    // RFQ가 해당 벤더의 것인지 체크
    const [tbeSession] = await db
      .select()
      .from(tbeLastView)
      .where(
        and(
          eq(tbeLastView.rfqId, rfqId),
          eq(tbeLastView.vendorId, vendorId)
        )
      )
      .limit(1)
    
    if (!tbeSession) {
      return []
    }
    
    // PR 아이템 조회
    const prItems = await db
      .select({
        id: rfqPrItems.id,
        prNo: rfqPrItems.prNo,
        prItem: rfqPrItems.prItem,
        materialCode: rfqPrItems.materialCode,
        materialCategory: rfqPrItems.materialCategory,
        materialDescription: rfqPrItems.materialDescription,
        size: rfqPrItems.size,
        quantity: rfqPrItems.quantity,
        uom: rfqPrItems.uom,
        deliveryDate: rfqPrItems.deliveryDate,
        majorYn: rfqPrItems.majorYn,
        remarks: rfqPrItems.remark,
      })
      .from(rfqPrItems)
      .where(eq(rfqPrItems.rfqsLastId, rfqId))
      .orderBy(desc(rfqPrItems.majorYn), asc(rfqPrItems.prItem))
    
    return prItems
  }