feat: Excel batch registration (equipment + employees)

This commit is contained in:
pray4skylark
2026-06-05 11:22:13 +09:00
parent eb5734aad6
commit 8b2607ddb3
9 changed files with 797 additions and 131 deletions
@@ -0,0 +1,45 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Users } from 'lucide-react';
import ExcelUploader from '@/components/ui/ExcelUploader';
import { useAuthStore } from '@/stores';
export default function BatchEmployeesPage() {
const router = useRouter();
const { user } = useAuthStore();
const [checked, setChecked] = useState(false);
useEffect(() => {
if (user?.roleCode !== 'ADMIN') {
router.push('/403');
} else {
setChecked(true);
}
}, [user, router]);
if (!checked) return null;
if (user?.roleCode !== 'ADMIN') return null;
return (
<div className="p-4 sm:p-6 lg:p-8">
<div className="max-w-7xl mx-auto">
<div className="flex items-center gap-3 mb-6">
<Users className="w-6 h-6 text-primary" />
<div>
<h1 className="font-outfit text-2xl font-semibold text-text-main tracking-tight">직원 일괄 등록</h1>
<p className="text-text-muted text-sm">엑셀 파일로 여러 직원 계정을 한 번에 등록합니다.</p>
</div>
</div>
<ExcelUploader
title="직원 일괄 등록"
description="템플릿을 다운로드하여 직원 정보를 작성한 후 업로드하세요."
templateUrl="/api/v1/employees/batch/template"
uploadUrl="/api/v1/employees/batch"
/>
</div>
</div>
);
}
+20 -131
View File
@@ -10,32 +10,20 @@ import {
RefreshCcw,
Zap
} from 'lucide-react';
import equipmentService from '@/services/equipmentService';
import type { Equipment, EquipmentType } from '@/types';
import ExcelUploader from '@/components/ui/ExcelUploader';
import type { EquipmentType } from '@/types';
interface ParsedItem {
row: number;
data: Partial<Equipment>;
error?: string;
}
interface ValidationResult {
row: number;
status: 'Error' | 'Warning' | 'Success';
field: string;
value: string;
message: string;
interface BatchRegistrationViewProps {
onRegisterSuccess?: () => void;
}
/**
* 대량 등록 (엑셀) 뷰 컴포넌트
* 엑셀 업로드 및 데이터 유효성 검증 프로세스를 제공합니다.
* ExcelUploader를 통한 서버사이드 엑셀 업로드 및 처리를 제공합니다.
*/
export default function BatchRegistrationView() {
export default function BatchRegistrationView({ onRegisterSuccess }: BatchRegistrationViewProps) {
const [isUploaded, setIsUploaded] = useState(false);
const [inputText, setInputText] = useState('');
const [parsedItems, setParsedItems] = useState<ParsedItem[]>([]);
const [validationResults, setValidationResults] = useState<ValidationResult[]>([]);
const [validationResults, setValidationResults] = useState<any[]>([]);
const [isProcessing, setIsProcessing] = useState(false);
const [successCount, setSuccessCount] = useState(0);
const [errorCount, setErrorCount] = useState(0);
@@ -47,100 +35,8 @@ export default function BatchRegistrationView() {
'ACCESSORY': 'ACCESSORY',
};
const parseInput = () => {
const lines = inputText.trim().split('\n');
const items: ParsedItem[] = [];
const errors: ValidationResult[] = [];
lines.forEach((line, index) => {
const row = index + 1;
const parts = line.split(',').map(p => p.trim());
if (parts.length < 7) {
errors.push({
row,
status: 'Error',
field: 'Format',
value: line,
message: '필수 항목이 부족합니다 (7 개 항목 필요)',
});
items.push({ row, data: {}, error: 'Invalid format' });
return;
}
const [equipmentType, manufacturer, modelName, serialNumber, assetCode, location, purchaseDate] = parts;
if (!typeMapping[equipmentType.toUpperCase()]) {
errors.push({
row,
status: 'Error',
field: 'EquipmentType',
value: equipmentType,
message: '허용되지 않는 장비 유형입니다 (LAPTOP, MONITOR, TEST_DEVICE, ACCESSORY)',
});
items.push({ row, data: {}, error: 'Invalid type' });
return;
}
items.push({
row,
data: {
equipmentType: typeMapping[equipmentType.toUpperCase()],
manufacturer,
modelName,
serialNumber,
assetCode,
specifications: { location },
status: 'AVAILABLE',
purchaseDate,
warrantyExpDate: '',
},
});
if (errors.length === 0) {
errors.push({
row,
status: 'Success',
field: 'All',
value: '-',
message: '정상',
});
}
});
setParsedItems(items);
setValidationResults(errors);
setIsUploaded(true);
};
const handleBatchRegister = async () => {
setIsProcessing(true);
setSuccessCount(0);
setErrorCount(0);
const validItems = parsedItems.filter(item => !item.error);
for (const item of validItems) {
try {
await equipmentService.create(item.data);
setSuccessCount(prev => prev + 1);
} catch (error: any) {
setErrorCount(prev => prev + 1);
setValidationResults(prev => prev.map(res =>
res.row === item.row
? { ...res, status: 'Error', message: error.response?.data?.message || '등록 실패' }
: res
));
}
}
setIsProcessing(false);
};
const handleReset = () => {
setIsUploaded(false);
setInputText('');
setParsedItems([]);
setValidationResults([]);
setSuccessCount(0);
setErrorCount(0);
@@ -168,32 +64,26 @@ export default function BatchRegistrationView() {
</button>
</div>
{/* Upload Card - Textarea Input */}
{/* Upload Card - ExcelUploader */}
<div className="bg-white p-8 rounded-[32px] border border-slate-200 shadow-sm flex flex-col justify-between">
<div>
<div className="w-12 h-12 rounded-2xl bg-blue-50 flex items-center justify-center mb-6">
<Upload className="w-6 h-6 text-blue-500" />
</div>
<h3 className="text-lg font-bold text-slate-900 mb-2">2. 데이터 입력</h3>
<h3 className="text-lg font-bold text-slate-900 mb-2">2. 엑셀 파일 업로드</h3>
<p className="text-xs text-slate-500 leading-relaxed mb-4">
각 줄마다 장비를 입력하세요: type,manufacturer,model,serial,assetCode,location,purchaseDate
작성한 엑셀 파일(.xlsx)을 업로드하면 서버에서 자동으로 파싱 및 검증 후 등록합니다.
</p>
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder={`LAPTOP,Samsung,NT500,SN-001,AST-2025-001,Seoul,2025-01-15
MONITOR,LG,27UP850,SN-002,AST-2025-002,Busan,2025-02-20`}
className="w-full h-40 p-4 bg-slate-50 border border-slate-200 rounded-xl text-xs font-mono focus:ring-2 focus:ring-primary/20 outline-none resize-none"
/>
</div>
<button
onClick={parseInput}
disabled={!inputText.trim()}
className="mt-4 flex items-center justify-center w-full py-4 bg-primary text-white rounded-2xl text-xs font-bold hover:bg-primary-hover transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
<CheckCircle2 className="w-4 h-4 mr-2" />
데이터 파싱 및 검증
</button>
<ExcelUploader
title="장비 일괄 등록"
description="엑셀 파일(.xlsx)로 여러 장비를 한 번에 등록합니다."
templateUrl="/api/v1/equipment/batch/template"
uploadUrl="/api/v1/equipment/batch"
onSuccess={(result) => {
if (onRegisterSuccess) onRegisterSuccess();
}}
/>
</div>
</div>
@@ -265,7 +155,6 @@ MONITOR,LG,27UP850,SN-002,AST-2025-002,Busan,2025-02-20`}
<span className="font-bold text-red-500">주의:</span> 오류가 있는 행을 모두 수정해야 일괄 등록이 가능합니다.
</p>
<button
onClick={handleBatchRegister}
disabled={isProcessing || validationResults.some(r => r.status === 'Error')}
className="bg-primary text-white px-8 py-3 rounded-2xl text-xs font-bold hover:bg-primary-hover transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
>
@@ -275,7 +164,7 @@ MONITOR,LG,27UP850,SN-002,AST-2025-002,Busan,2025-02-20`}
등록 중... ({successCount}건 완료)
</>
) : (
`일괄 등록 완료 (${parsedItems.filter(i => !i.error).length}건)`
`일괄 등록 완료`
)}
</button>
</div>
+1
View File
@@ -234,6 +234,7 @@ const Sidebar = ({ isCollapsed }: { isCollapsed?: boolean }) => {
{[
{ name: 'Codes', href: '/settings/codes', icon: Settings },
{ name: 'Accounts', href: '/settings/accounts', icon: Users },
{ name: 'Batch Employees', href: '/settings/batch/employees', icon: FileText },
{ name: 'System', href: '/settings/system', icon: Monitor },
{ name: 'Notification', href: '/settings/notification', icon: FileText },
{ name: 'Audit Log', href: '/settings/audit', icon: History },
+397
View File
@@ -0,0 +1,397 @@
'use client';
import React, { useState, useCallback, useRef } from 'react';
import {
Upload,
FileSpreadsheet,
Download,
CheckCircle2,
XCircle,
AlertCircle,
Loader2,
} from 'lucide-react';
export interface BatchResult {
totalCount: number;
successCount: number;
failCount: number;
failures: { row: number; reason: string }[];
data?: any[];
}
export interface ExcelUploaderProps {
title: string;
description?: string;
templateUrl?: string;
uploadUrl: string;
onSuccess?: (result: BatchResult) => void;
accept?: string;
}
interface PreviewData {
headers: string[];
rows: string[][];
}
export default function ExcelUploader({
title,
description,
templateUrl,
uploadUrl,
onSuccess,
accept = '.xlsx',
}: ExcelUploaderProps) {
const [file, setFile] = useState<File | null>(null);
const [preview, setPreview] = useState<PreviewData | null>(null);
const [rowCount, setRowCount] = useState(0);
const [isDragging, setIsDragging] = useState(false);
const [isUploading, setIsUploading] = useState(false);
const [result, setResult] = useState<BatchResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [showFailures, setShowFailures] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const resetState = useCallback(() => {
setFile(null);
setPreview(null);
setRowCount(0);
setResult(null);
setError(null);
setShowFailures(false);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}, []);
const handleFile = useCallback((selectedFile: File) => {
if (!selectedFile.name.endsWith('.xlsx')) {
setError('지원하지 않는 파일 형식입니다. .xlsx 파일을 선택해주세요.');
return;
}
setError(null);
setResult(null);
setFile(selectedFile);
setShowFailures(false);
// Parse file for preview (filename + row count estimation)
const reader = new FileReader();
reader.onload = (e) => {
try {
// Simple row count from binary content (approximate)
// In production, you'd use xlsx library for proper parsing
const content = e.target?.result;
if (content) {
// For preview purposes, we'll just show the filename
// A full xlsx parser would be needed for actual cell data
setRowCount(0); // Will be updated by server response
setPreview(null); // Preview requires xlsx library
}
} catch {
// Ignore parse errors for preview
}
};
reader.readAsArrayBuffer(selectedFile);
}, []);
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragging(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragging(false);
}, []);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragging(false);
const droppedFile = e.dataTransfer.files[0];
if (droppedFile) {
handleFile(droppedFile);
}
}, [handleFile]);
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0];
if (selectedFile) {
handleFile(selectedFile);
}
}, [handleFile]);
const handleUpload = useCallback(async () => {
if (!file) return;
setIsUploading(true);
setError(null);
setResult(null);
try {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(uploadUrl, {
method: 'POST',
body: formData,
});
const json = await response.json();
if (!response.ok || !json.success) {
throw new Error(json.message || '업로드 중 오류가 발생했습니다.');
}
const batchResult: BatchResult = json.data;
setResult(batchResult);
setRowCount(batchResult.totalCount);
if (batchResult.failCount === 0 && onSuccess) {
onSuccess(batchResult);
}
} catch (err) {
const message = err instanceof Error ? err.message : '알 수 없는 오류가 발생했습니다.';
setError(message);
} finally {
setIsUploading(false);
}
}, [file, uploadUrl, onSuccess]);
const handleDownloadTemplate = useCallback(() => {
if (templateUrl) {
window.open(templateUrl, '_blank');
}
}, [templateUrl]);
return (
<div className="rounded-2xl bg-white border border-gray-200 shadow-sm p-6">
{/* Header */}
<div className="mb-6">
<h3 className="text-lg font-semibold text-gray-900">{title}</h3>
{description && (
<p className="mt-1 text-sm text-gray-500">{description}</p>
)}
</div>
{/* Drop Zone */}
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={() => fileInputRef.current?.click()}
className={`
relative border-2 border-dashed rounded-xl p-8 text-center cursor-pointer
transition-colors duration-200
${isDragging
? 'border-indigo-500 bg-indigo-50'
: 'border-gray-300 hover:border-indigo-400 hover:bg-gray-50'
}
`}
>
<input
ref={fileInputRef}
type="file"
accept={accept}
onChange={handleFileSelect}
className="hidden"
/>
<FileSpreadsheet className="mx-auto h-10 w-10 text-gray-400" />
<p className="mt-3 text-sm text-gray-600">
엑셀 파일을 드래그하거나 <span className="text-indigo-600 font-medium">[파일 선택]</span>
</p>
<p className="mt-1 text-xs text-gray-400">지원 형식: {accept}</p>
</div>
{/* Template Download */}
{templateUrl && (
<div className="mt-4">
<button
type="button"
onClick={handleDownloadTemplate}
className="inline-flex items-center gap-2 text-sm text-indigo-600 hover:text-indigo-700 font-medium"
>
<Download className="h-4 w-4" />
템플릿 다운로드
</button>
</div>
)}
{/* File Info */}
{file && (
<div className="mt-6 p-4 bg-gray-50 rounded-xl border border-gray-200">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<FileSpreadsheet className="h-5 w-5 text-indigo-600" />
<div>
<p className="text-sm font-medium text-gray-900">{file.name}</p>
<p className="text-xs text-gray-500">
{rowCount > 0 ? `${rowCount}행` : '행 수 분석 중...'}
</p>
</div>
</div>
<button
type="button"
onClick={resetState}
className="text-xs text-gray-500 hover:text-gray-700"
>
취소
</button>
</div>
</div>
)}
{/* Preview Table */}
{preview && (
<div className="mt-6">
<h4 className="text-sm font-medium text-gray-700 mb-3">미리보기</h4>
<div className="overflow-x-auto rounded-lg border border-gray-200">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
{preview.headers.map((header, i) => (
<th
key={i}
className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
{header}
</th>
))}
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{preview.rows.slice(0, 5).map((row, i) => (
<tr key={i}>
{row.map((cell, j) => (
<td key={j} className="px-4 py-2 text-sm text-gray-900 whitespace-nowrap">
{cell}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{preview.rows.length > 5 && (
<p className="mt-2 text-xs text-gray-500">
상위 5행만 표시됩니다 (총 {preview.rows.length}행)
</p>
)}
</div>
)}
{/* Upload Button */}
{file && !result && (
<div className="mt-6">
<button
type="button"
onClick={handleUpload}
disabled={isUploading}
className="inline-flex items-center justify-center gap-2 px-6 py-2.5 bg-indigo-600 text-white text-sm font-medium rounded-xl hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isUploading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
업로드 중...
</>
) : (
<>
<Upload className="h-4 w-4" />
일괄 등록
</>
)}
</button>
</div>
)}
{/* Error State */}
{error && (
<div className="mt-6 p-4 bg-red-50 border border-red-200 rounded-xl">
<div className="flex items-start gap-3">
<AlertCircle className="h-5 w-5 text-red-500 mt-0.5 flex-shrink-0" />
<div>
<p className="text-sm font-medium text-red-800">오류</p>
<p className="mt-1 text-sm text-red-700">{error}</p>
</div>
</div>
</div>
)}
{/* Results */}
{result && (
<div className="mt-6 space-y-4">
{/* Summary */}
<div className={`p-4 rounded-xl border ${
result.failCount === 0
? 'bg-green-50 border-green-200'
: 'bg-amber-50 border-amber-200'
}`}>
<div className="flex items-center gap-3">
{result.failCount === 0 ? (
<CheckCircle2 className="h-5 w-5 text-green-600" />
) : (
<AlertCircle className="h-5 w-5 text-amber-600" />
)}
<p className={`text-sm font-medium ${
result.failCount === 0 ? 'text-green-800' : 'text-amber-800'
}`}>
{result.totalCount}건 중 {result.successCount}건 성공
{result.failCount > 0 && `, ${result.failCount}건 실패`}
</p>
</div>
</div>
{/* Failure Details */}
{result.failCount > 0 && (
<div className="border border-gray-200 rounded-xl overflow-hidden">
<button
type="button"
onClick={() => setShowFailures(!showFailures)}
className="w-full flex items-center justify-between px-4 py-3 bg-gray-50 hover:bg-gray-100 transition-colors"
>
<div className="flex items-center gap-2">
<XCircle className="h-4 w-4 text-red-500" />
<span className="text-sm font-medium text-gray-700">실패 상세</span>
<span className="text-xs text-gray-500">({result.failures.length}건)</span>
</div>
<svg
className={`h-4 w-4 text-gray-500 transition-transform ${showFailures ? 'rotate-180' : ''}`}
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{showFailures && (
<div className="divide-y divide-gray-200 max-h-64 overflow-y-auto">
{result.failures.map((failure, i) => (
<div key={i} className="px-4 py-3">
<div className="flex items-start gap-2">
<span className="text-xs font-mono text-gray-500 bg-gray-100 px-2 py-0.5 rounded">
Row {failure.row}
</span>
<p className="text-sm text-red-600">{failure.reason}</p>
</div>
</div>
))}
</div>
)}
</div>
)}
{/* Reset Button */}
<button
type="button"
onClick={resetState}
className="text-sm text-indigo-600 hover:text-indigo-700 font-medium"
>
다른 파일 업로드
</button>
</div>
)}
</div>
);
}