summaryrefslogtreecommitdiff
path: root/lib/project-gtc/service.ts
blob: 7ae09635d3ac24ef06d505f68d3ac613809f9962 (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
"use server";

import { revalidateTag } from "next/cache";
import db from "@/db/db";
import { unstable_cache } from "@/lib/unstable-cache";
import { asc, desc, ilike, or, eq, count, and, ne, sql } from "drizzle-orm";
import {
  projectGtcFiles,
  projectGtcView,
  type ProjectGtcFile,
  projects,
} from "@/db/schema";
import { promises as fs } from "fs";
import path from "path";
import crypto from "crypto";
import { revalidatePath } from 'next/cache';
import { deleteFile, saveFile } from "../file-stroage";

// Project GTC 목록 조회
export async function getProjectGtcList(
  input: {
    page: number;
    perPage: number;
    search?: string;
    sort: Array<{ id: string; desc: boolean }>;
    filters?: Record<string, unknown>;
  }
) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        const { data, total } = await db.transaction(async (tx) => {
          let whereCondition = undefined;

          // GTC 파일이 있는 프로젝트만 필터링
          const gtcFileCondition = sql`${projectGtcView.gtcFileId} IS NOT NULL`;

          if (input.search) {
            const s = `%${input.search}%`;
            const searchCondition = or(
              ilike(projectGtcView.code, s),
              ilike(projectGtcView.name, s),
              ilike(projectGtcView.type, s),
              ilike(projectGtcView.originalFileName, s)
            );
            whereCondition = and(gtcFileCondition, searchCondition);
          } else {
            whereCondition = gtcFileCondition;
          }

          const orderBy =
            input.sort.length > 0
              ? input.sort.map((item) =>
                item.desc
                  ? desc(
                    projectGtcView[
                    item.id as keyof typeof projectGtcView
                    ] as never
                  )
                  : asc(
                    projectGtcView[
                    item.id as keyof typeof projectGtcView
                    ] as never
                  )
              )
              : [desc(projectGtcView.projectCreatedAt)];

          const dataResult = await tx
            .select()
            .from(projectGtcView)
            .where(whereCondition)
            .orderBy(...orderBy)
            .limit(input.perPage)
            .offset(offset);

          const totalCount = await tx
            .select({ count: count() })
            .from(projectGtcView)
            .where(whereCondition);

          return {
            data: dataResult,
            total: totalCount[0]?.count || 0,
          };
        });

        const pageCount = Math.ceil(total / input.perPage);

        return {
          data,
          pageCount,
        };
      } catch (error) {
        console.error("getProjectGtcList 에러:", error);
        throw new Error("Project GTC 목록을 가져오는 중 오류가 발생했습니다.");
      }
    },
    [`project-gtc-list-${JSON.stringify(input)}`],
    {
      tags: ["project-gtc"],
      revalidate: false,
    }
  )();
}

// Project GTC 파일 업로드
export async function uploadProjectGtcFile(
  projectId: number,
  file: File
): Promise<{ success: boolean; data?: ProjectGtcFile; error?: string }> {
  try {
    // 유효성 검사
    if (!projectId) {
      return { success: false, error: "프로젝트 ID는 필수입니다." };
    }

    if (!file) {
      return { success: false, error: "파일은 필수입니다." };
    }

    const saveResult = await saveFile(file, 'proejctGTC');
    if (!saveResult.success) {
      return { success: false, error: saveResult.error };
    }


    // 기존 파일이 있으면 삭제
    const existingFile = await db.query.projectGtcFiles.findFirst({
      where: eq(projectGtcFiles.projectId, projectId)
    });

    if (existingFile) {

      const deleted = await deleteFile(existingFile.filePath);
     
      // DB에서 기존 파일 정보 삭제
      await db.delete(projectGtcFiles)
        .where(eq(projectGtcFiles.id, existingFile.id));
    }

    // DB에 새 파일 정보 저장
    const newFile = await db.insert(projectGtcFiles).values({
      projectId,
      fileName: saveResult.fileName!,
      filePath: saveResult.publicPath!,
      originalFileName:file.name,
      fileSize: file.size,
      mimeType: file.type,
    }).returning();

    revalidateTag("project-gtc");
    revalidatePath("/evcp/project-gtc");

    return { success: true, data: newFile[0] };

  } catch (error) {
    console.error("Project GTC 파일 업로드 에러:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "파일 업로드 중 오류가 발생했습니다."
    };
  }
}

