- executeServerAction 공통 유틸 도입으로 actions.ts 대폭 간소화 (50+개 파일) - sanitize 유틸 추가 (XSS 방지) - middleware CSP 헤더 추가 및 Open Redirect 방지 - 프록시 라우트 로깅 개발환경 한정으로 변경 - 프로덕션 불필요 console.log 제거 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
273 lines
9.2 KiB
TypeScript
273 lines
9.2 KiB
TypeScript
/**
|
|
* 직원관리 서버 액션
|
|
*
|
|
* API Endpoints:
|
|
* - GET /api/v1/employees - 목록 조회
|
|
* - GET /api/v1/employees/{id} - 상세 조회
|
|
* - POST /api/v1/employees - 등록
|
|
* - PATCH /api/v1/employees/{id} - 수정
|
|
* - DELETE /api/v1/employees/{id} - 삭제
|
|
* - POST /api/v1/employees/bulk-delete - 일괄 삭제
|
|
* - GET /api/v1/employees/stats - 통계
|
|
*
|
|
* 🚨 401 에러 시 __authError: true 반환 → 클라이언트에서 로그인 페이지로 리다이렉트
|
|
*/
|
|
|
|
'use server';
|
|
|
|
|
|
import { executeServerAction } from '@/lib/api/execute-server-action';
|
|
import { isNextRedirectError } from '@/lib/utils/redirect-error';
|
|
import { cookies } from 'next/headers';
|
|
import type { Employee, EmployeeFormData, EmployeeStats } from './types';
|
|
import { transformApiToFrontend, transformFrontendToApi, type EmployeeApiData } from './utils';
|
|
|
|
// ============================================
|
|
// API 응답 타입 정의
|
|
// ============================================
|
|
|
|
interface ApiResponse<T> {
|
|
success: boolean;
|
|
data: T;
|
|
message: string;
|
|
}
|
|
|
|
interface PaginatedResponse<T> {
|
|
current_page: number;
|
|
data: T[];
|
|
total: number;
|
|
per_page: number;
|
|
last_page: number;
|
|
}
|
|
|
|
const API_URL = process.env.NEXT_PUBLIC_API_URL;
|
|
|
|
// ============================================
|
|
// API 함수
|
|
// ============================================
|
|
|
|
export async function getEmployees(params?: {
|
|
page?: number; per_page?: number; q?: string; status?: string;
|
|
department_id?: string; has_account?: boolean;
|
|
sort_by?: string; sort_dir?: 'asc' | 'desc';
|
|
}): Promise<{ data: Employee[]; total: number; lastPage: number; __authError?: boolean }> {
|
|
const searchParams = new URLSearchParams();
|
|
if (params?.page) searchParams.set('page', String(params.page));
|
|
if (params?.per_page) searchParams.set('per_page', String(params.per_page));
|
|
if (params?.q) searchParams.set('q', params.q);
|
|
if (params?.status && params.status !== 'all') searchParams.set('status', params.status);
|
|
if (params?.department_id) searchParams.set('department_id', params.department_id);
|
|
if (params?.has_account !== undefined) searchParams.set('has_account', String(params.has_account));
|
|
if (params?.sort_by) searchParams.set('sort_by', params.sort_by);
|
|
if (params?.sort_dir) searchParams.set('sort_dir', params.sort_dir);
|
|
|
|
const result = await executeServerAction<PaginatedResponse<EmployeeApiData>>({
|
|
url: `${API_URL}/api/v1/employees?${searchParams.toString()}`,
|
|
errorMessage: '직원 목록 조회에 실패했습니다.',
|
|
});
|
|
|
|
if (result.__authError) return { data: [], total: 0, lastPage: 1, __authError: true };
|
|
if (!result.success || !result.data?.data) return { data: [], total: 0, lastPage: 1 };
|
|
|
|
return {
|
|
data: result.data.data.map(transformApiToFrontend),
|
|
total: result.data.total,
|
|
lastPage: result.data.last_page,
|
|
};
|
|
}
|
|
|
|
export async function getEmployeeById(id: string): Promise<Employee | null | { __authError: true }> {
|
|
const result = await executeServerAction({
|
|
url: `${API_URL}/api/v1/employees/${id}`,
|
|
transform: (data: EmployeeApiData) => transformApiToFrontend(data),
|
|
errorMessage: '직원 조회에 실패했습니다.',
|
|
});
|
|
|
|
if (result.__authError) return { __authError: true };
|
|
return result.success ? result.data || null : null;
|
|
}
|
|
|
|
export async function createEmployee(
|
|
data: EmployeeFormData
|
|
): Promise<{
|
|
success: boolean; data?: Employee; error?: string;
|
|
errors?: Record<string, string[]>; status?: number; __authError?: boolean;
|
|
}> {
|
|
const apiData = transformFrontendToApi(data);
|
|
const result = await executeServerAction({
|
|
url: `${API_URL}/api/v1/employees`,
|
|
method: 'POST',
|
|
body: apiData,
|
|
transform: (d: EmployeeApiData) => transformApiToFrontend(d),
|
|
errorMessage: '직원 등록에 실패했습니다.',
|
|
});
|
|
|
|
if (result.__authError) return { success: false, __authError: true };
|
|
return { success: result.success, data: result.data, error: result.error };
|
|
}
|
|
|
|
export async function updateEmployee(
|
|
id: string,
|
|
data: EmployeeFormData
|
|
): Promise<{ success: boolean; data?: Employee; error?: string; __authError?: boolean }> {
|
|
const apiData = transformFrontendToApi(data);
|
|
const result = await executeServerAction({
|
|
url: `${API_URL}/api/v1/employees/${id}`,
|
|
method: 'PATCH',
|
|
body: apiData,
|
|
transform: (d: EmployeeApiData) => transformApiToFrontend(d),
|
|
errorMessage: '직원 수정에 실패했습니다.',
|
|
});
|
|
|
|
if (result.__authError) return { success: false, __authError: true };
|
|
return { success: result.success, data: result.data, error: result.error };
|
|
}
|
|
|
|
export async function deleteEmployee(id: string): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
|
|
const result = await executeServerAction({
|
|
url: `${API_URL}/api/v1/employees/${id}`,
|
|
method: 'DELETE',
|
|
errorMessage: '직원 삭제에 실패했습니다.',
|
|
});
|
|
|
|
if (result.__authError) return { success: false, __authError: true };
|
|
return { success: result.success, error: result.error };
|
|
}
|
|
|
|
export async function deleteEmployees(ids: string[]): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
|
|
const result = await executeServerAction({
|
|
url: `${API_URL}/api/v1/employees/bulk-delete`,
|
|
method: 'POST',
|
|
body: { ids: ids.map(id => parseInt(id, 10)) },
|
|
errorMessage: '직원 일괄 삭제에 실패했습니다.',
|
|
});
|
|
|
|
if (result.__authError) return { success: false, __authError: true };
|
|
return { success: result.success, error: result.error };
|
|
}
|
|
|
|
interface EmployeeStatsApiData {
|
|
active_count: number;
|
|
leave_count: number;
|
|
resigned_count: number;
|
|
average_tenure: number;
|
|
}
|
|
|
|
export async function getEmployeeStats(): Promise<EmployeeStats | null | { __authError: true }> {
|
|
const result = await executeServerAction<EmployeeStatsApiData>({
|
|
url: `${API_URL}/api/v1/employees/stats`,
|
|
errorMessage: '직원 통계 조회에 실패했습니다.',
|
|
});
|
|
|
|
if (result.__authError) return { __authError: true };
|
|
if (!result.success || !result.data) return null;
|
|
|
|
return {
|
|
activeCount: result.data.active_count ?? 0,
|
|
leaveCount: result.data.leave_count ?? 0,
|
|
resignedCount: result.data.resigned_count ?? 0,
|
|
averageTenure: result.data.average_tenure ?? 0,
|
|
};
|
|
}
|
|
|
|
// ============================================
|
|
// 직급/직책 조회 (native fetch - keep as-is)
|
|
// ============================================
|
|
|
|
export interface PositionItem {
|
|
id: number;
|
|
key: string;
|
|
name: string;
|
|
type: 'rank' | 'title';
|
|
sort_order: number;
|
|
is_active: boolean;
|
|
}
|
|
|
|
export async function getPositions(type?: 'rank' | 'title'): Promise<PositionItem[]> {
|
|
const searchParams = new URLSearchParams();
|
|
if (type) searchParams.set('type', type);
|
|
|
|
const result = await executeServerAction<PositionItem[]>({
|
|
url: `${API_URL}/api/v1/positions?${searchParams.toString()}`,
|
|
errorMessage: '직급/직책 조회에 실패했습니다.',
|
|
});
|
|
return result.data || [];
|
|
}
|
|
|
|
// ============================================
|
|
// 부서 조회 (native fetch - keep as-is)
|
|
// ============================================
|
|
|
|
export interface DepartmentItem {
|
|
id: number;
|
|
name: string;
|
|
code: string | null;
|
|
parent_id: number | null;
|
|
is_active: boolean;
|
|
}
|
|
|
|
export async function getDepartments(): Promise<DepartmentItem[]> {
|
|
const result = await executeServerAction<DepartmentItem[] | { data: DepartmentItem[] }>({
|
|
url: `${API_URL}/api/v1/departments`,
|
|
errorMessage: '부서 조회에 실패했습니다.',
|
|
});
|
|
if (!result.data) return [];
|
|
return Array.isArray(result.data) ? result.data : result.data.data || [];
|
|
}
|
|
|
|
// ============================================
|
|
// 파일 업로드 (native fetch - keep as-is)
|
|
// ============================================
|
|
|
|
export async function uploadProfileImage(inputFormData: FormData): Promise<{
|
|
success: boolean;
|
|
data?: { url: string; path: string };
|
|
error?: string;
|
|
__authError?: boolean;
|
|
}> {
|
|
try {
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get('access_token')?.value;
|
|
|
|
if (!token) return { success: false, __authError: true };
|
|
|
|
inputFormData.append('directory', 'employees/profiles');
|
|
|
|
const response = await fetch(
|
|
`${API_URL}/api/v1/files/upload`,
|
|
{
|
|
method: 'POST',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
'X-API-KEY': process.env.API_KEY || '',
|
|
},
|
|
body: inputFormData,
|
|
}
|
|
);
|
|
|
|
if (response.status === 401) return { success: false, __authError: true };
|
|
if (!response.ok) return { success: false, error: `파일 업로드 실패: ${response.status}` };
|
|
|
|
const result = await response.json();
|
|
if (!result.success) return { success: false, error: result.message || '파일 업로드에 실패했습니다.' };
|
|
|
|
const uploadedPath = result.data?.file_path || result.data?.path || result.data?.url;
|
|
if (!uploadedPath) return { success: false, error: '업로드된 파일 경로를 가져올 수 없습니다.' };
|
|
|
|
const storagePath = uploadedPath.startsWith('/storage/')
|
|
? uploadedPath
|
|
: `/storage/tenants/${uploadedPath}`;
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
url: `${API_URL}${storagePath}`,
|
|
path: uploadedPath,
|
|
},
|
|
};
|
|
} catch (error) {
|
|
if (isNextRedirectError(error)) throw error;
|
|
return { success: false, error: '서버 오류가 발생했습니다.' };
|
|
}
|
|
}
|