summaryrefslogtreecommitdiff
path: root/lib/compliance/approval-handlers.ts
blob: 05f92a289b2be166bd7ebe26b01b4683a580db06 (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
"use server"

import db from "@/db/db"
import { and, inArray, isNull } from "drizzle-orm"
import { complianceResponses } from "@/db/schema/compliance"
import { resolveRedFlag } from "./red-flag-resolution"
import { revalidatePath } from "next/cache"

interface RedFlagResolutionPayload {
  contractIds: number[]
}

/**
 * 결재 승인 후 RED FLAG 해제를 처리하는 핸들러
 * 
 * approval-workflow에서 자동으로 호출됩니다.
 */
export async function resolveRedFlagAfterApproval(payload: RedFlagResolutionPayload) {
  if (!payload?.contractIds || payload.contractIds.length === 0) {
    return {
      success: false,
      message: "처리할 계약서가 없습니다.",
    }
  }

  const uniqueContractIds = Array.from(new Set(payload.contractIds))

  // 이미 해제된 계약을 제외한 대상을 조회
  const targets = await db
    .select({
      basicContractId: complianceResponses.basicContractId,
      approvalId: complianceResponses.redFlagResolutionApprovalId,
    })
    .from(complianceResponses)
    .where(
      and(
        inArray(complianceResponses.basicContractId, uniqueContractIds),
        isNull(complianceResponses.redFlagResolvedAt)
      )
    )

  if (targets.length === 0) {
    return {
      success: true,
      message: "해제 대상이 없습니다.",
    }
  }

  for (const target of targets) {
    await resolveRedFlag(target.basicContractId, {
      approvalId: target.approvalId ?? undefined,
      revalidate: false,
    })
  }

  await revalidatePath("/evcp/basic-contract")
  await revalidatePath("/evcp/compliance")

  return {
    success: true,
    updated: targets.length,
  }
}