Files
SR-SYSTEM/src/components/ui/ExcelUploader.tsx
T
2026-06-05 11:22:13 +09:00

398 lines
13 KiB
TypeScript

'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>
);
}