import { execute, query, queryOne } from '../../../../utils/db' import { getClientIp } from '../../../../utils/ip' import { getCurrentUserEmail } from '../../../../utils/user' interface ProjectItem { projectId: number workDescription?: string planDescription?: string } interface UpdateReportBody { projects?: ProjectItem[] issueDescription?: string vacationDescription?: string remarkDescription?: string } /** * 주간보고 수정 * PUT /api/report/weekly/[id]/update */ export default defineEventHandler(async (event) => { const userId = getCookie(event, 'user_id') if (!userId) { throw createError({ statusCode: 401, message: '로그인이 필요합니다.' }) } const reportId = getRouterParam(event, 'id') const body = await readBody(event) const clientIp = getClientIp(event) const userEmail = await getCurrentUserEmail(event) // 보고서 조회 및 권한 확인 const report = await queryOne(` SELECT * FROM wr_weekly_report WHERE report_id = $1 `, [reportId]) if (!report) { throw createError({ statusCode: 404, message: '보고서를 찾을 수 없습니다.' }) } if (report.author_id !== parseInt(userId)) { throw createError({ statusCode: 403, message: '본인의 보고서만 수정할 수 있습니다.' }) } if (report.report_status === 'SUBMITTED' || report.report_status === 'AGGREGATED') { throw createError({ statusCode: 400, message: '제출된 보고서는 수정할 수 없습니다.' }) } // 마스터 업데이트 await execute(` UPDATE wr_weekly_report SET issue_description = $1, vacation_description = $2, remark_description = $3, updated_at = NOW(), updated_ip = $4, updated_email = $5 WHERE report_id = $6 `, [ body.issueDescription ?? report.issue_description, body.vacationDescription ?? report.vacation_description, body.remarkDescription ?? report.remark_description, clientIp, userEmail, reportId ]) // 프로젝트별 실적 업데이트 if (body.projects && body.projects.length > 0) { // 기존 삭제 후 재등록 await execute(`DELETE FROM wr_weekly_report_project WHERE report_id = $1`, [reportId]) for (const proj of body.projects) { await execute(` INSERT INTO wr_weekly_report_project ( report_id, project_id, work_description, plan_description, created_ip, created_email, updated_ip, updated_email ) VALUES ($1, $2, $3, $4, $5, $6, $5, $6) `, [ reportId, proj.projectId, proj.workDescription || null, proj.planDescription || null, clientIp, userEmail ]) } } return { success: true } })