"use server" import db from '@/db/db'; import { ApprovalLine } from "./approval"; import { approval } from '@/db/schema/knox/approvals'; import { eq, and } from 'drizzle-orm'; // ========== 데이터베이스 서비스 함수들 ========== /** * 결재 상신 데이터를 데이터베이스에 저장 */ export async function saveApprovalToDatabase( apInfId: string, userId: string, epId: string, emailAddress: string, subject: string, content: string, aplns: ApprovalLine[] ): Promise { try { await db.insert(approval).values({ apInfId, userId, epId, emailAddress, subject, content, status: '1', // 진행중 상태로 초기 설정 aplns, isDeleted: false, createdAt: new Date(), updatedAt: new Date(), }); } catch (error) { console.error('결재 데이터 저장 실패:', error); throw new Error( '결재 데이터를 데이터베이스에 저장하는 중 오류가 발생했습니다.' ); } } /** * 결재 상태 업데이트 */ export async function updateApprovalStatus( apInfId: string, status: string ): Promise { try { await db .update(approval) .set({ status, updatedAt: new Date(), }) .where(eq(approval.apInfId, apInfId)); } catch (error) { console.error('결재 상태 업데이트 실패:', error); throw new Error('결재 상태를 업데이트하는 중 오류가 발생했습니다.'); } } /** * 결재 상세 정보 조회 */ export async function getApprovalFromDatabase( apInfId: string, includeDeleted: boolean = false ): Promise { try { const whereCondition = includeDeleted ? eq(approval.apInfId, apInfId) : and(eq(approval.apInfId, apInfId), eq(approval.isDeleted, false)); const result = await db .select() .from(approval) .where(whereCondition) .limit(1); return result[0] || null; } catch (error) { console.error('결재 데이터 조회 실패:', error); throw new Error('결재 데이터를 조회하는 중 오류가 발생했습니다.'); } } /** * 사용자별 결재 목록 조회 */ export async function getApprovalsByUser( userId: string, limit: number = 50, offset: number = 0, includeDeleted: boolean = false ): Promise { try { const whereCondition = includeDeleted ? eq(approval.userId, userId) : and(eq(approval.userId, userId), eq(approval.isDeleted, false)); const result = await db .select() .from(approval) .where(whereCondition) .orderBy(approval.createdAt) .limit(limit) .offset(offset); return result; } catch (error) { console.error('사용자 결재 목록 조회 실패:', error); throw new Error('사용자 결재 목록을 조회하는 중 오류가 발생했습니다.'); } } /** * 결재 삭제 (상신 취소 시) - Soft Delete */ export async function deleteApprovalFromDatabase( apInfId: string ): Promise { try { await db .update(approval) .set({ isDeleted: true, updatedAt: new Date(), }) .where(eq(approval.apInfId, apInfId)); } catch (error) { console.error('결재 데이터 삭제 실패:', error); throw new Error('결재 데이터를 삭제하는 중 오류가 발생했습니다.'); } }