summaryrefslogtreecommitdiff
path: root/lib/rfqs
diff options
context:
space:
mode:
Diffstat (limited to 'lib/rfqs')
-rw-r--r--lib/rfqs/service.ts110
1 files changed, 13 insertions, 97 deletions
diff --git a/lib/rfqs/service.ts b/lib/rfqs/service.ts
index 820de294..38bf467c 100644
--- a/lib/rfqs/service.ts
+++ b/lib/rfqs/service.ts
@@ -11,8 +11,6 @@ import { getErrorMessage } from "@/lib/handle-error";
import { GetRfqsSchema, CreateRfqSchema, UpdateRfqSchema, CreateRfqItemSchema, GetMatchedVendorsSchema, GetRfqsForVendorsSchema, UpdateRfqVendorSchema, GetTBESchema, RfqType, GetCBESchema, createCbeEvaluationSchema } from "./validations";
import { asc, desc, ilike, inArray, and, gte, lte, not, or, sql, eq, isNull, ne, isNotNull, count } from "drizzle-orm";
import path from "path";
-import fs from "fs/promises";
-import { randomUUID } from "crypto";
import { writeFile, mkdir } from 'fs/promises'
import { join } from 'path'
@@ -29,6 +27,7 @@ import { headers } from 'next/headers';
// DRM 복호화 관련 유틸 import
import { decryptWithServerAction } from "@/components/drm/drmUtils";
+import { deleteFile, saveDRMFile, saveFile } from "../file-stroage";
interface InviteVendorsInput {
rfqId: number
@@ -449,50 +448,22 @@ export async function processRfqAttachments(args: {
// 1-3) 파일 삭제
for (const row of rows) {
- // filePath: 예) "/rfq/123/...xyz"
- const absolutePath = path.join(
- process.cwd(),
- "public",
- row.filePath.replace(/^\/+/, "") // 슬래시 제거
- );
- try {
- await fs.unlink(absolutePath);
- } catch (err) {
- console.error("File remove error:", err);
- }
+ await deleteFile(row.filePath!);
}
}
// 2) 새 파일 업로드
if (newFiles.length > 0) {
- const rfqDir = path.join("public", "rfq", String(rfqId));
- // 폴더 없으면 생성
- await fs.mkdir(rfqDir, { recursive: true });
-
for (const file of newFiles) {
- // 2-1) DRM 복호화 시도 ----------------------------------------------------------------------
- // decryptWithServerAction 함수는 오류 처리 및 원본 반환 로직을 포함하고 있음 (해제 실패시 원본 반환)
- // 이후 코드가 buffer로 작업하므로 buffer로 전환한다.
- const decryptedData = await decryptWithServerAction(file);
- const buffer = Buffer.from(decryptedData);
- // -----------------------------------------------------------------------------------------
-
-
- // 2-2) 고유 파일명
- const uniqueName = `${randomUUID()}-${file.name}`;
- // 예) "rfq/123/xxx"
- const relativePath = path.join("rfq", String(rfqId), uniqueName);
- const absolutePath = path.join("public", relativePath);
-
- // 2-3) 파일 저장
- await fs.writeFile(absolutePath, buffer);
+ const saveResult = await saveDRMFile(file, decryptWithServerAction,'rfq' )
+
// 2-4) DB Insert
await db.insert(rfqAttachments).values({
rfqId,
vendorId,
fileName: file.name,
- filePath: "/" + relativePath.replace(/\\/g, "/"),
+ filePath: saveResult.publicPath!,
// (Windows 경로 대비)
});
}
@@ -1521,16 +1492,6 @@ export async function inviteTbeVendorsAction(formData: FormData) {
throw new Error("Invalid input or no files attached.")
}
- // /public/rfq/[rfqId] 경로
- const uploadDir = path.join(process.cwd(), "public", "rfq", String(rfqId))
-
- // 디렉토리가 없다면 생성
- try {
- await fs.mkdir(uploadDir, { recursive: true })
- } catch (err) {
- console.error("디렉토리 생성 실패:", err)
- }
-
// DB 트랜잭션
await db.transaction(async (tx) => {
// (A) RFQ 기본 정보 조회
@@ -1577,21 +1538,13 @@ export async function inviteTbeVendorsAction(formData: FormData) {
// 여기서는 "모든 파일"을 RFQ-DIR에 저장 + "각 협력업체"에는 동일 파일 목록을 첨부한다는 예시.
const savedFiles = []
for (const file of tbeFiles) {
- const originalName = file.name || "tbe-sheet.xlsx"
- // 파일명 충돌 방지를 위한 타임스탬프 추가
- const timestamp = new Date().getTime()
- const fileName = `${timestamp}-${originalName}`
- const savePath = path.join(uploadDir, fileName)
-
- // 파일 ArrayBuffer → Buffer 변환 후 저장
- const arrayBuffer = await file.arrayBuffer()
- await fs.writeFile(savePath, Buffer.from(arrayBuffer))
+ const saveResult = await saveFile({file, directory:'rfb'});
// 저장 경로 & 파일명 기록
savedFiles.push({
- fileName: originalName, // 원본 파일명으로 첨부
- filePath: `/rfq/${rfqId}/${fileName}`, // public 이하 경로
- absolutePath: savePath,
+ fileName: file.name, // 원본 파일명으로 첨부
+ filePath: saveResult.publicPath, // public 이하 경로
+ absolutePath: saveResult.publicPath,
})
}
@@ -1769,22 +1722,9 @@ export async function createRfqCommentWithAttachments(params: {
// 2) 첨부파일 처리
if (files && files.length > 0) {
- const rfqDir = path.join(process.cwd(), "public", "rfq", String(rfqId));
- // 폴더 없으면 생성
- await fs.mkdir(rfqDir, { recursive: true });
-
for (const file of files) {
- const ab = await file.arrayBuffer();
- const buffer = Buffer.from(ab);
-
- // 2-2) 고유 파일명
- const uniqueName = `${randomUUID()}-${file.name}`;
- // 예) "rfq/123/xxx"
- const relativePath = path.join("rfq", String(rfqId), uniqueName);
- const absolutePath = path.join(process.cwd(), "public", relativePath);
- // 2-3) 파일 저장
- await fs.writeFile(absolutePath, buffer);
+ const saveResult = await saveFile({file, directory:'rfq'})
// DB에 첨부파일 row 생성
await db.insert(rfqAttachments).values({
@@ -1794,7 +1734,7 @@ export async function createRfqCommentWithAttachments(params: {
cbeId: cbeId || null,
commentId: insertedComment.id, // 새 코멘트와 연결
fileName: file.name,
- filePath: "/" + relativePath.replace(/\\/g, "/"),
+ filePath:saveResult.publicPath!,
})
}
}
@@ -3119,17 +3059,6 @@ export async function createCbeEvaluation(formData: FormData) {
const files = formData.getAll("files") as File[]
const hasFiles = files && files.length > 0 && files[0].size > 0
- // 파일 저장을 위한 디렉토리 생성 (파일이 있는 경우에만)
- let uploadDir = ""
- if (hasFiles) {
- uploadDir = path.join(process.cwd(), "public", "rfq", String(rfqId))
- try {
- await fs.mkdir(uploadDir, { recursive: true })
- } catch (err) {
- console.error("디렉토리 생성 실패:", err)
- return { error: "파일 업로드를 위한 디렉토리 생성에 실패했습니다." }
- }
- }
// 첨부 파일 정보를 저장할 배열
const attachments: { filename: string; path: string }[] = []
@@ -3144,22 +3073,9 @@ export async function createCbeEvaluation(formData: FormData) {
const safeFilename = `cbe-${rfqId}-${timestamp}${fileExtension}`
const filePath = path.join("rfq", String(rfqId), safeFilename)
const fullPath = path.join(process.cwd(), "public", filePath)
+
+ const saveResult = await saveFile({file, directory:'rfq'})
- try {
- // File을 ArrayBuffer로 변환하여 파일 시스템에 저장
- const arrayBuffer = await file.arrayBuffer()
- const buffer = Buffer.from(arrayBuffer)
- await fs.writeFile(fullPath, buffer)
-
- // 첨부 파일 정보 추가
- attachments.push({
- filename: originalFilename,
- path: fullPath, // 이메일 첨부를 위한 전체 경로
- })
- } catch (err) {
- console.error(`파일 저장 실패:`, err)
- // 파일 저장 실패를 기록하지만 전체 프로세스는 계속 진행
- }
}
}
}