summaryrefslogtreecommitdiff
path: root/lib/swp/actions.ts
blob: 694936ab9a4647d94a1d6e0ee352e70847d641e4 (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
"use server";

import db from "@/db/db";
import { swpDocuments, swpDocumentRevisions, swpDocumentFiles } from "@/db/schema/SWP/swp-documents";
import { eq, and, sql, like, desc, asc, type SQL } from "drizzle-orm";
import { fetchSwpProjectData } from "./api-client";
import { syncSwpProject } from "./sync-service";

// ============================================================================
// 타입 정의
// ============================================================================

export interface SwpTableFilters {
  projNo?: string;
  docNo?: string;
  docTitle?: string;
  pkgNo?: string;
  vndrCd?: string;
  stage?: string;
}

export interface SwpTableParams {
  page: number;
  pageSize: number;
  sortBy?: string;
  sortOrder?: "asc" | "desc";
  filters?: SwpTableFilters;
}

export interface SwpDocumentWithStats {
  DOC_NO: string;
  DOC_TITLE: string;
  PROJ_NO: string;
  PROJ_NM: string | null;
  PKG_NO: string | null;
  VNDR_CD: string | null;
  CPY_NM: string | null;
  LTST_REV_NO: string | null;
  STAGE: string | null;
  sync_status: "synced" | "pending" | "error";
  last_synced_at: Date;
  revision_count: number;
  file_count: number;
}

// ============================================================================
// 서버 액션: 문서 목록 조회 (페이지네이션 + 검색)
// ============================================================================

export async function fetchSwpDocuments(params: SwpTableParams) {
  const { page, pageSize, sortBy = "last_synced_at", sortOrder = "desc", filters } = params;
  const offset = (page - 1) * pageSize;

  try {
    // WHERE 조건 구성
    const conditions: SQL<unknown>[] = [];
    
    if (filters?.projNo) {
      conditions.push(like(swpDocuments.PROJ_NO, `%${filters.projNo}%`));
    }
    if (filters?.docNo) {
      conditions.push(like(swpDocuments.DOC_NO, `%${filters.docNo}%`));
    }
    if (filters?.docTitle) {
      conditions.push(like(swpDocuments.DOC_TITLE, `%${filters.docTitle}%`));
    }
    if (filters?.pkgNo) {
      conditions.push(like(swpDocuments.PKG_NO, `%${filters.pkgNo}%`));
    }
    if (filters?.vndrCd) {
      conditions.push(like(swpDocuments.VNDR_CD, `%${filters.vndrCd}%`));
    }
    if (filters?.stage) {
      conditions.push(eq(swpDocuments.STAGE, filters.stage));
    }

    const whereClause = conditions.length > 0 ? and(...conditions) : undefined;

    // 총 개수 조회
    const totalResult = await db
      .select({ count: sql<number>`count(*)::int` })
      .from(swpDocuments)
      .where(whereClause);
    
    const total = totalResult[0]?.count || 0;

    // 정렬 컬럼 결정
    const orderByColumn = 
      sortBy === "DOC_NO" ? swpDocuments.DOC_NO :
      sortBy === "DOC_TITLE" ? swpDocuments.DOC_TITLE :
      sortBy === "PROJ_NO" ? swpDocuments.PROJ_NO :
      sortBy === "PKG_NO" ? swpDocuments.PKG_NO :
      sortBy === "STAGE" ? swpDocuments.STAGE :
      swpDocuments.last_synced_at;

    // 데이터 조회 (Drizzle query builder 사용)
    const documents = await db
      .select({
        DOC_NO: swpDocuments.DOC_NO,
        DOC_TITLE: swpDocuments.DOC_TITLE,
        PROJ_NO: swpDocuments.PROJ_NO,
        PROJ_NM: swpDocuments.PROJ_NM,
        PKG_NO: swpDocuments.PKG_NO,
        VNDR_CD: swpDocuments.VNDR_CD,
        CPY_NM: swpDocuments.CPY_NM,
        LTST_REV_NO: swpDocuments.LTST_REV_NO,
        STAGE: swpDocuments.STAGE,
        sync_status: swpDocuments.sync_status,
        last_synced_at: swpDocuments.last_synced_at,
        revision_count: sql<number>`COUNT(DISTINCT ${swpDocumentRevisions.id})::int`,
        file_count: sql<number>`COUNT(${swpDocumentFiles.id})::int`,
      })
      .from(swpDocuments)
      .leftJoin(swpDocumentRevisions, eq(swpDocuments.DOC_NO, swpDocumentRevisions.DOC_NO))
      .leftJoin(swpDocumentFiles, eq(swpDocumentRevisions.id, swpDocumentFiles.revision_id))
      .where(whereClause)
      .groupBy(
        swpDocuments.DOC_NO,
        swpDocuments.DOC_TITLE,
        swpDocuments.PROJ_NO,
        swpDocuments.PROJ_NM,
        swpDocuments.PKG_NO,
        swpDocuments.VNDR_CD,
        swpDocuments.CPY_NM,
        swpDocuments.LTST_REV_NO,
        swpDocuments.STAGE,
        swpDocuments.sync_status,
        swpDocuments.last_synced_at
      )
      .orderBy(sortOrder === "desc" ? desc(orderByColumn) : asc(orderByColumn))
      .limit(pageSize)
      .offset(offset);

    return {
      data: documents,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  } catch (error) {
    console.error("[fetchSwpDocuments] 오류:", error);
    throw new Error("문서 목록 조회 실패 [SWP API에서 실패가 발생했습니다. 담당자에게 문의하세요]");
  }
}

// ============================================================================
// 서버 액션: 문서의 리비전 목록 조회
// ============================================================================

export async function fetchDocumentRevisions(docNo: string) {
  try {
    const revisions = await db
      .select({
        id: swpDocumentRevisions.id,
        DOC_NO: swpDocumentRevisions.DOC_NO,
        REV_NO: swpDocumentRevisions.REV_NO,
        STAGE: swpDocumentRevisions.STAGE,
        ACTV_NO: swpDocumentRevisions.ACTV_NO,
        OFDC_NO: swpDocumentRevisions.OFDC_NO,
        sync_status: swpDocumentRevisions.sync_status,
        last_synced_at: swpDocumentRevisions.last_synced_at,
        file_count: sql<number>`(
          SELECT COUNT(*)::int 
          FROM swp.swp_document_files f 
          WHERE f.revision_id = ${swpDocumentRevisions.id}
        )`,
      })
      .from(swpDocumentRevisions)
      .where(eq(swpDocumentRevisions.DOC_NO, docNo))
      .orderBy(desc(swpDocumentRevisions.REV_NO));

    return revisions;
  } catch (error) {
    console.error("[fetchDocumentRevisions] 오류:", error);
    throw new Error("리비전 목록 조회 실패");
  }
}

// ============================================================================
// 서버 액션: 리비전의 파일 목록 조회
// ============================================================================

export async function fetchRevisionFiles(revisionId: number) {
  try {
    const files = await db
      .select({
        id: swpDocumentFiles.id,
        FILE_NM: swpDocumentFiles.FILE_NM,
        FILE_SEQ: swpDocumentFiles.FILE_SEQ,
        FILE_SZ: swpDocumentFiles.FILE_SZ,
        FLD_PATH: swpDocumentFiles.FLD_PATH,
        STAT: swpDocumentFiles.STAT,
        STAT_NM: swpDocumentFiles.STAT_NM,
        sync_status: swpDocumentFiles.sync_status,
        created_at: swpDocumentFiles.created_at,
      })
      .from(swpDocumentFiles)
      .where(eq(swpDocumentFiles.revision_id, revisionId))
      .orderBy(asc(swpDocumentFiles.FILE_SEQ));

    return files;
  } catch (error) {
    console.error("[fetchRevisionFiles] 오류:", error);
    throw new Error("파일 목록 조회 실패");
  }
}

// ============================================================================
// 서버 액션: 프로젝트 동기화
// ============================================================================

export async function syncSwpProjectAction(projectNo: string, docGb: "M" | "V" = "V") {
  try {
    console.log(`[syncSwpProjectAction] 시작: ${projectNo}`);
    
    // 1. API에서 데이터 조회
    const { documents, files } = await fetchSwpProjectData(projectNo, docGb);
    
    // 2. 동기화 실행
    const result = await syncSwpProject(projectNo, documents, files);
    
    console.log(`[syncSwpProjectAction] 완료:`, result.stats);
    
    return result;
  } catch (error) {
    console.error("[syncSwpProjectAction] 오류:", error);
    throw new Error(
      error instanceof Error ? error.message : "동기화 실패"
    );
  }
}

// ============================================================================
// 서버 액션: 프로젝트 목록 조회 (필터용)
// ============================================================================

export async function fetchProjectList() {
  try {
    const projects = await db
      .select({
        PROJ_NO: swpDocuments.PROJ_NO,
        PROJ_NM: swpDocuments.PROJ_NM,
        doc_count: sql<number>`COUNT(DISTINCT ${swpDocuments.DOC_NO})::int`,
      })
      .from(swpDocuments)
      .groupBy(swpDocuments.PROJ_NO, swpDocuments.PROJ_NM)
      .orderBy(desc(sql`COUNT(DISTINCT ${swpDocuments.DOC_NO})`));

    return projects;
  } catch (error) {
    console.error("[fetchProjectList] 오류:", error);
    return [];
  }
}

// ============================================================================
// 서버 액션: 통계 조회
// ============================================================================

export async function fetchSwpStats(projNo?: string) {
  try {
    const whereClause = projNo ? eq(swpDocuments.PROJ_NO, projNo) : undefined;

    const stats = await db
      .select({
        total_documents: sql<number>`COUNT(DISTINCT ${swpDocuments.DOC_NO})::int`,
        total_revisions: sql<number>`COUNT(DISTINCT ${swpDocumentRevisions.id})::int`,
        total_files: sql<number>`COUNT(${swpDocumentFiles.id})::int`,
        last_sync: sql<Date>`MAX(${swpDocuments.last_synced_at})`,
      })
      .from(swpDocuments)
      .leftJoin(swpDocumentRevisions, eq(swpDocuments.DOC_NO, swpDocumentRevisions.DOC_NO))
      .leftJoin(swpDocumentFiles, eq(swpDocumentRevisions.id, swpDocumentFiles.revision_id))
      .where(whereClause);

    return stats[0] || {
      total_documents: 0,
      total_revisions: 0,
      total_files: 0,
      last_sync: null,
    };
  } catch (error) {
    console.error("[fetchSwpStats] 오류:", error);
    return {
      total_documents: 0,
      total_revisions: 0,
      total_files: 0,
      last_sync: null,
    };
  }
}