// Project GTC 파일 삭제
export async function deleteProjectGtcFile(
  projectId: number
): Promise<{ success: boolean; error?: string }> {
  try {
    return await db.transaction(async (tx) => {
      const existingFile = await tx.query.projectGtcFiles.findFirst({
        where: eq(projectGtcFiles.projectId, projectId)
      });

      if (!existingFile) {
        return { success: false, error: "삭제할 파일이 없습니다." };
      }

      // 파일 시스템에서 파일 삭제
      try {

        const deleted = await deleteFile(existingFile.filePath);
      } catch (error) {
        console.error("파일 시스템에서 파일 삭제 실패:", error);
        throw new Error("파일 시스템에서 파일 삭제에 실패했습니다.");
      }

      // DB에서 파일 정보 삭제
      await tx.delete(projectGtcFiles)
        .where(eq(projectGtcFiles.id, existingFile.id));

      return { success: true };
    });

  } catch (error) {
    console.error("Project GTC 파일 삭제 에러:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "파일 삭제 중 오류가 발생했습니다."
    };
  } finally {
    // 트랜잭션 성공/실패와 관계없이 캐시 무효화
    revalidateTag("project-gtc");
    revalidatePath("/evcp/project-gtc");
  }
}

// 프로젝트별 GTC 파일 정보 조회
export async function getProjectGtcFile(projectId: number): Promise<ProjectGtcFile | null> {
  try {
    const file = await db.query.projectGtcFiles.findFirst({
      where: eq(projectGtcFiles.projectId, projectId)
    });

    return file || null;
  } catch (error) {
    console.error("Project GTC 파일 조회 에러:", error);
    return null;
  }
}

// 프로젝트 생성 서버 액션
export async function createProject(
  input: {
    code: string;
    name: string;
    type: string;
  }
): Promise<{ success: boolean; data?: typeof projects.$inferSelect; error?: string }> {
  try {
    // 유효성 검사
    if (!input.code?.trim()) {
      return { success: false, error: "프로젝트 코드는 필수입니다." };
    }

    if (!input.name?.trim()) {
      return { success: false, error: "프로젝트명은 필수입니다." };
    }

    if (!input.type?.trim()) {
      return { success: false, error: "프로젝트 타입은 필수입니다." };
    }

    // 프로젝트 코드 중복 검사
    const existingProject = await db.query.projects.findFirst({
      where: eq(projects.code, input.code.trim())
    });

    if (existingProject) {
      return { success: false, error: "이미 존재하는 프로젝트 코드입니다." };
    }

    // 프로젝트 생성
    const newProject = await db.insert(projects).values({
      code: input.code.trim(),
      name: input.name.trim(),
      type: input.type.trim(),
    }).returning();

    revalidateTag("project-gtc");
    revalidatePath("/evcp/project-gtc");

    return { success: true, data: newProject[0] };

  } catch (error) {
    console.error("프로젝트 생성 에러:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "프로젝트 생성 중 오류가 발생했습니다."
    };
  }
}

// 프로젝트 정보 수정 서버 액션
export async function updateProject(
  input: {
    id: number;
    code: string;
    name: string;
    type: string;
  }
): Promise<{ success: boolean; error?: string }> {
  try {
    if (!input.id) {
      return { success: false, error: "프로젝트 ID는 필수입니다." };
    }
    if (!input.code?.trim()) {
      return { success: false, error: "프로젝트 코드는 필수입니다." };
    }
    if (!input.name?.trim()) {
      return { success: false, error: "프로젝트명은 필수입니다." };
    }
    if (!input.type?.trim()) {
      return { success: false, error: "프로젝트 타입은 필수입니다." };
    }

    // 프로젝트 코드 중복 검사 (본인 제외)
    const existingProject = await db.query.projects.findFirst({
      where: and(
        eq(projects.code, input.code.trim()),
        ne(projects.id, input.id)
      )
    });
    if (existingProject) {
      return { success: false, error: "이미 존재하는 프로젝트 코드입니다." };
    }

    // 업데이트
    await db.update(projects)
      .set({
        code: input.code.trim(),
        name: input.name.trim(),
        type: input.type.trim(),
      })
      .where(eq(projects.id, input.id));

    revalidateTag("project-gtc");
    revalidatePath("/evcp/project-gtc");

    return { success: true };
  } catch (error) {
    console.error("프로젝트 수정 에러:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "프로젝트 수정 중 오류가 발생했습니다."
    };
  }
}

// 이미 GTC 파일이 등록된 프로젝트 ID 목록 조회
export async function getProjectsWithGtcFiles(): Promise<number[]> {
  try {
    const result = await db
      .select({ projectId: projectGtcFiles.projectId })
      .from(projectGtcFiles);
    
    return result.map(row => row.projectId);
  } catch (error) {
    console.error("GTC 파일이 등록된 프로젝트 조회 에러:", error);
    return [];
  }
}