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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
|
"use server"
import db from "@/db/db"
import { and, eq, inArray } from "drizzle-orm"
import { complianceResponses, redFlagManagers } from "@/db/schema/compliance"
import { basicContract, basicContractTemplates } from "@/db/schema/basicContractDocumnet"
import { vendors } from "@/db/schema/vendors"
import { users } from "@/db/schema"
import { getTriggeredRedFlagQuestions, type TriggeredRedFlagInfo } from "./red-flag-notifier"
import { getServerSession } from "next-auth"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
import { ApprovalSubmissionSaga } from "@/lib/approval"
import { htmlListConverter, htmlTableConverter } from "@/lib/approval/template-utils"
import type { ApprovalResult } from "@/lib/approval/types"
import { revalidatePath } from "next/cache"
type ContractSummary = {
contractId: number
vendorName: string | null
vendorCode: string | null
templateName: string | null
createdAt: Date | null
triggeredFlags: TriggeredRedFlagInfo[]
}
const RED_FLAG_TEMPLATE_NAME = "컴플라이언스 Red Flag 해소요청"
type SessionResult = Awaited<ReturnType<typeof getServerSession>>
type SessionUser = (SessionResult extends { user: infer U } ? NonNullable<U> : never) & {
epId?: string | null
id?: string | number
}
type RedFlagResolutionRequestInput = {
contractIds: number[]
approvers?: string[]
title?: string
}
type RedFlagResolutionPreparationResult = {
currentUser: SessionUser
currentUserId: number
validContractIds: number[]
variables: Record<string, string>
title: string
defaultApprovers: string[]
now: Date
}
/**
* RED FLAG 해소요청 미리보기 데이터 준비
*/
export async function prepareRedFlagResolutionApproval(contractIds: number[]) {
const context = await prepareRedFlagResolutionContext(contractIds)
return {
contractIds: context.validContractIds,
templateName: RED_FLAG_TEMPLATE_NAME,
title: context.title,
variables: context.variables,
defaultApprovers: context.defaultApprovers,
}
}
/**
* RED FLAG 해소요청 - Approval Saga를 통해 상신
*/
export async function requestRedFlagResolution(
input: RedFlagResolutionRequestInput
): Promise<ApprovalResult> {
const context = await prepareRedFlagResolutionContext(input.contractIds)
const requestedTitle = input.title?.trim() || context.title
const baseApprovers =
input.approvers && input.approvers.length > 0 ? input.approvers : context.defaultApprovers
const approverEpIds = Array.from(
new Set(baseApprovers.filter((epId): epId is string => typeof epId === "string" && epId.length > 0))
)
if (approverEpIds.length === 0) {
throw new Error("결재선을 설정해주세요.")
}
const saga = new ApprovalSubmissionSaga(
"compliance_red_flag_resolution",
{
contractIds: context.validContractIds,
requestedBy: context.currentUserId,
requestedAt: context.now.toISOString(),
},
{
title: requestedTitle,
description: RED_FLAG_TEMPLATE_NAME,
templateName: RED_FLAG_TEMPLATE_NAME,
variables: context.variables,
approvers: approverEpIds,
currentUser: {
id: context.currentUserId,
epId: context.currentUser.epId!,
email: context.currentUser.email ?? undefined,
},
}
)
const result = await saga.execute()
if (result.status === "pending_approval") {
await db
.update(complianceResponses)
.set({
redFlagResolutionApprovalId: result.approvalId,
redFlagResolvedAt: null,
updatedAt: new Date(),
})
.where(inArray(complianceResponses.basicContractId, context.validContractIds))
await revalidatePath("/evcp/basic-contract")
await revalidatePath("/evcp/compliance")
}
return result
}
/**
* RED FLAG 해소 처리 (승인 후 실행)
*/
export async function resolveRedFlag(
contractId: number,
options: { approvalId?: string; revalidate?: boolean } = {}
): Promise<{ success: boolean; message: string }> {
const conditions = [eq(complianceResponses.basicContractId, contractId)]
if (options.approvalId) {
conditions.push(eq(complianceResponses.redFlagResolutionApprovalId, options.approvalId))
}
const [updated] = await db
.update(complianceResponses)
.set({
redFlagResolvedAt: new Date(),
updatedAt: new Date(),
})
.where(and(...conditions))
.returning({ id: complianceResponses.id })
if (!updated) {
throw new Error("해소요청 정보를 찾을 수 없습니다.")
}
if (options.revalidate !== false) {
await revalidatePath("/evcp/basic-contract")
await revalidatePath("/evcp/compliance")
}
return {
success: true,
message: "RED FLAG가 해제되었습니다.",
}
}
async function getPurchasingManagerEpId(): Promise<string | null> {
const [manager] = await db
.select({
purchasingManagerId: redFlagManagers.purchasingManagerId,
})
.from(redFlagManagers)
.orderBy(redFlagManagers.createdAt)
.limit(1)
if (!manager?.purchasingManagerId) {
return null
}
const [user] = await db
.select({
epId: users.epId,
})
.from(users)
.where(eq(users.id, manager.purchasingManagerId))
.limit(1)
return user?.epId ?? null
}
async function fetchContractsWithFlags(contractIds: number[]): Promise<ContractSummary[]> {
const contracts = await db
.select({
contractId: basicContract.id,
vendorName: vendors.vendorName,
vendorCode: vendors.vendorCode,
templateName: basicContractTemplates.templateName,
createdAt: basicContract.createdAt,
})
.from(basicContract)
.leftJoin(vendors, eq(basicContract.vendorId, vendors.id))
.leftJoin(basicContractTemplates, eq(basicContract.templateId, basicContractTemplates.id))
.where(inArray(basicContract.id, contractIds))
const withFlags = await Promise.all(
contracts.map(async (contract) => {
const triggeredFlags = await getTriggeredRedFlagQuestions(contract.contractId)
return {
...contract,
triggeredFlags,
}
})
)
return withFlags.filter((contract) => contract.triggeredFlags.length > 0)
}
async function fetchContractVendorSummaries(
contractIds: number[]
): Promise<Array<{ contractId: number; vendorName: string | null }>> {
if (contractIds.length === 0) {
return []
}
return db
.select({
contractId: basicContract.id,
vendorName: vendors.vendorName,
})
.from(basicContract)
.leftJoin(vendors, eq(basicContract.vendorId, vendors.id))
.where(inArray(basicContract.id, contractIds))
}
async function buildTemplateVariables(
contracts: ContractSummary[],
meta: { requesterName: string; requestedAt: Date }
): Promise<Record<string, string>> {
const summaryRows = contracts.map((contract) => ({
contractId: contract.contractId,
vendorName: contract.vendorName ?? "-",
templateName: contract.templateName ?? "-",
redFlagCount: contract.triggeredFlags.length,
}))
const summaryTable = await htmlTableConverter(summaryRows, [
{ key: "contractId", label: "계약 ID" },
{ key: "vendorName", label: "업체명" },
{ key: "templateName", label: "템플릿" },
{ key: "redFlagCount", label: "RED FLAG 수" },
])
const detailSections = await Promise.all(
contracts.map(async (contract) => {
const questionList = contract.triggeredFlags.map((flag, index) => {
const prefix = flag.questionNumber || `${index + 1}`
return `${prefix}. ${flag.questionText}`
})
const listHtml = await htmlListConverter(questionList)
return `
<div style="margin-bottom: 24px;">
<div style="font-weight:600;margin-bottom:8px;">
계약 ID: ${contract.contractId} / ${contract.vendorName ?? "-"}
</div>
<div>${listHtml}</div>
</div>
`
})
)
const detailHtml = detailSections.join("")
const formattedDate = new Intl.DateTimeFormat("ko-KR", {
dateStyle: "medium",
timeStyle: "short",
}).format(meta.requestedAt)
return {
요청자이름: meta.requesterName,
요청일시: formattedDate,
요청사유: "컴플라이언스 Red Flag 해소를 위해 구매기획 합의를 요청드립니다.",
RedFlag요약테이블: summaryTable,
RedFlag상세내역: detailHtml,
}
}
function buildApprovalTitle(contracts: ContractSummary[]) {
if (contracts.length === 0) return "컴플라이언스 Red Flag 해소요청"
const firstVendor = contracts[0].vendorName ?? `계약 ${contracts[0].contractId}`
if (contracts.length === 1) {
return `Red Flag 해소요청 - ${firstVendor}`
}
return `Red Flag 해소요청 - ${firstVendor} 외 ${contracts.length - 1}건`
}
async function prepareRedFlagResolutionContext(
contractIds: number[]
): Promise<RedFlagResolutionPreparationResult> {
if (!contractIds || contractIds.length === 0) {
throw new Error("RED FLAG 해소요청을 위한 계약서를 선택해주세요.")
}
const uniqueContractIds = Array.from(new Set(contractIds))
const session = await getServerSession(authOptions)
if (!session?.user) {
throw new Error("인증이 필요합니다.")
}
const currentUser = session.user
if (!currentUser.epId) {
throw new Error("Knox EP ID가 필요합니다.")
}
const currentUserId = Number(currentUser.id)
if (Number.isNaN(currentUserId)) {
throw new Error("유효한 사용자 정보가 필요합니다.")
}
const purchasingManagerEpId = await getPurchasingManagerEpId()
if (!purchasingManagerEpId) {
throw new Error("구매기획 담당자의 EP ID가 설정되지 않았습니다.")
}
const responses = await db
.select({
basicContractId: complianceResponses.basicContractId,
redFlagResolvedAt: complianceResponses.redFlagResolvedAt,
redFlagResolutionApprovalId: complianceResponses.redFlagResolutionApprovalId,
})
.from(complianceResponses)
.where(inArray(complianceResponses.basicContractId, uniqueContractIds))
const blockedContracts = responses
.filter((response) => response.redFlagResolutionApprovalId && !response.redFlagResolvedAt)
.map((response) => response.basicContractId)
if (blockedContracts.length > 0) {
const blockedSummaries = await fetchContractVendorSummaries(blockedContracts)
const blockedNames = blockedSummaries.map(
(contract) => contract.vendorName ?? `계약 ${contract.contractId}`
)
const preview =
blockedNames.length > 2
? `${blockedNames.slice(0, 2).join(", ")} 외 ${blockedNames.length - 2}건`
: blockedNames.join(", ")
throw new Error(`이미 해소요청이 진행 중인 계약서가 있습니다: ${preview}`)
}
const contractSummaries = await fetchContractsWithFlags(uniqueContractIds)
if (contractSummaries.length === 0) {
throw new Error("선택한 계약서에 RED FLAG가 존재하지 않습니다.")
}
const validContractIds = contractSummaries.map((contract) => contract.contractId)
const missingResponses = validContractIds.filter(
(contractId) => !responses.some((response) => response.basicContractId === contractId)
)
if (missingResponses.length > 0) {
throw new Error("준법 응답 정보를 찾을 수 없는 계약서가 포함되어 있습니다.")
}
const now = new Date()
const variables = await buildTemplateVariables(contractSummaries, {
requesterName: currentUser.name || currentUser.email || "요청자",
requestedAt: now,
})
const title = buildApprovalTitle(contractSummaries)
return {
currentUser,
currentUserId,
validContractIds,
variables,
title,
defaultApprovers: [purchasingManagerEpId],
now,
}
}
|