summaryrefslogtreecommitdiff
path: root/lib/pos
diff options
context:
space:
mode:
authorjoonhoekim <26rote@gmail.com>2025-10-30 10:35:26 +0900
committerjoonhoekim <26rote@gmail.com>2025-10-30 10:35:26 +0900
commit284f9f40d9494168f3e68eedd9af067c38362eea (patch)
treeac26b3e9fab46b996c16bfa7a7add8f26ddb5042 /lib/pos
parent88f13ab89d2250e52c3375b077328a933a5762ec (diff)
(김준회) refactor: POS: 온디맨드로 다운로드받도록 변경, 매핑로직에선 pos 관련 로직 제거
Diffstat (limited to 'lib/pos')
-rw-r--r--lib/pos/components/pos-file-selection-dialog.tsx134
-rw-r--r--lib/pos/download-on-demand-action.ts193
-rw-r--r--lib/pos/index.ts24
-rw-r--r--lib/pos/sync-rfq-pos-files.ts407
4 files changed, 346 insertions, 412 deletions
diff --git a/lib/pos/components/pos-file-selection-dialog.tsx b/lib/pos/components/pos-file-selection-dialog.tsx
new file mode 100644
index 00000000..29936d21
--- /dev/null
+++ b/lib/pos/components/pos-file-selection-dialog.tsx
@@ -0,0 +1,134 @@
+"use client"
+
+import * as React from "react"
+import { Download, FileText } from "lucide-react"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog"
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table"
+import { Button } from "@/components/ui/button"
+import { ScrollArea } from "@/components/ui/scroll-area"
+import { Badge } from "@/components/ui/badge"
+
+interface PosFileInfo {
+ fileName: string
+ dcmtmId: string
+ projNo: string
+ posNo: string
+ posRevNo: string
+ fileSer: string
+}
+
+interface PosFileSelectionDialogProps {
+ isOpen: boolean
+ onClose: () => void
+ materialCode: string
+ files: PosFileInfo[]
+ onDownload: (fileIndex: number, fileName: string) => void
+ downloadingIndex: number | null
+}
+
+export function PosFileSelectionDialog({
+ isOpen,
+ onClose,
+ materialCode,
+ files,
+ onDownload,
+ downloadingIndex,
+}: PosFileSelectionDialogProps) {
+ return (
+ <Dialog open={isOpen} onOpenChange={onClose}>
+ <DialogContent className="max-w-4xl">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <FileText className="h-5 w-5 text-green-600" />
+ POS 파일 선택
+ </DialogTitle>
+ <DialogDescription>
+ 자재코드 <Badge variant="outline" className="font-mono">{materialCode}</Badge>에 대한
+ POS 파일 <Badge variant="secondary">{files.length}개</Badge>가 있습니다.
+ 다운로드할 파일을 선택해주세요.
+ </DialogDescription>
+ </DialogHeader>
+
+ <ScrollArea className="max-h-[60vh]">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[50px]">번호</TableHead>
+ <TableHead>파일명</TableHead>
+ <TableHead className="w-[120px]">프로젝트</TableHead>
+ <TableHead className="w-[150px]">POS 번호</TableHead>
+ <TableHead className="w-[80px]">리비전</TableHead>
+ <TableHead className="w-[80px]">파일 SEQ</TableHead>
+ <TableHead className="w-[120px] text-center">다운로드</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {files.map((file, index) => (
+ <TableRow key={`${file.dcmtmId}-${index}`}>
+ <TableCell className="text-center font-mono text-sm">
+ #{index + 1}
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <FileText className="h-4 w-4 text-blue-500 flex-shrink-0" />
+ <span className="text-sm font-medium truncate" title={file.fileName}>
+ {file.fileName}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell>
+ <span className="text-xs font-mono">{file.projNo}</span>
+ </TableCell>
+ <TableCell>
+ <span className="text-xs font-mono">{file.posNo}</span>
+ </TableCell>
+ <TableCell>
+ <Badge variant="outline" className="text-xs">
+ {file.posRevNo}
+ </Badge>
+ </TableCell>
+ <TableCell>
+ <span className="text-xs font-mono">{file.fileSer}</span>
+ </TableCell>
+ <TableCell className="text-center">
+ <Button
+ size="sm"
+ variant="default"
+ onClick={() => onDownload(index, file.fileName)}
+ disabled={downloadingIndex !== null}
+ className="w-full"
+ >
+ <Download className="h-3 w-3 mr-1" />
+ {downloadingIndex === index ? '다운로드 중...' : '다운로드'}
+ </Button>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </ScrollArea>
+
+ {files.length === 0 && (
+ <div className="text-center py-8 text-muted-foreground">
+ <FileText className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
+ <p>사용 가능한 POS 파일이 없습니다.</p>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+ )
+}
+
diff --git a/lib/pos/download-on-demand-action.ts b/lib/pos/download-on-demand-action.ts
new file mode 100644
index 00000000..568bae22
--- /dev/null
+++ b/lib/pos/download-on-demand-action.ts
@@ -0,0 +1,193 @@
+/**
+ * POS 파일 온디맨드 다운로드 서버 액션
+ *
+ * 클라이언트 컴포넌트에서 자재코드로 POS 파일을 다운로드할 수 있는 함수들을 제공합니다.
+ */
+
+'use server';
+
+import { getDcmtmIdByMaterialCode } from './get-dcmtm-id';
+
+export interface DownloadPosOnDemandResult {
+ success: boolean;
+ downloadUrl?: string;
+ fileName?: string;
+ availableFiles?: Array<{
+ fileName: string;
+ dcmtmId: string;
+ projNo: string;
+ posNo: string;
+ posRevNo: string;
+ fileSer: string;
+ }>;
+ error?: string;
+}
+
+/**
+ * 자재코드로 POS 파일 다운로드 URL을 생성합니다.
+ *
+ * @param materialCode - 자재코드 (MATNR)
+ * @param fileIndex - 여러 파일이 있을 경우 선택할 파일 인덱스 (기본값: 0)
+ * @returns 다운로드 URL과 파일 정보
+ *
+ * @example
+ * ```typescript
+ * const result = await getDownloadUrlByMaterialCode('SN2693A6410100001');
+ * if (result.success && result.downloadUrl) {
+ * window.open(result.downloadUrl, '_blank');
+ * }
+ * ```
+ */
+export async function getDownloadUrlByMaterialCode(
+ materialCode: string,
+ fileIndex: number = 0
+): Promise<DownloadPosOnDemandResult> {
+ try {
+ if (!materialCode || materialCode.trim() === '') {
+ return {
+ success: false,
+ error: '자재코드가 제공되지 않았습니다.',
+ };
+ }
+
+ // 1. 자재코드로 DCMTM_ID 및 파일 정보 조회
+ const dcmtmResult = await getDcmtmIdByMaterialCode({ materialCode });
+
+ if (!dcmtmResult.success || !dcmtmResult.files || dcmtmResult.files.length === 0) {
+ return {
+ success: false,
+ error: dcmtmResult.error || '해당 자재코드에 대한 POS 파일을 찾을 수 없습니다.',
+ };
+ }
+
+ // 파일 인덱스 범위 검증
+ if (fileIndex >= dcmtmResult.files.length) {
+ return {
+ success: false,
+ error: `파일 인덱스가 범위를 벗어났습니다. 사용 가능한 파일 수: ${dcmtmResult.files.length}`,
+ availableFiles: dcmtmResult.files.map(file => ({
+ fileName: file.fileName,
+ dcmtmId: file.dcmtmId,
+ projNo: file.projNo,
+ posNo: file.posNo,
+ posRevNo: file.posRevNo,
+ fileSer: file.fileSer,
+ })),
+ };
+ }
+
+ const selectedFile = dcmtmResult.files[fileIndex];
+
+ // 2. 다운로드 URL 생성
+ const downloadUrl = `/api/pos/download-on-demand?materialCode=${encodeURIComponent(materialCode)}&fileIndex=${fileIndex}`;
+
+ return {
+ success: true,
+ downloadUrl,
+ fileName: selectedFile.fileName,
+ availableFiles: dcmtmResult.files.map(file => ({
+ fileName: file.fileName,
+ dcmtmId: file.dcmtmId,
+ projNo: file.projNo,
+ posNo: file.posNo,
+ posRevNo: file.posRevNo,
+ fileSer: file.fileSer,
+ })),
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.',
+ };
+ }
+}
+
+/**
+ * 여러 자재코드에 대한 POS 파일 다운로드 URL을 일괄 조회합니다.
+ *
+ * @param materialCodes - 자재코드 배열
+ * @returns 각 자재코드별 다운로드 정보
+ *
+ * @example
+ * ```typescript
+ * const results = await getDownloadUrlsForMaterialCodes([
+ * 'SN2693A6410100001',
+ * 'SN2693A6410100002'
+ * ]);
+ *
+ * results.forEach(result => {
+ * if (result.success) {
+ * console.log(`${result.materialCode}: ${result.downloadUrl}`);
+ * }
+ * });
+ * ```
+ */
+export async function getDownloadUrlsForMaterialCodes(
+ materialCodes: string[]
+): Promise<Array<DownloadPosOnDemandResult & { materialCode: string }>> {
+ const results = await Promise.all(
+ materialCodes.map(async (materialCode) => {
+ const result = await getDownloadUrlByMaterialCode(materialCode);
+ return {
+ materialCode,
+ ...result,
+ };
+ })
+ );
+
+ return results;
+}
+
+/**
+ * 자재코드의 POS 파일 존재 여부를 확인합니다.
+ *
+ * @param materialCode - 자재코드 (MATNR)
+ * @returns 파일 존재 여부와 파일 수
+ */
+export async function checkPosFileExists(
+ materialCode: string
+): Promise<{
+ exists: boolean;
+ fileCount: number;
+ files?: Array<{
+ fileName: string;
+ dcmtmId: string;
+ projNo: string;
+ posNo: string;
+ posRevNo: string;
+ fileSer: string;
+ }>;
+ error?: string;
+}> {
+ try {
+ const dcmtmResult = await getDcmtmIdByMaterialCode({ materialCode });
+
+ if (!dcmtmResult.success || !dcmtmResult.files) {
+ return {
+ exists: false,
+ fileCount: 0,
+ error: dcmtmResult.error,
+ };
+ }
+
+ return {
+ exists: dcmtmResult.files.length > 0,
+ fileCount: dcmtmResult.files.length,
+ files: dcmtmResult.files.map(file => ({
+ fileName: file.fileName,
+ dcmtmId: file.dcmtmId,
+ projNo: file.projNo,
+ posNo: file.posNo,
+ posRevNo: file.posRevNo,
+ fileSer: file.fileSer,
+ })),
+ };
+ } catch (error) {
+ return {
+ exists: false,
+ fileCount: 0,
+ error: error instanceof Error ? error.message : '알 수 없는 오류',
+ };
+ }
+}
+
diff --git a/lib/pos/index.ts b/lib/pos/index.ts
index 75309bdd..d889f8c1 100644
--- a/lib/pos/index.ts
+++ b/lib/pos/index.ts
@@ -1,4 +1,16 @@
-// POS 관련 모든 기능을 하나로 통합하는 인덱스 파일
+/**
+ * POS (Purchase Order Specification) 파일 관련 기능 통합 모듈
+ *
+ * 주요 기능:
+ * - MATNR(자재코드)로 DCMTM_ID 조회
+ * - SOAP API를 통한 POS 파일 경로 조회
+ * - NFS 네트워크 드라이브에서 파일 다운로드
+ * - 온디맨드 방식의 POS 파일 다운로드 (자동 동기화 제거됨)
+ *
+ * 주요 변경사항:
+ * - syncRfqPosFiles 함수 제거됨 (온디맨드 방식으로 대체)
+ * - getDownloadUrlByMaterialCode 등 새로운 온디맨드 함수 추가
+ */
import { getEncryptDocumentumFile } from './get-pos';
import { createDownloadUrl } from './download-pos-file';
@@ -20,16 +32,18 @@ export {
} from './get-dcmtm-id';
export {
- syncRfqPosFiles
-} from './sync-rfq-pos-files';
-
-export {
getDesignDocumentByMaterialCode,
getDesignDocumentsForRfqItems,
getDesignDocumentByMaterialCodeAction,
getDesignDocumentsForRfqItemsAction
} from './design-document-service';
+export {
+ getDownloadUrlByMaterialCode,
+ getDownloadUrlsForMaterialCodes,
+ checkPosFileExists
+} from './download-on-demand-action';
+
// 타입들은 ./types 에서 export
export type * from './types';
diff --git a/lib/pos/sync-rfq-pos-files.ts b/lib/pos/sync-rfq-pos-files.ts
deleted file mode 100644
index acb34f20..00000000
--- a/lib/pos/sync-rfq-pos-files.ts
+++ /dev/null
@@ -1,407 +0,0 @@
-'use server';
-
-import db from '@/db/db';
-import { rfqPrItems, rfqLastAttachments, rfqLastAttachmentRevisions } from '@/db/schema/rfqLast';
-import { eq, and, ne } from 'drizzle-orm';
-import { getDcmtmIdByMaterialCode } from './get-dcmtm-id';
-import { getEncryptDocumentumFile } from './get-pos';
-import { downloadPosFile } from './download-pos-file';
-import type { PosFileSyncResult } from './types';
-import path from 'path';
-import fs from 'fs/promises';
-import { revalidatePath } from 'next/cache';
-import { debugLog, debugError, debugSuccess, debugProcess, debugWarn } from '@/lib/debug-utils';
-
-
-/**
- * RFQ의 모든 PR Items의 MATNR로 POS 파일을 조회하고 서버에 다운로드하여 저장
- */
-export async function syncRfqPosFiles(
- rfqId: number,
- userId: number
-): Promise<PosFileSyncResult> {
- debugLog(`🚀 POS 파일 동기화 시작`, { rfqId, userId });
-
- const result: PosFileSyncResult = {
- success: false,
- processedCount: 0,
- successCount: 0,
- failedCount: 0,
- errors: [],
- details: []
- };
-
- try {
- // 1. RFQ의 모든 PR Items 조회 (materialCode 중복 제거)
- debugProcess(`📋 RFQ PR Items 조회 시작 (RFQ ID: ${rfqId})`);
-
- const prItems = await db
- .selectDistinct({
- materialCode: rfqPrItems.materialCode,
- materialDescription: rfqPrItems.materialDescription,
- })
- .from(rfqPrItems)
- .where(and(
- eq(rfqPrItems.rfqsLastId, rfqId),
- // materialCode가 null이 아닌 것만
- ))
- .then(items => items.filter(item => item.materialCode && item.materialCode.trim() !== ''));
-
- debugLog(`📦 조회된 PR Items`, {
- totalCount: prItems.length,
- materialCodes: prItems.map(item => item.materialCode)
- });
-
- if (prItems.length === 0) {
- debugWarn(`⚠️ 처리할 자재코드가 없습니다 (RFQ ID: ${rfqId})`);
- result.errors.push('처리할 자재코드가 없습니다.');
- return result;
- }
-
- result.processedCount = prItems.length;
- debugSuccess(`✅ 처리할 자재코드 ${prItems.length}개 발견`);
-
- // 2. 각 자재코드별로 POS 파일 처리
- debugProcess(`🔄 자재코드별 POS 파일 처리 시작`);
-
- for (const prItem of prItems) {
- const materialCode = prItem.materialCode!;
- debugLog(`📋 자재코드 처리 시작: ${materialCode}`);
-
- try {
- // 2-1. 자재코드로 DCMTM_ID 조회
- debugProcess(`🔍 DCMTM_ID 조회 시작 (자재코드: ${materialCode})`);
- const dcmtmResult = await getDcmtmIdByMaterialCode({ materialCode });
-
- debugLog(`🎯 DCMTM_ID 조회 결과`, {
- materialCode,
- success: dcmtmResult.success,
- fileCount: dcmtmResult.files?.length || 0,
- files: dcmtmResult.files
- });
-
- if (!dcmtmResult.success || !dcmtmResult.files || dcmtmResult.files.length === 0) {
- debugWarn(`⚠️ DCMTM_ID 조회 실패 또는 파일 없음 (자재코드: ${materialCode})`, dcmtmResult.error);
- result.details.push({
- materialCode,
- status: 'no_files',
- error: dcmtmResult.error || 'POS 파일을 찾을 수 없음'
- });
- continue;
- }
-
- // 여러 파일이 있을 경우 첫 번째 파일만 처리
- const posFile = dcmtmResult.files[0];
- debugLog(`📁 처리할 POS 파일 선택`, {
- materialCode,
- selectedFile: posFile,
- totalFiles: dcmtmResult.files.length
- });
-
- // 2-2. POS API로 파일 경로 가져오기
- debugProcess(`🌐 POS API 호출 시작 (DCMTM_ID: ${posFile.dcmtmId})`);
- const posResult = await getEncryptDocumentumFile({
- objectID: posFile.dcmtmId
- });
-
- debugLog(`🌐 POS API 호출 결과`, {
- materialCode,
- dcmtmId: posFile.dcmtmId,
- success: posResult.success,
- resultPath: posResult.result,
- error: posResult.error
- });
-
- if (!posResult.success || !posResult.result) {
- debugError(`❌ POS API 호출 실패 (자재코드: ${materialCode})`, posResult.error);
- result.details.push({
- materialCode,
- fileName: posFile.fileName,
- status: 'failed',
- error: posResult.error || 'POS 파일 경로 조회 실패'
- });
- result.failedCount++;
- continue;
- }
-
- // 2-3. 내부망에서 파일 다운로드
- debugProcess(`⬇️ 파일 다운로드 시작 (경로: ${posResult.result})`);
- const downloadResult = await downloadPosFile({
- relativePath: posResult.result
- });
-
- debugLog(`⬇️ 파일 다운로드 결과`, {
- materialCode,
- success: downloadResult.success,
- fileName: downloadResult.fileName,
- fileSize: downloadResult.fileBuffer?.length,
- mimeType: downloadResult.mimeType,
- error: downloadResult.error
- });
-
- if (!downloadResult.success || !downloadResult.fileBuffer) {
- debugError(`❌ 파일 다운로드 실패 (자재코드: ${materialCode})`, downloadResult.error);
- result.details.push({
- materialCode,
- fileName: posFile.fileName,
- status: 'failed',
- error: downloadResult.error || '파일 다운로드 실패'
- });
- result.failedCount++;
- continue;
- }
-
- // 2-4. 서버 파일 시스템에 저장
- debugProcess(`💾 서버 파일 저장 시작 (파일명: ${downloadResult.fileName || `${materialCode}.pdf`})`);
- const saveResult = await saveFileToServer(
- downloadResult.fileBuffer,
- downloadResult.fileName || `${materialCode}.pdf`
- );
-
- debugLog(`💾 서버 파일 저장 결과`, {
- materialCode,
- success: saveResult.success,
- filePath: saveResult.filePath,
- fileName: saveResult.fileName,
- error: saveResult.error
- });
-
- if (!saveResult.success) {
- debugError(`❌ 서버 파일 저장 실패 (자재코드: ${materialCode})`, saveResult.error);
- result.details.push({
- materialCode,
- fileName: posFile.fileName,
- status: 'failed',
- error: saveResult.error || '서버 파일 저장 실패'
- });
- result.failedCount++;
- continue;
- }
-
- // 2-5. 데이터베이스에 첨부파일 정보 저장
- debugProcess(`🗄️ DB 첨부파일 정보 저장 시작 (자재코드: ${materialCode})`);
- const dbResult = await saveAttachmentToDatabase(
- rfqId,
- materialCode,
- { dcmtmId: posFile.dcmtmId, fileName: posFile.fileName },
- saveResult.filePath!,
- saveResult.fileName!,
- downloadResult.fileBuffer.length,
- downloadResult.mimeType || 'application/pdf',
- userId
- );
-
- debugLog(`🗄️ DB 저장 결과`, {
- materialCode,
- success: dbResult.success,
- error: dbResult.error
- });
-
- if (!dbResult.success) {
- debugError(`❌ DB 저장 실패 (자재코드: ${materialCode})`, dbResult.error);
- result.details.push({
- materialCode,
- fileName: posFile.fileName,
- status: 'failed',
- error: dbResult.error || 'DB 저장 실패'
- });
- result.failedCount++;
- continue;
- }
-
- debugSuccess(`✅ 자재코드 ${materialCode} 처리 완료`);
- result.details.push({
- materialCode,
- fileName: posFile.fileName,
- status: 'success'
- });
- result.successCount++;
-
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : '알 수 없는 오류';
- debugError(`❌ 자재코드 ${materialCode} 처리 중 예외 발생`, { error: errorMessage, stack: error instanceof Error ? error.stack : undefined });
- result.details.push({
- materialCode,
- status: 'failed',
- error: errorMessage
- });
- result.failedCount++;
- result.errors.push(`${materialCode}: ${errorMessage}`);
- }
- }
-
- result.success = result.successCount > 0;
-
- debugLog(`📊 POS 파일 동기화 최종 결과`, {
- rfqId,
- processedCount: result.processedCount,
- successCount: result.successCount,
- failedCount: result.failedCount,
- success: result.success,
- errors: result.errors
- });
-
- // 캐시 무효화
- debugProcess(`🔄 캐시 무효화 (경로: /evcp/rfq-last/${rfqId})`);
- revalidatePath(`/evcp/rfq-last/${rfqId}`);
-
- debugSuccess(`🎉 POS 파일 동기화 완료 (성공: ${result.successCount}건, 실패: ${result.failedCount}건)`);
- return result;
-
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : '알 수 없는 오류';
- debugError(`❌ POS 파일 동기화 전체 처리 오류`, { error: errorMessage, stack: error instanceof Error ? error.stack : undefined });
- result.errors.push(`전체 처리 오류: ${errorMessage}`);
- return result;
- }
-}
-
-/**
- * 파일을 서버 파일 시스템에 저장
- */
-async function saveFileToServer(
- fileBuffer: Buffer,
- originalFileName: string
-): Promise<{
- success: boolean;
- filePath?: string;
- fileName?: string;
- error?: string;
-}> {
- try {
- // uploads/pos 디렉토리 생성
- const uploadDir = path.join(process.cwd(), 'uploads', 'pos');
-
- try {
- await fs.access(uploadDir);
- } catch {
- await fs.mkdir(uploadDir, { recursive: true });
- }
-
- // 고유한 파일명 생성 (타임스탬프 + 원본명)
- const timestamp = Date.now();
- const sanitizedFileName = originalFileName.replace(/[^a-zA-Z0-9.-]/g, '_');
- const fileName = `${timestamp}_${sanitizedFileName}`;
- const filePath = path.join(uploadDir, fileName);
-
- // 파일 저장
- await fs.writeFile(filePath, fileBuffer);
-
- return {
- success: true,
- filePath: `uploads/pos/${fileName}`, // 상대 경로로 저장
- fileName: originalFileName
- };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : '파일 저장 실패'
- };
- }
-}
-
-/**
- * 첨부파일 정보를 데이터베이스에 저장
- */
-async function saveAttachmentToDatabase(
- rfqId: number,
- materialCode: string,
- posFileInfo: { dcmtmId: string; fileName: string },
- filePath: string,
- originalFileName: string,
- fileSize: number,
- fileType: string,
- userId: number
-): Promise<{
- success: boolean;
- error?: string;
-}> {
- try {
- await db.transaction(async (tx) => {
- // 1. 기존 동일한 자재코드의 설계 첨부파일이 있는지 확인
- const existingAttachment = await tx
- .select()
- .from(rfqLastAttachments)
- .where(and(
- eq(rfqLastAttachments.rfqId, rfqId),
- eq(rfqLastAttachments.attachmentType, '설계'),
- eq(rfqLastAttachments.serialNo, materialCode)
- ))
- .limit(1);
-
- let attachmentId: number;
-
- if (existingAttachment.length > 0) {
- // 기존 첨부파일이 있으면 업데이트
- attachmentId = existingAttachment[0].id;
-
- await tx
- .update(rfqLastAttachments)
- .set({
- currentRevision: 'Rev.1', // 새 리비전으로 업데이트
- description: `${posFileInfo.fileName} (자재코드: ${materialCode})`,
- updatedAt: new Date()
- })
- .where(eq(rfqLastAttachments.id, attachmentId));
- } else {
- // 새 첨부파일 생성
- const [newAttachment] = await tx
- .insert(rfqLastAttachments)
- .values({
- attachmentType: '설계',
- serialNo: materialCode,
- rfqId,
- currentRevision: 'Rev.0',
- description: `${posFileInfo.fileName} (자재코드: ${materialCode})`,
- createdBy: userId,
- createdAt: new Date(),
- updatedAt: new Date()
- })
- .returning({ id: rfqLastAttachments.id });
-
- attachmentId = newAttachment.id;
- }
-
- // 2. 새 리비전 생성
- const [newRevision] = await tx
- .insert(rfqLastAttachmentRevisions)
- .values({
- attachmentId,
- revisionNo: 'Rev.0',
- fileName: path.basename(filePath),
- originalFileName,
- filePath,
- fileSize,
- fileType,
- isLatest: true,
- revisionComment: `POS 시스템에서 자동 동기화됨 (DCMTM_ID: ${posFileInfo.dcmtmId})`,
- createdBy: userId
- })
- .returning({ id: rfqLastAttachmentRevisions.id });
-
- // 3. 첨부파일의 latestRevisionId 업데이트
- await tx
- .update(rfqLastAttachments)
- .set({
- latestRevisionId: newRevision.id
- })
- .where(eq(rfqLastAttachments.id, attachmentId));
-
- // 4. 기존 리비전들의 isLatest를 false로 업데이트
- await tx
- .update(rfqLastAttachmentRevisions)
- .set({ isLatest: false })
- .where(and(
- eq(rfqLastAttachmentRevisions.attachmentId, attachmentId),
- ne(rfqLastAttachmentRevisions.id, newRevision.id)
- ));
- });
-
- return { success: true };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'DB 저장 실패'
- };
- }
-}