feat: Excel batch registration (equipment + employees)
This commit is contained in:
@@ -34,6 +34,8 @@ dependencies {
|
||||
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.5'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-batch'
|
||||
implementation 'org.postgresql:postgresql'
|
||||
implementation 'org.apache.poi:poi-ooxml:5.2.5'
|
||||
implementation 'com.opencsv:opencsv:5.9'
|
||||
implementation 'org.projectlombok:lombok:1.18.38'
|
||||
annotationProcessor 'org.projectlombok:lombok:1.18.38'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.srsystem.controller;
|
||||
|
||||
import com.srsystem.config.jwt.CurrentUser;
|
||||
import com.srsystem.dto.ApiResponse;
|
||||
import com.srsystem.dto.BatchResult;
|
||||
import com.srsystem.dto.ChangePasswordRequest;
|
||||
import com.srsystem.dto.EmployeeSearchResult;
|
||||
import com.srsystem.dto.EmployeeSummary;
|
||||
@@ -14,6 +15,7 @@ import com.srsystem.entity.EquipmentAssignment;
|
||||
import com.srsystem.entity.enums.DispatchStatus;
|
||||
import com.srsystem.entity.enums.EmpStatus;
|
||||
import com.srsystem.entity.enums.RoleCode;
|
||||
import com.srsystem.util.ExcelParser;
|
||||
import com.srsystem.repository.EquipmentAssignmentRepository;
|
||||
import com.srsystem.service.DispatchHistoryService;
|
||||
import com.srsystem.service.EmployeeService;
|
||||
@@ -27,12 +29,16 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -250,4 +256,78 @@ public class EmployeeController {
|
||||
employeeService.changePassword(currentUser.getEmpId(), request);
|
||||
return ResponseEntity.ok(ApiResponse.ok("비밀번호가 변경되었습니다", null));
|
||||
}
|
||||
|
||||
// ---- Batch ----
|
||||
|
||||
@Operation(summary = "직원 일괄 등록", description = "엑셀 파일로 직원을 일괄 등록합니다")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@PostMapping("/batch")
|
||||
@Transactional
|
||||
public ResponseEntity<ApiResponse<BatchResult<Employee>>> batchCreate(@RequestParam("file") MultipartFile file) {
|
||||
try {
|
||||
ExcelParser.ParseResult<Employee> parsed = ExcelParser.parse(
|
||||
file,
|
||||
(row) -> {
|
||||
Employee emp = new Employee();
|
||||
emp.setLoginId(row.getOrDefault("로그인ID", ""));
|
||||
emp.setName(row.getOrDefault("이름", ""));
|
||||
emp.setEmail(row.getOrDefault("이메일", ""));
|
||||
emp.setPhone(row.getOrDefault("전화번호", ""));
|
||||
emp.setRoleCode(RoleCode.valueOf(row.getOrDefault("권한", "EMPLOYEE").toUpperCase()));
|
||||
emp.setEmpStatus(EmpStatus.valueOf(row.getOrDefault("재직상태", "ACTIVE").toUpperCase()));
|
||||
emp.setDispatchStatus(DispatchStatus.valueOf(row.getOrDefault("파견상태", "WAITING").toUpperCase()));
|
||||
emp.setPassword("batch1234!");
|
||||
if (row.containsKey("생년월일")) emp.setBirthDate(java.time.LocalDate.parse(row.get("생년월일")));
|
||||
if (row.containsKey("학력")) emp.setEducation(row.get("학력"));
|
||||
if (row.containsKey("학과")) emp.setMajor(row.get("학과"));
|
||||
if (row.containsKey("입사일")) emp.setJoinedDate(java.time.LocalDate.parse(row.get("입사일")));
|
||||
return emp;
|
||||
},
|
||||
List.of()
|
||||
);
|
||||
|
||||
List<BatchResult.Failure> failures = new ArrayList<>();
|
||||
List<Employee> success = new ArrayList<>();
|
||||
for (var pf : parsed.failures()) {
|
||||
failures.add(new BatchResult.Failure(pf.row(), pf.reason()));
|
||||
}
|
||||
|
||||
for (int i = 0; i < parsed.data().size(); i++) {
|
||||
try {
|
||||
Employee emp = employeeService.create(parsed.data().get(i));
|
||||
success.add(emp);
|
||||
} catch (Exception e) {
|
||||
failures.add(new BatchResult.Failure(i + 2, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
BatchResult<Employee> result = new BatchResult<>(
|
||||
parsed.data().size() + parsed.failures().size(),
|
||||
success.size(), failures.size(), failures, success
|
||||
);
|
||||
return ResponseEntity.ok(ApiResponse.ok(
|
||||
String.format("%d건 중 %d건 성공, %d건 실패", result.totalCount(), result.successCount(), result.failCount()),
|
||||
result
|
||||
));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.badRequest().body(ApiResponse.error("엑셀 파싱 실패: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "직원 일괄 등록 템플릿 다운로드")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@GetMapping("/batch/template")
|
||||
public ResponseEntity<byte[]> downloadTemplate() throws Exception {
|
||||
String[] headers = {"로그인ID", "이름", "이메일", "전화번호", "권한", "재직상태", "파견상태", "생년월일", "학력", "학과", "입사일"};
|
||||
Map<Integer, String[]> dropdowns = Map.of(
|
||||
4, new String[]{"ADMIN", "MANAGER", "EMPLOYEE"},
|
||||
5, new String[]{"ACTIVE", "ON_LEAVE", "RESIGNED"},
|
||||
6, new String[]{"WAITING", "DISPATCHED"}
|
||||
);
|
||||
byte[] data = ExcelParser.generateTemplate(headers, "직원 일괄등록", dropdowns);
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=employee_batch_template.xlsx")
|
||||
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
|
||||
.body(data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.srsystem.controller;
|
||||
|
||||
import com.srsystem.dto.ApiResponse;
|
||||
import com.srsystem.dto.BatchResult;
|
||||
import com.srsystem.dto.CreateEquipmentRequest;
|
||||
import com.srsystem.dto.CreateMaintenanceRequest;
|
||||
import com.srsystem.dto.EquipmentSummary;
|
||||
@@ -11,6 +12,7 @@ import com.srsystem.entity.EquipmentMaintenance;
|
||||
import com.srsystem.entity.enums.EquipmentStatus;
|
||||
import com.srsystem.entity.enums.EquipmentType;
|
||||
import com.srsystem.service.EquipmentService;
|
||||
import com.srsystem.util.ExcelParser;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
@@ -19,11 +21,15 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -158,4 +164,75 @@ public class EquipmentController {
|
||||
Equipment equipment = equipmentService.removeImage(equipmentId, imageIndex);
|
||||
return ResponseEntity.ok(ApiResponse.ok("이미지가 삭제되었습니다", equipment));
|
||||
}
|
||||
|
||||
// ---- Batch ----
|
||||
|
||||
@Operation(summary = "장비 일괄 등록", description = "엑셀 파일로 장비를 일괄 등록합니다")
|
||||
@PreAuthorize("hasAnyRole('MANAGER', 'ADMIN')")
|
||||
@Transactional
|
||||
@PostMapping("/batch")
|
||||
public ResponseEntity<ApiResponse<BatchResult<Equipment>>> batchCreate(@RequestParam("file") MultipartFile file) {
|
||||
try {
|
||||
ExcelParser.ParseResult<CreateEquipmentRequest> parsed = ExcelParser.parse(
|
||||
file,
|
||||
(row) -> new CreateEquipmentRequest(
|
||||
EquipmentType.valueOf(row.getOrDefault("장비유형", "LAPTOP").toUpperCase()),
|
||||
row.getOrDefault("제조사", ""),
|
||||
row.getOrDefault("모델명", ""),
|
||||
row.getOrDefault("시리얼번호", ""),
|
||||
row.getOrDefault("자산코드", ""),
|
||||
row.getOrDefault("제원정보", ""),
|
||||
EquipmentStatus.AVAILABLE,
|
||||
row.containsKey("구매일") ? java.time.LocalDate.parse(row.get("구매일")) : java.time.LocalDate.now(),
|
||||
null
|
||||
),
|
||||
List.of()
|
||||
);
|
||||
|
||||
List<BatchResult.Failure> failures = new ArrayList<>();
|
||||
List<Equipment> success = new ArrayList<>();
|
||||
var parseFailures = parsed.failures();
|
||||
for (var pf : parseFailures) {
|
||||
failures.add(new BatchResult.Failure(pf.row(), pf.reason()));
|
||||
}
|
||||
|
||||
for (int i = 0; i < parsed.data().size(); i++) {
|
||||
try {
|
||||
Equipment eq = equipmentService.createEquipment(parsed.data().get(i));
|
||||
success.add(eq);
|
||||
} catch (Exception e) {
|
||||
failures.add(new BatchResult.Failure(i + 2, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
BatchResult<Equipment> result = new BatchResult<>(
|
||||
parsed.data().size() + parseFailures.size(),
|
||||
success.size(),
|
||||
failures.size(),
|
||||
failures,
|
||||
success
|
||||
);
|
||||
return ResponseEntity.ok(ApiResponse.ok(
|
||||
String.format("%d건 중 %d건 성공, %d건 실패", result.totalCount(), result.successCount(), result.failCount()),
|
||||
result
|
||||
));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.badRequest().body(ApiResponse.error("엑셀 파싱 실패: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "장비 일괄 등록 템플릿 다운로드")
|
||||
@PreAuthorize("hasAnyRole('MANAGER', 'ADMIN')")
|
||||
@GetMapping("/batch/template")
|
||||
public ResponseEntity<byte[]> downloadTemplate() throws Exception {
|
||||
String[] headers = {"장비유형", "제조사", "모델명", "시리얼번호", "자산코드", "제원정보", "구매일"};
|
||||
Map<Integer, String[]> dropdowns = Map.of(
|
||||
0, new String[]{"LAPTOP", "MONITOR", "TEST_DEVICE", "ACCESSORY"}
|
||||
);
|
||||
byte[] data = ExcelParser.generateTemplate(headers, "장비 일괄등록", dropdowns);
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=equipment_batch_template.xlsx")
|
||||
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
|
||||
.body(data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.srsystem.dto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public record BatchResult<T>(
|
||||
int totalCount,
|
||||
int successCount,
|
||||
int failCount,
|
||||
List<Failure> failures,
|
||||
List<T> data
|
||||
) {
|
||||
public static <T> BatchResult<T> ok(List<T> data) {
|
||||
return new BatchResult<>(data.size(), data.size(), 0, List.of(), data);
|
||||
}
|
||||
|
||||
public static <T> BatchResult<T> partial(List<T> successData, List<Failure> failures) {
|
||||
return new BatchResult<>(
|
||||
successData.size() + failures.size(),
|
||||
successData.size(),
|
||||
failures.size(),
|
||||
failures,
|
||||
successData
|
||||
);
|
||||
}
|
||||
|
||||
public record Failure(int row, String reason) {}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package com.srsystem.util;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.util.CellRangeAddressList;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ExcelParser {
|
||||
|
||||
public static <T> ParseResult<T> parse(MultipartFile file, RowMapper<T> mapper, List<Validator<T>> validators) throws IOException {
|
||||
List<T> data = new ArrayList<>();
|
||||
List<ParseFailure> failures = new ArrayList<>();
|
||||
|
||||
try (InputStream is = file.getInputStream(); Workbook wb = new XSSFWorkbook(is)) {
|
||||
Sheet sheet = wb.getSheetAt(0);
|
||||
if (sheet.getPhysicalNumberOfRows() < 2) {
|
||||
return new ParseResult<>(List.of(), List.of(new ParseFailure(0, "데이터 행이 없습니다")));
|
||||
}
|
||||
|
||||
Row headerRow = sheet.getRow(0);
|
||||
int colCount = headerRow.getPhysicalNumberOfCells();
|
||||
String[] headers = new String[colCount];
|
||||
for (int i = 0; i < colCount; i++) {
|
||||
headers[i] = getCellValue(headerRow.getCell(i)).trim().toLowerCase();
|
||||
}
|
||||
|
||||
for (int r = 1; r <= sheet.getLastRowNum(); r++) {
|
||||
Row row = sheet.getRow(r);
|
||||
if (row == null) continue;
|
||||
|
||||
try {
|
||||
Map<String, String> rowData = new HashMap<>();
|
||||
for (int c = 0; c < colCount; c++) {
|
||||
String val = getCellValue(row.getCell(c));
|
||||
if (!val.isEmpty()) {
|
||||
rowData.put(headers[c], val);
|
||||
}
|
||||
}
|
||||
|
||||
if (rowData.isEmpty()) continue;
|
||||
|
||||
T item = mapper.map(rowData);
|
||||
for (Validator<T> v : validators) {
|
||||
String err = v.validate(item, rowData);
|
||||
if (err != null) {
|
||||
throw new ValidationException(err);
|
||||
}
|
||||
}
|
||||
data.add(item);
|
||||
} catch (Exception e) {
|
||||
failures.add(new ParseFailure(r + 1, e.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new ParseResult<>(data, failures);
|
||||
}
|
||||
|
||||
public static byte[] generateTemplate(String[] headers, String sheetName, Map<Integer, String[]> dropdowns) throws IOException {
|
||||
try (Workbook wb = new XSSFWorkbook(); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
|
||||
Sheet sheet = wb.createSheet(sheetName);
|
||||
Row headerRow = sheet.createRow(0);
|
||||
|
||||
CellStyle headerStyle = wb.createCellStyle();
|
||||
Font headerFont = wb.createFont();
|
||||
headerFont.setBold(true);
|
||||
headerFont.setColor(IndexedColors.WHITE.getIndex());
|
||||
headerStyle.setFont(headerFont);
|
||||
headerStyle.setFillForegroundColor(IndexedColors.INDIGO.getIndex());
|
||||
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
headerStyle.setBorderBottom(BorderStyle.THIN);
|
||||
headerStyle.setBorderLeft(BorderStyle.THIN);
|
||||
headerStyle.setBorderRight(BorderStyle.THIN);
|
||||
headerStyle.setBorderTop(BorderStyle.THIN);
|
||||
|
||||
for (int i = 0; i < headers.length; i++) {
|
||||
Cell cell = headerRow.createCell(i);
|
||||
cell.setCellValue(headers[i]);
|
||||
cell.setCellStyle(headerStyle);
|
||||
sheet.autoSizeColumn(i);
|
||||
}
|
||||
|
||||
if (dropdowns != null) {
|
||||
for (Map.Entry<Integer, String[]> entry : dropdowns.entrySet()) {
|
||||
int col = entry.getKey();
|
||||
String[] values = entry.getValue();
|
||||
DataValidationHelper helper = sheet.getDataValidationHelper();
|
||||
DataValidationConstraint constraint = helper.createExplicitListConstraint(values);
|
||||
CellRangeAddressList range = new CellRangeAddressList(1, 1000, col, col);
|
||||
DataValidation validation = helper.createValidation(constraint, range);
|
||||
validation.setShowErrorBox(true);
|
||||
validation.createErrorBox("유효성 검사", "허용된 값만 입력 가능합니다.");
|
||||
sheet.addValidationData(validation);
|
||||
}
|
||||
}
|
||||
|
||||
wb.write(bos);
|
||||
return bos.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static String getCellValue(Cell cell) {
|
||||
if (cell == null) return "";
|
||||
return switch (cell.getCellType()) {
|
||||
case STRING -> cell.getStringCellValue().trim();
|
||||
case NUMERIC -> {
|
||||
double val = cell.getNumericCellValue();
|
||||
if (val == Math.floor(val) && !Double.isInfinite(val)) {
|
||||
yield String.valueOf((long) val);
|
||||
}
|
||||
yield String.valueOf(val);
|
||||
}
|
||||
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
|
||||
case FORMULA -> {
|
||||
try { yield String.valueOf((int) cell.getNumericCellValue()); }
|
||||
catch (Exception e) { yield cell.getStringCellValue(); }
|
||||
}
|
||||
default -> "";
|
||||
};
|
||||
}
|
||||
|
||||
public record ParseResult<T>(List<T> data, List<ParseFailure> failures) {
|
||||
public boolean hasFailures() { return !failures.isEmpty(); }
|
||||
}
|
||||
|
||||
public record ParseFailure(int row, String reason) {}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface RowMapper<T> {
|
||||
T map(Map<String, String> rowData) throws Exception;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Validator<T> {
|
||||
String validate(T item, Map<String, String> rawData);
|
||||
}
|
||||
|
||||
private static class ValidationException extends RuntimeException {
|
||||
public ValidationException(String message) { super(message); }
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user