summaryrefslogtreecommitdiff
path: root/lib/gtc-contract
diff options
context:
space:
mode:
Diffstat (limited to 'lib/gtc-contract')
-rw-r--r--lib/gtc-contract/service.ts269
1 files changed, 268 insertions, 1 deletions
diff --git a/lib/gtc-contract/service.ts b/lib/gtc-contract/service.ts
index 4d11ad0a..f9725f80 100644
--- a/lib/gtc-contract/service.ts
+++ b/lib/gtc-contract/service.ts
@@ -3,9 +3,10 @@
import { revalidateTag, unstable_cache } from "next/cache"
import { and, desc, asc, eq, or, ilike, count, max , inArray, isNotNull, notInArray} from "drizzle-orm"
import db from "@/db/db"
-import { GtcClauseTreeView, gtcClauses, gtcDocuments, gtcDocumentsView, type GtcDocument, type GtcDocumentWithRelations } from "@/db/schema/gtc"
+import { GtcClauseTreeView, gtcClauses, gtcDocuments, gtcDocumentsView, gtcVendorDocuments, type GtcDocument, type GtcDocumentWithRelations } from "@/db/schema/gtc"
import { projects } from "@/db/schema/projects"
import { users } from "@/db/schema/users"
+import { vendors } from "@/db/schema/vendors"
import { filterColumns } from "@/lib/filter-columns"
import type { GetGtcDocumentsSchema, CreateGtcDocumentSchema, UpdateGtcDocumentSchema, CreateNewRevisionSchema, CloneGtcDocumentSchema } from "./validations"
@@ -446,6 +447,8 @@ export async function getAvailableProjectsForGtc(): Promise<ProjectForFilter[]>
})
.from(gtcDocuments)
.where(isNotNull(gtcDocuments.projectId))
+
+ console.log(projectsWithGtc,"projectsWithGtc")
const usedProjectIds = projectsWithGtc
.map(row => row.projectId)
@@ -457,6 +460,8 @@ export async function getAvailableProjectsForGtc(): Promise<ProjectForFilter[]>
return await getProjectsForSelect()
}
+
+
return await db
.select({
id: projects.id,
@@ -844,4 +849,266 @@ export async function validateGtcClausesImport(
}
}
}
+}
+
+/**
+ * GTC 문서를 벤더별로 생성
+ */
+export async function createGtcVendorDocuments({
+ baseDocumentId,
+ vendorIds,
+ createdById,
+ documentTitle = "General GTC"
+}: {
+ baseDocumentId: number
+ vendorIds: number[]
+ createdById: number
+ documentTitle?: string
+}) {
+ try {
+ console.log(`🔍 [GTC] 표준 GTC 문서 생성 시작: baseDocumentId=${baseDocumentId}, title=${documentTitle}`)
+
+ const results = []
+
+ for (let i = 0; i < vendorIds.length; i++) {
+ const vendorId = vendorIds[i]
+ try {
+ console.log(`📄 [GTC] 벤더 ${i + 1}/${vendorIds.length} 표준 GTC 문서 생성: vendorId=${vendorId}`)
+
+ const result = await db.insert(gtcVendorDocuments).values({
+ baseDocumentId,
+ vendorId,
+ name: documentTitle,
+ reviewStatus: "draft",
+ isActive: true,
+ createdById,
+ updatedById: createdById,
+ }).returning()
+
+ console.log(`✅ [GTC] 표준 GTC 문서 생성 성공: vendorId=${vendorId}, insertedId=${result[0].id}`)
+ results.push(result[0])
+
+ } catch (vendorError) {
+ console.error(`❌ [GTC] 표준 GTC 문서 생성 실패: vendorId=${vendorId}`, vendorError)
+ continue
+ }
+ }
+
+ console.log(`🎉 [GTC] 표준 GTC 문서 생성 완료: ${results.length}/${vendorIds.length}개 성공`)
+
+ return {
+ success: true,
+ data: results,
+ count: results.length
+ }
+ } catch (error) {
+ console.error("❌ [GTC] 표준 GTC 벤더 문서 생성 오류:", error)
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "알 수 없는 오류"
+ }
+ }
+}
+
+/**
+ * 프로젝트별 GTC 문서를 벤더별로 생성
+ */
+export async function createProjectGtcVendorDocuments({
+ projectCode,
+ vendorIds,
+ createdById,
+ documentTitle
+}: {
+ projectCode: string
+ vendorIds: number[]
+ createdById: number
+ documentTitle?: string
+}) {
+ try {
+ console.log(`🔍 [GTC] 프로젝트별 GTC 문서 생성 시작: ${projectCode}`)
+
+ // 1. 프로젝트 코드로 GTC 문서 찾기
+ console.log(`🔍 [GTC] GTC 문서 검색 쿼리 실행: projectCode=${projectCode}`)
+
+ // 1. 프로젝트 코드로 프로젝트 id 조회
+ const projectRow = await db
+ .select({ id: projects.id })
+ .from(projects)
+ .where(eq(projects.code, projectCode))
+ .limit(1);
+
+ if (!projectRow || projectRow.length === 0) {
+ console.log(`❌ [GTC] 프로젝트 코드에 해당하는 프로젝트를 찾을 수 없음: ${projectCode}`);
+ return {
+ success: false,
+ error: `프로젝트 코드 "${projectCode}"에 해당하는 프로젝트를 찾을 수 없습니다.`
+ }
+ }
+
+ const projectId = projectRow[0].id;
+ console.log(projectId,"projectId")
+
+ // 2. 해당 프로젝트 id로 GTC 문서 조회
+ const gtcDocument = await db
+ .select({
+ id: gtcDocuments.id,
+ title: gtcDocuments.title
+ })
+ .from(gtcDocuments)
+ .where(
+ and(
+ eq(gtcDocuments.type, "project"),
+ eq(gtcDocuments.isActive, true),
+ eq(gtcDocuments.projectId, projectId)
+ )
+ )
+ .orderBy(desc(gtcDocuments.revision))
+ .limit(1);
+
+ console.log(`🔍 [GTC] GTC 문서 검색 결과:`, gtcDocument)
+
+ if (!gtcDocument || gtcDocument.length === 0) {
+ console.log(`❌ [GTC] 프로젝트 GTC 문서를 찾을 수 없음: ${projectCode}`)
+ return {
+ success: false,
+ error: `프로젝트 코드 "${projectCode}"에 해당하는 GTC 문서를 찾을 수 없습니다.`
+ }
+ }
+
+ const baseDocumentId = gtcDocument[0].id
+ const finalDocumentTitle = documentTitle || `${projectCode} GTC`
+
+ console.log(`✅ [GTC] GTC 문서 찾음: id=${baseDocumentId}, title=${finalDocumentTitle}`)
+
+ // 2. 각 벤더별로 GTC 벤더 문서 생성
+ console.log(`📝 [GTC] 벤더별 GTC 문서 생성 시작: ${vendorIds.length}개 벤더`)
+
+ const results = []
+
+ for (let i = 0; i < vendorIds.length; i++) {
+ const vendorId = vendorIds[i]
+ try {
+ console.log(`📄 [GTC] 벤더 ${i + 1}/${vendorIds.length} GTC 문서 생성: vendorId=${vendorId}`)
+
+ const result = await db.insert(gtcVendorDocuments).values({
+ baseDocumentId,
+ vendorId,
+ name: finalDocumentTitle,
+ reviewStatus: "draft",
+ isActive: true,
+ createdById,
+ updatedById: createdById,
+ }).returning()
+
+ console.log(`✅ [GTC] 벤더 GTC 문서 생성 성공: vendorId=${vendorId}, insertedId=${result[0].id}`)
+ results.push(result[0])
+
+ } catch (vendorError) {
+ console.error(`❌ [GTC] 벤더 GTC 문서 생성 실패: vendorId=${vendorId}`, vendorError)
+ // 개별 벤더 실패는 전체 실패로 처리하지 않고 계속 진행
+ continue
+ }
+ }
+
+ console.log(`🎉 [GTC] 프로젝트 GTC 문서 생성 완료: ${results.length}/${vendorIds.length}개 성공`)
+
+ return {
+ success: true,
+ data: results,
+ count: results.length
+ }
+ } catch (error) {
+ console.error("❌ [GTC] 프로젝트 GTC 벤더 문서 생성 오류:", error)
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "알 수 없는 오류"
+ }
+ }
+}
+
+/**
+ * 표준 GTC 문서 ID 가져오기 (최신 리비전)
+ */
+export async function getStandardGtcDocumentId(): Promise<{ id: number; title: string } | null> {
+ try {
+ console.log(`🔍 [GTC-UTIL] 표준 GTC 문서 조회 시작`)
+
+ const result = await db
+ .select({
+ id: gtcDocuments.id,
+ title: gtcDocuments.title,
+ revision: gtcDocuments.revision
+ })
+ .from(gtcDocuments)
+ .where(
+ and(
+ eq(gtcDocuments.type, "standard"),
+ eq(gtcDocuments.isActive, true)
+ )
+ )
+ .orderBy(desc(gtcDocuments.revision))
+ .limit(1)
+
+ console.log(`🔍 [GTC-UTIL] 표준 GTC 문서 조회 결과:`, result)
+
+ if (result.length > 0) {
+ const gtcDoc = {
+ id: result[0].id,
+ title: result[0].title || "General GTC"
+ }
+ console.log(`✅ [GTC-UTIL] 표준 GTC 문서 찾음:`, gtcDoc)
+ return gtcDoc
+ } else {
+ console.log(`⚠️ [GTC-UTIL] 표준 GTC 문서를 찾을 수 없음`)
+ return null
+ }
+ } catch (error) {
+ console.error("❌ [GTC-UTIL] 표준 GTC 문서 ID 조회 오류:", error)
+ return null
+ }
+}
+
+/**
+ * 프로젝트 코드로 GTC 문서 ID 가져오기 (최신 리비전)
+ */
+export async function getProjectGtcDocumentId(projectCode: string): Promise<{ id: number; title: string } | null> {
+ try {
+ console.log(`🔍 [GTC-UTIL] 프로젝트 GTC 문서 조회 시작: ${projectCode}`)
+
+ const result = await db
+ .select({
+ id: gtcDocuments.id,
+ title: gtcDocuments.title,
+ revision: gtcDocuments.revision,
+ projectCode: projects.code
+ })
+ .from(gtcDocuments)
+ .leftJoin(projects, eq(gtcDocuments.projectId, projects.id))
+ .where(
+ and(
+ eq(gtcDocuments.type, "project"),
+ eq(gtcDocuments.isActive, true),
+ eq(projects.code, projectCode)
+ )
+ )
+ .orderBy(desc(gtcDocuments.revision))
+ .limit(1)
+
+ console.log(`🔍 [GTC-UTIL] 프로젝트 GTC 문서 조회 결과:`, result)
+
+ if (result.length > 0) {
+ const gtcDoc = {
+ id: result[0].id,
+ title: result[0].title || `${projectCode} GTC`
+ }
+ console.log(`✅ [GTC-UTIL] 프로젝트 GTC 문서 찾음:`, gtcDoc)
+ return gtcDoc
+ } else {
+ console.log(`⚠️ [GTC-UTIL] 프로젝트 GTC 문서를 찾을 수 없음: ${projectCode}`)
+ return null
+ }
+ } catch (error) {
+ console.error("❌ [GTC-UTIL] 프로젝트 GTC 문서 ID 조회 오류:", error)
+ return null
+ }
} \ No newline at end of file