fix: TypeScript 타입 오류 수정 및 설정 페이지 추가
- BOMItem Omit 타입 시그니처 통일 (useTemplateManagement, SectionsTab, ItemMasterContext) - HeadersInit → Record<string, string> 타입 변경 - Zustand useShallow 마이그레이션 (zustand/react/shallow) - DataTable, ListPageTemplate 제네릭 타입 제약 추가 - 설정 관리 페이지 추가 (직급, 직책, 휴가정책, 근무일정, 권한) - HR 관리 페이지 추가 (급여, 휴가) - 단가관리 페이지 리팩토링 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,7 +10,6 @@
|
||||
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "../ui/button";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
|
||||
@@ -26,6 +25,8 @@ import {
|
||||
Mail,
|
||||
} from "lucide-react";
|
||||
import { Client } from "../../hooks/useClientList";
|
||||
import { PageLayout } from "../organisms/PageLayout";
|
||||
import { PageHeader } from "../organisms/PageHeader";
|
||||
|
||||
interface ClientDetailProps {
|
||||
client: Client;
|
||||
@@ -63,8 +64,6 @@ export function ClientDetail({
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: ClientDetailProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// 금액 포맷
|
||||
const formatCurrency = (amount: string) => {
|
||||
if (!amount) return "-";
|
||||
@@ -73,30 +72,32 @@ export function ClientDetail({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* 헤더 */}
|
||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Building2 className="h-6 w-6 text-primary" />
|
||||
<h1 className="text-2xl font-bold">{client.name}</h1>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록
|
||||
</Button>
|
||||
<Button variant="outline" onClick={onEdit}>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
수정
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={onDelete}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
삭제
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<PageLayout maxWidth="2xl">
|
||||
{/* 헤더 - PageHeader 사용으로 등록/수정과 동일한 레이아웃 */}
|
||||
<PageHeader
|
||||
title={client.name}
|
||||
description="거래처 상세 정보"
|
||||
icon={Building2}
|
||||
actions={
|
||||
<>
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록
|
||||
</Button>
|
||||
<Button variant="outline" onClick={onEdit}>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
수정
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={onDelete}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
삭제
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 1. 기본 정보 */}
|
||||
<div className="space-y-6">
|
||||
{/* 1. 기본 정보 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -242,6 +243,7 @@ export function ClientDetail({
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -12,24 +12,13 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Input } from "../ui/input";
|
||||
import { Textarea } from "../ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "../ui/select";
|
||||
import { RadioGroup, RadioGroupItem } from "../ui/radio-group";
|
||||
import { Checkbox } from "../ui/checkbox";
|
||||
import { Label } from "../ui/label";
|
||||
import {
|
||||
Building2,
|
||||
UserCircle,
|
||||
Phone,
|
||||
CreditCard,
|
||||
FileText,
|
||||
AlertTriangle,
|
||||
Calculator,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
@@ -42,7 +31,6 @@ import {
|
||||
ClientFormData,
|
||||
INITIAL_CLIENT_FORM,
|
||||
ClientType,
|
||||
BadDebtProgress,
|
||||
} from "../../hooks/useClientList";
|
||||
|
||||
interface ClientRegistrationProps {
|
||||
@@ -52,15 +40,33 @@ interface ClientRegistrationProps {
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
// 4자리 영문+숫자 조합 코드 생성 (중복 방지를 위해 타임스탬프 기반)
|
||||
const generateClientCode = (): string => {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
const timestamp = Date.now().toString(36).toUpperCase().slice(-2); // 타임스탬프 2자리
|
||||
let random = "";
|
||||
for (let i = 0; i < 2; i++) {
|
||||
random += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return timestamp + random;
|
||||
};
|
||||
|
||||
export function ClientRegistration({
|
||||
onBack,
|
||||
onSave,
|
||||
editingClient,
|
||||
isLoading = false,
|
||||
}: ClientRegistrationProps) {
|
||||
const [formData, setFormData] = useState<ClientFormData>(
|
||||
editingClient || INITIAL_CLIENT_FORM
|
||||
);
|
||||
const [formData, setFormData] = useState<ClientFormData>(() => {
|
||||
if (editingClient) {
|
||||
return editingClient;
|
||||
}
|
||||
// 신규 등록 시 클라이언트 코드 자동 생성
|
||||
return {
|
||||
...INITIAL_CLIENT_FORM,
|
||||
clientCode: generateClientCode(),
|
||||
};
|
||||
});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
@@ -79,7 +85,15 @@ export function ClientRegistration({
|
||||
newErrors.name = "거래처명은 2자 이상 입력해주세요";
|
||||
}
|
||||
|
||||
if (!formData.businessNo || !/^\d{10}$/.test(formData.businessNo)) {
|
||||
// 하이픈 제거 후 10자리 숫자 검증 (123-45-67890 또는 1234567890 허용)
|
||||
const businessNoDigits = formData.businessNo.replace(/-/g, "").trim();
|
||||
console.log("[ClientRegistration] businessNo 검증:", {
|
||||
원본: formData.businessNo,
|
||||
하이픈제거: businessNoDigits,
|
||||
길이: businessNoDigits.length,
|
||||
숫자만: /^\d{10}$/.test(businessNoDigits),
|
||||
});
|
||||
if (!formData.businessNo || !/^\d{10}$/.test(businessNoDigits)) {
|
||||
newErrors.businessNo = "사업자등록번호는 10자리 숫자여야 합니다";
|
||||
}
|
||||
|
||||
@@ -125,6 +139,7 @@ export function ClientRegistration({
|
||||
field: keyof ClientFormData,
|
||||
value: string | boolean
|
||||
) => {
|
||||
console.log("[ClientRegistration] handleFieldChange:", field, value);
|
||||
setFormData({ ...formData, [field]: value });
|
||||
if (errors[field]) {
|
||||
setErrors((prev) => {
|
||||
@@ -160,10 +175,11 @@ export function ClientRegistration({
|
||||
required
|
||||
error={errors.businessNo}
|
||||
htmlFor="businessNo"
|
||||
type="custom"
|
||||
>
|
||||
<Input
|
||||
id="businessNo"
|
||||
placeholder="10자리 숫자"
|
||||
placeholder="10자리 숫자 (예: 123-45-67890)"
|
||||
value={formData.businessNo}
|
||||
onChange={(e) => handleFieldChange("businessNo", e.target.value)}
|
||||
/>
|
||||
@@ -173,6 +189,7 @@ export function ClientRegistration({
|
||||
label="거래처 코드"
|
||||
htmlFor="clientCode"
|
||||
helpText="자동 생성됩니다"
|
||||
type="custom"
|
||||
>
|
||||
<Input
|
||||
id="clientCode"
|
||||
@@ -189,6 +206,7 @@ export function ClientRegistration({
|
||||
required
|
||||
error={errors.name}
|
||||
htmlFor="name"
|
||||
type="custom"
|
||||
>
|
||||
<Input
|
||||
id="name"
|
||||
@@ -203,6 +221,7 @@ export function ClientRegistration({
|
||||
required
|
||||
error={errors.representative}
|
||||
htmlFor="representative"
|
||||
type="custom"
|
||||
>
|
||||
<Input
|
||||
id="representative"
|
||||
@@ -239,7 +258,7 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="업태" htmlFor="businessType">
|
||||
<FormField label="업태" htmlFor="businessType" type="custom">
|
||||
<Input
|
||||
id="businessType"
|
||||
placeholder="제조업, 도소매업 등"
|
||||
@@ -250,7 +269,7 @@ export function ClientRegistration({
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="종목" htmlFor="businessItem">
|
||||
<FormField label="종목" htmlFor="businessItem" type="custom">
|
||||
<Input
|
||||
id="businessItem"
|
||||
placeholder="철강, 건설 등"
|
||||
@@ -269,7 +288,7 @@ export function ClientRegistration({
|
||||
description="거래처의 연락처 정보를 입력하세요"
|
||||
icon={Phone}
|
||||
>
|
||||
<FormField label="주소" htmlFor="address">
|
||||
<FormField label="주소" htmlFor="address" type="custom">
|
||||
<Input
|
||||
id="address"
|
||||
placeholder="주소 입력"
|
||||
@@ -279,7 +298,7 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
|
||||
<FormFieldGrid columns={3}>
|
||||
<FormField label="전화번호" error={errors.phone} htmlFor="phone">
|
||||
<FormField label="전화번호" error={errors.phone} htmlFor="phone" type="custom">
|
||||
<Input
|
||||
id="phone"
|
||||
placeholder="02-1234-5678"
|
||||
@@ -288,7 +307,7 @@ export function ClientRegistration({
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="모바일" htmlFor="mobile">
|
||||
<FormField label="모바일" htmlFor="mobile" type="custom">
|
||||
<Input
|
||||
id="mobile"
|
||||
placeholder="010-1234-5678"
|
||||
@@ -297,7 +316,7 @@ export function ClientRegistration({
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="팩스" htmlFor="fax">
|
||||
<FormField label="팩스" htmlFor="fax" type="custom">
|
||||
<Input
|
||||
id="fax"
|
||||
placeholder="02-1234-5678"
|
||||
@@ -307,7 +326,7 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
|
||||
<FormField label="이메일" error={errors.email} htmlFor="email">
|
||||
<FormField label="이메일" error={errors.email} htmlFor="email" type="custom">
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
@@ -325,7 +344,7 @@ export function ClientRegistration({
|
||||
icon={UserCircle}
|
||||
>
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="담당자명" htmlFor="managerName">
|
||||
<FormField label="담당자명" htmlFor="managerName" type="custom">
|
||||
<Input
|
||||
id="managerName"
|
||||
placeholder="담당자명 입력"
|
||||
@@ -334,7 +353,7 @@ export function ClientRegistration({
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="담당자 전화" htmlFor="managerTel">
|
||||
<FormField label="담당자 전화" htmlFor="managerTel" type="custom">
|
||||
<Input
|
||||
id="managerTel"
|
||||
placeholder="010-1234-5678"
|
||||
@@ -344,7 +363,7 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
|
||||
<FormField label="시스템 관리자" htmlFor="systemManager">
|
||||
<FormField label="시스템 관리자" htmlFor="systemManager" type="custom">
|
||||
<Input
|
||||
id="systemManager"
|
||||
placeholder="시스템 관리자명"
|
||||
@@ -356,224 +375,22 @@ export function ClientRegistration({
|
||||
</FormField>
|
||||
</FormSection>
|
||||
|
||||
{/* 4. 발주처 설정 */}
|
||||
<FormSection
|
||||
title="발주처 설정"
|
||||
description="발주처로 사용할 경우 계정 정보를 입력하세요"
|
||||
icon={CreditCard}
|
||||
>
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="계정 ID" htmlFor="accountId">
|
||||
<Input
|
||||
id="accountId"
|
||||
placeholder="계정 ID"
|
||||
value={formData.accountId}
|
||||
onChange={(e) => handleFieldChange("accountId", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
{/*
|
||||
TODO: 기획 확정 후 활성화 (2025-12-09)
|
||||
- 발주처 설정: 계정ID, 비밀번호, 매입/매출 결제일
|
||||
- 약정 세금: 약정 여부, 금액, 시작/종료일
|
||||
- 악성채권 정보: 악성채권 여부, 금액, 발생/만료일, 진행상태
|
||||
|
||||
<FormField label="비밀번호" htmlFor="accountPassword">
|
||||
<Input
|
||||
id="accountPassword"
|
||||
type="password"
|
||||
placeholder="비밀번호"
|
||||
value={formData.accountPassword}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("accountPassword", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
백엔드 API에서는 이미 지원됨 (nullable 필드)
|
||||
*/}
|
||||
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="매입 결제일" htmlFor="purchasePaymentDay">
|
||||
<Select
|
||||
value={formData.purchasePaymentDay}
|
||||
onValueChange={(value) =>
|
||||
handleFieldChange("purchasePaymentDay", value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="purchasePaymentDay">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="말일">말일</SelectItem>
|
||||
<SelectItem value="익월 10일">익월 10일</SelectItem>
|
||||
<SelectItem value="익월 15일">익월 15일</SelectItem>
|
||||
<SelectItem value="익월 20일">익월 20일</SelectItem>
|
||||
<SelectItem value="익월 25일">익월 25일</SelectItem>
|
||||
<SelectItem value="익월 말일">익월 말일</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
|
||||
<FormField label="매출 결제일" htmlFor="salesPaymentDay">
|
||||
<Select
|
||||
value={formData.salesPaymentDay}
|
||||
onValueChange={(value) =>
|
||||
handleFieldChange("salesPaymentDay", value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="salesPaymentDay">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="말일">말일</SelectItem>
|
||||
<SelectItem value="익월 10일">익월 10일</SelectItem>
|
||||
<SelectItem value="익월 15일">익월 15일</SelectItem>
|
||||
<SelectItem value="익월 20일">익월 20일</SelectItem>
|
||||
<SelectItem value="익월 25일">익월 25일</SelectItem>
|
||||
<SelectItem value="익월 말일">익월 말일</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
</FormSection>
|
||||
|
||||
{/* 5. 약정 세금 */}
|
||||
<FormSection
|
||||
title="약정 세금"
|
||||
description="세금 약정이 있는 경우 입력하세요"
|
||||
icon={Calculator}
|
||||
>
|
||||
<FormField label="약정 여부" type="custom">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="taxAgreement"
|
||||
checked={formData.taxAgreement}
|
||||
onCheckedChange={(checked) =>
|
||||
handleFieldChange("taxAgreement", checked as boolean)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="taxAgreement">세금 약정 있음</Label>
|
||||
</div>
|
||||
</FormField>
|
||||
|
||||
{formData.taxAgreement && (
|
||||
<>
|
||||
<FormField label="약정 금액" htmlFor="taxAmount">
|
||||
<Input
|
||||
id="taxAmount"
|
||||
type="number"
|
||||
placeholder="약정 금액"
|
||||
value={formData.taxAmount}
|
||||
onChange={(e) => handleFieldChange("taxAmount", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="약정 시작일" htmlFor="taxStartDate">
|
||||
<Input
|
||||
id="taxStartDate"
|
||||
type="date"
|
||||
value={formData.taxStartDate}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("taxStartDate", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="약정 종료일" htmlFor="taxEndDate">
|
||||
<Input
|
||||
id="taxEndDate"
|
||||
type="date"
|
||||
value={formData.taxEndDate}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("taxEndDate", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
</>
|
||||
)}
|
||||
</FormSection>
|
||||
|
||||
{/* 6. 악성채권 */}
|
||||
<FormSection
|
||||
title="악성채권 정보"
|
||||
description="악성채권이 있는 경우 입력하세요"
|
||||
icon={AlertTriangle}
|
||||
>
|
||||
<FormField label="악성채권 여부" type="custom">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="badDebt"
|
||||
checked={formData.badDebt}
|
||||
onCheckedChange={(checked) =>
|
||||
handleFieldChange("badDebt", checked as boolean)
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="badDebt">악성채권 있음</Label>
|
||||
</div>
|
||||
</FormField>
|
||||
|
||||
{formData.badDebt && (
|
||||
<>
|
||||
<FormField label="악성채권 금액" htmlFor="badDebtAmount">
|
||||
<Input
|
||||
id="badDebtAmount"
|
||||
type="number"
|
||||
placeholder="채권 금액"
|
||||
value={formData.badDebtAmount}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("badDebtAmount", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormFieldGrid columns={2}>
|
||||
<FormField label="채권 발생일" htmlFor="badDebtReceiveDate">
|
||||
<Input
|
||||
id="badDebtReceiveDate"
|
||||
type="date"
|
||||
value={formData.badDebtReceiveDate}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("badDebtReceiveDate", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="채권 만료일" htmlFor="badDebtEndDate">
|
||||
<Input
|
||||
id="badDebtEndDate"
|
||||
type="date"
|
||||
value={formData.badDebtEndDate}
|
||||
onChange={(e) =>
|
||||
handleFieldChange("badDebtEndDate", e.target.value)
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
</FormFieldGrid>
|
||||
|
||||
<FormField label="진행 상태" htmlFor="badDebtProgress">
|
||||
<Select
|
||||
value={formData.badDebtProgress}
|
||||
onValueChange={(value) =>
|
||||
handleFieldChange("badDebtProgress", value as BadDebtProgress)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="badDebtProgress">
|
||||
<SelectValue placeholder="진행 상태 선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="협의중">협의중</SelectItem>
|
||||
<SelectItem value="소송중">소송중</SelectItem>
|
||||
<SelectItem value="회수완료">회수완료</SelectItem>
|
||||
<SelectItem value="대손처리">대손처리</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
</>
|
||||
)}
|
||||
</FormSection>
|
||||
|
||||
{/* 7. 기타 */}
|
||||
{/* 4. 기타 */}
|
||||
<FormSection
|
||||
title="기타 정보"
|
||||
description="추가 정보를 입력하세요"
|
||||
icon={FileText}
|
||||
>
|
||||
<FormField label="메모" htmlFor="memo">
|
||||
<FormField label="메모" htmlFor="memo" type="custom">
|
||||
<Textarea
|
||||
id="memo"
|
||||
placeholder="메모 입력"
|
||||
|
||||
@@ -378,10 +378,10 @@ export function DataTable<T extends BaseDataItem>({
|
||||
: col.render
|
||||
? col.render(value, row, index)
|
||||
: value;
|
||||
if (rendered === null) return null;
|
||||
if (rendered === null || rendered === undefined) return null;
|
||||
return (
|
||||
<div key={col.key}>
|
||||
{rendered}
|
||||
{rendered as React.ReactNode}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
* 모든 목록 페이지에서 재사용 가능한 테이블 컴포넌트
|
||||
*/
|
||||
|
||||
import { DataTable } from './DataTable';
|
||||
|
||||
export { DataTable } from './DataTable';
|
||||
export { SearchFilter } from './SearchFilter';
|
||||
export { Pagination } from './Pagination';
|
||||
|
||||
287
src/components/hr/SalaryManagement/SalaryDetailDialog.tsx
Normal file
287
src/components/hr/SalaryManagement/SalaryDetailDialog.tsx
Normal file
@@ -0,0 +1,287 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Plus, Save } from 'lucide-react';
|
||||
import type { SalaryDetail, PaymentStatus } from './types';
|
||||
import {
|
||||
PAYMENT_STATUS_LABELS,
|
||||
PAYMENT_STATUS_COLORS,
|
||||
formatCurrency,
|
||||
} from './types';
|
||||
|
||||
interface SalaryDetailDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
salaryDetail: SalaryDetail | null;
|
||||
onSave?: (updatedDetail: SalaryDetail) => void;
|
||||
onAddPaymentItem?: () => void;
|
||||
}
|
||||
|
||||
export function SalaryDetailDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
salaryDetail,
|
||||
onSave,
|
||||
onAddPaymentItem,
|
||||
}: SalaryDetailDialogProps) {
|
||||
const [editedStatus, setEditedStatus] = useState<PaymentStatus>('scheduled');
|
||||
const [hasChanges, setHasChanges] = useState(false);
|
||||
|
||||
// 다이얼로그가 열릴 때 상태 초기화
|
||||
useEffect(() => {
|
||||
if (salaryDetail) {
|
||||
setEditedStatus(salaryDetail.status);
|
||||
setHasChanges(false);
|
||||
}
|
||||
}, [salaryDetail]);
|
||||
|
||||
if (!salaryDetail) return null;
|
||||
|
||||
const handleStatusChange = (newStatus: PaymentStatus) => {
|
||||
setEditedStatus(newStatus);
|
||||
setHasChanges(newStatus !== salaryDetail.status);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (onSave && salaryDetail) {
|
||||
onSave({
|
||||
...salaryDetail,
|
||||
status: editedStatus,
|
||||
});
|
||||
}
|
||||
setHasChanges(false);
|
||||
};
|
||||
|
||||
const handleAddPaymentItem = () => {
|
||||
if (onAddPaymentItem) {
|
||||
onAddPaymentItem();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
급여 수정 - {salaryDetail.employeeName}
|
||||
</div>
|
||||
{/* 상태 변경 셀렉트 박스 */}
|
||||
<Select
|
||||
value={editedStatus}
|
||||
onValueChange={(value) => handleStatusChange(value as PaymentStatus)}
|
||||
>
|
||||
<SelectTrigger className="w-[140px]">
|
||||
<SelectValue>
|
||||
<Badge className={PAYMENT_STATUS_COLORS[editedStatus]}>
|
||||
{PAYMENT_STATUS_LABELS[editedStatus]}
|
||||
</Badge>
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="scheduled">
|
||||
<Badge className={PAYMENT_STATUS_COLORS.scheduled}>
|
||||
{PAYMENT_STATUS_LABELS.scheduled}
|
||||
</Badge>
|
||||
</SelectItem>
|
||||
<SelectItem value="completed">
|
||||
<Badge className={PAYMENT_STATUS_COLORS.completed}>
|
||||
{PAYMENT_STATUS_LABELS.completed}
|
||||
</Badge>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* 기본 정보 */}
|
||||
<div className="bg-muted/50 rounded-lg p-4">
|
||||
<h3 className="font-semibold mb-3">기본 정보</h3>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">사번</span>
|
||||
<p className="font-medium">{salaryDetail.employeeId}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">이름</span>
|
||||
<p className="font-medium">{salaryDetail.employeeName}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">부서</span>
|
||||
<p className="font-medium">{salaryDetail.department}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">직급</span>
|
||||
<p className="font-medium">{salaryDetail.rank}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">직책</span>
|
||||
<p className="font-medium">{salaryDetail.position}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">지급월</span>
|
||||
<p className="font-medium">{salaryDetail.year}년 {salaryDetail.month}월</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">지급일</span>
|
||||
<p className="font-medium">{salaryDetail.paymentDate}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 급여 항목 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* 수당 내역 */}
|
||||
<div className="border rounded-lg p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="font-semibold text-blue-600">수당 내역</h3>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleAddPaymentItem}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
<Plus className="h-3 w-3 mr-1" />
|
||||
지급항목 추가
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">본봉</span>
|
||||
<span className="font-medium">{formatCurrency(salaryDetail.baseSalary)}원</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">직책수당</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.positionAllowance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">초과근무수당</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.overtimeAllowance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">식대</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.mealAllowance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">교통비</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.transportAllowance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">기타수당</span>
|
||||
<span>{formatCurrency(salaryDetail.allowances.otherAllowance)}원</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between font-semibold text-blue-600">
|
||||
<span>수당 합계</span>
|
||||
<span>{formatCurrency(salaryDetail.totalAllowance)}원</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 공제 내역 */}
|
||||
<div className="border rounded-lg p-4">
|
||||
<h3 className="font-semibold mb-3 text-red-600">공제 내역</h3>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">국민연금</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.nationalPension)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">건강보험</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.healthInsurance)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">장기요양보험</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.longTermCare)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">고용보험</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.employmentInsurance)}원</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">소득세</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.incomeTax)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">지방소득세</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.localIncomeTax)}원</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">기타공제</span>
|
||||
<span className="text-red-600">-{formatCurrency(salaryDetail.deductions.otherDeduction)}원</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between font-semibold text-red-600">
|
||||
<span>공제 합계</span>
|
||||
<span>-{formatCurrency(salaryDetail.totalDeduction)}원</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 지급 합계 */}
|
||||
<div className="bg-primary/5 border-2 border-primary/20 rounded-lg p-4">
|
||||
<div className="grid grid-cols-3 gap-4 text-center">
|
||||
<div>
|
||||
<span className="text-sm text-muted-foreground block">급여 총액</span>
|
||||
<span className="text-lg font-semibold text-blue-600">
|
||||
{formatCurrency(salaryDetail.baseSalary + salaryDetail.totalAllowance)}원
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-sm text-muted-foreground block">공제 총액</span>
|
||||
<span className="text-lg font-semibold text-red-600">
|
||||
-{formatCurrency(salaryDetail.totalDeduction)}원
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-sm text-muted-foreground block">실지급액</span>
|
||||
<span className="text-xl font-bold text-primary">
|
||||
{formatCurrency(salaryDetail.netPayment)}원
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 저장 버튼 */}
|
||||
<DialogFooter className="mt-6">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges}
|
||||
className="gap-2"
|
||||
>
|
||||
<Save className="h-4 w-4" />
|
||||
저장
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
509
src/components/hr/SalaryManagement/index.tsx
Normal file
509
src/components/hr/SalaryManagement/index.tsx
Normal file
@@ -0,0 +1,509 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
Download,
|
||||
DollarSign,
|
||||
Check,
|
||||
Clock,
|
||||
Pencil,
|
||||
Banknote,
|
||||
Briefcase,
|
||||
Timer,
|
||||
Gift,
|
||||
MinusCircle,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
type StatCard,
|
||||
type TabOption,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { SalaryDetailDialog } from './SalaryDetailDialog';
|
||||
import type {
|
||||
SalaryRecord,
|
||||
SalaryDetail,
|
||||
PaymentStatus,
|
||||
SortOption,
|
||||
} from './types';
|
||||
import {
|
||||
PAYMENT_STATUS_LABELS,
|
||||
PAYMENT_STATUS_COLORS,
|
||||
SORT_OPTIONS,
|
||||
formatCurrency,
|
||||
} from './types';
|
||||
|
||||
// ===== Mock 데이터 생성 =====
|
||||
const generateSalaryData = (): SalaryRecord[] => {
|
||||
const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
|
||||
const positions = ['팀장', '파트장', '선임', '주임', '사원'];
|
||||
const ranks = ['부장', '차장', '과장', '대리', '사원'];
|
||||
const statuses: PaymentStatus[] = ['scheduled', 'completed'];
|
||||
const names = ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현', '한승우', '송예진'];
|
||||
|
||||
return Array.from({ length: 10 }, (_, i) => {
|
||||
const baseSalary = 3000000 + Math.floor(Math.random() * 2000000);
|
||||
const allowance = 300000 + Math.floor(Math.random() * 500000);
|
||||
const overtime = Math.floor(Math.random() * 500000);
|
||||
const bonus = Math.floor(Math.random() * 1000000);
|
||||
const deduction = 200000 + Math.floor(Math.random() * 300000);
|
||||
const netPayment = baseSalary + allowance + overtime + bonus - deduction;
|
||||
|
||||
return {
|
||||
id: `salary-${i + 1}`,
|
||||
employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
|
||||
employeeName: names[i],
|
||||
department: departments[i % departments.length],
|
||||
position: positions[i % positions.length],
|
||||
rank: ranks[i % ranks.length],
|
||||
baseSalary,
|
||||
allowance,
|
||||
overtime,
|
||||
bonus,
|
||||
deduction,
|
||||
netPayment,
|
||||
paymentDate: format(new Date(2025, 11, 25), 'yyyy-MM-dd'),
|
||||
status: statuses[i % statuses.length],
|
||||
year: 2025,
|
||||
month: 12,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
// Mock 상세 데이터 생성
|
||||
const generateSalaryDetail = (record: SalaryRecord): SalaryDetail => {
|
||||
const positionAllowance = 100000 + Math.floor(Math.random() * 200000);
|
||||
const overtimeAllowance = Math.floor(Math.random() * 300000);
|
||||
const mealAllowance = 100000;
|
||||
const transportAllowance = 100000;
|
||||
const otherAllowance = Math.floor(Math.random() * 100000);
|
||||
|
||||
const totalAllowance = positionAllowance + overtimeAllowance + mealAllowance + transportAllowance + otherAllowance;
|
||||
|
||||
const nationalPension = Math.floor(record.baseSalary * 0.045);
|
||||
const healthInsurance = Math.floor(record.baseSalary * 0.0343);
|
||||
const longTermCare = Math.floor(healthInsurance * 0.1227);
|
||||
const employmentInsurance = Math.floor(record.baseSalary * 0.009);
|
||||
const incomeTax = Math.floor((record.baseSalary + totalAllowance) * 0.08);
|
||||
const localIncomeTax = Math.floor(incomeTax * 0.1);
|
||||
const otherDeduction = Math.floor(Math.random() * 50000);
|
||||
|
||||
const totalDeduction = nationalPension + healthInsurance + longTermCare + employmentInsurance + incomeTax + localIncomeTax + otherDeduction;
|
||||
|
||||
return {
|
||||
employeeId: record.employeeId,
|
||||
employeeName: record.employeeName,
|
||||
department: record.department,
|
||||
position: record.position,
|
||||
rank: record.rank,
|
||||
baseSalary: record.baseSalary,
|
||||
allowances: {
|
||||
positionAllowance,
|
||||
overtimeAllowance,
|
||||
mealAllowance,
|
||||
transportAllowance,
|
||||
otherAllowance,
|
||||
},
|
||||
deductions: {
|
||||
nationalPension,
|
||||
healthInsurance,
|
||||
longTermCare,
|
||||
employmentInsurance,
|
||||
incomeTax,
|
||||
localIncomeTax,
|
||||
otherDeduction,
|
||||
},
|
||||
totalAllowance,
|
||||
totalDeduction,
|
||||
netPayment: record.baseSalary + totalAllowance - totalDeduction,
|
||||
paymentDate: record.paymentDate,
|
||||
status: record.status,
|
||||
year: record.year,
|
||||
month: record.month,
|
||||
};
|
||||
};
|
||||
|
||||
export function SalaryManagement() {
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('rank');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 날짜 범위 상태
|
||||
const [startDate, setStartDate] = useState('2025-12-01');
|
||||
const [endDate, setEndDate] = useState('2025-12-31');
|
||||
|
||||
// 다이얼로그 상태
|
||||
const [detailDialogOpen, setDetailDialogOpen] = useState(false);
|
||||
const [selectedSalaryDetail, setSelectedSalaryDetail] = useState<SalaryDetail | null>(null);
|
||||
|
||||
// Mock 데이터
|
||||
const [salaryData, setSalaryData] = useState<SalaryRecord[]>(generateSalaryData);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
const toggleSelection = useCallback((id: string) => {
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(id)) newSet.delete(id);
|
||||
else newSet.add(id);
|
||||
return newSet;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === filteredData.length && filteredData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(filteredData.map(item => item.id)));
|
||||
}
|
||||
}, [selectedItems.size]);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
return salaryData.filter(item =>
|
||||
item.employeeName.includes(searchQuery) ||
|
||||
item.department.includes(searchQuery)
|
||||
);
|
||||
}, [salaryData, searchQuery]);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return filteredData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [filteredData, currentPage, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
|
||||
|
||||
// ===== 지급완료 핸들러 =====
|
||||
const handleMarkCompleted = useCallback(() => {
|
||||
if (selectedItems.size === 0) return;
|
||||
|
||||
setSalaryData(prev => prev.map(item => {
|
||||
if (selectedItems.has(item.id)) {
|
||||
return { ...item, status: 'completed' as PaymentStatus };
|
||||
}
|
||||
return item;
|
||||
}));
|
||||
|
||||
setSelectedItems(new Set());
|
||||
console.log('지급완료 처리:', Array.from(selectedItems));
|
||||
}, [selectedItems]);
|
||||
|
||||
// ===== 지급예정 핸들러 =====
|
||||
const handleMarkScheduled = useCallback(() => {
|
||||
if (selectedItems.size === 0) return;
|
||||
|
||||
setSalaryData(prev => prev.map(item => {
|
||||
if (selectedItems.has(item.id)) {
|
||||
return { ...item, status: 'scheduled' as PaymentStatus };
|
||||
}
|
||||
return item;
|
||||
}));
|
||||
|
||||
setSelectedItems(new Set());
|
||||
console.log('지급예정 처리:', Array.from(selectedItems));
|
||||
}, [selectedItems]);
|
||||
|
||||
// ===== 상세보기 핸들러 =====
|
||||
const handleViewDetail = useCallback((record: SalaryRecord) => {
|
||||
const detail = generateSalaryDetail(record);
|
||||
setSelectedSalaryDetail(detail);
|
||||
setDetailDialogOpen(true);
|
||||
}, []);
|
||||
|
||||
// ===== 급여 상세 저장 핸들러 =====
|
||||
const handleSaveDetail = useCallback((updatedDetail: SalaryDetail) => {
|
||||
setSalaryData(prev => prev.map(item => {
|
||||
if (item.employeeId === updatedDetail.employeeId) {
|
||||
return {
|
||||
...item,
|
||||
status: updatedDetail.status,
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}));
|
||||
setDetailDialogOpen(false);
|
||||
console.log('급여 상세 저장:', updatedDetail);
|
||||
}, []);
|
||||
|
||||
// ===== 지급항목 추가 핸들러 =====
|
||||
const handleAddPaymentItem = useCallback(() => {
|
||||
// TODO: 지급항목 추가 다이얼로그 또는 로직 구현
|
||||
console.log('지급항목 추가 클릭');
|
||||
}, []);
|
||||
|
||||
// ===== 탭 (단일 탭) =====
|
||||
const [activeTab, setActiveTab] = useState('all');
|
||||
const tabs: TabOption[] = useMemo(() => [
|
||||
{ value: 'all', label: '전체', count: salaryData.length, color: 'blue' },
|
||||
], [salaryData.length]);
|
||||
|
||||
// ===== 통계 카드 (총 실지급액, 총 기본급, 총 수당, 초과근무, 상여, 총공제) =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
const totalNetPayment = salaryData.reduce((sum, s) => sum + s.netPayment, 0);
|
||||
const totalBaseSalary = salaryData.reduce((sum, s) => sum + s.baseSalary, 0);
|
||||
const totalAllowance = salaryData.reduce((sum, s) => sum + s.allowance, 0);
|
||||
const totalOvertime = salaryData.reduce((sum, s) => sum + s.overtime, 0);
|
||||
const totalBonus = salaryData.reduce((sum, s) => sum + s.bonus, 0);
|
||||
const totalDeduction = salaryData.reduce((sum, s) => sum + s.deduction, 0);
|
||||
|
||||
return [
|
||||
{
|
||||
label: '총 실지급액',
|
||||
value: `${formatCurrency(totalNetPayment)}원`,
|
||||
icon: DollarSign,
|
||||
iconColor: 'text-green-500',
|
||||
},
|
||||
{
|
||||
label: '총 기본급',
|
||||
value: `${formatCurrency(totalBaseSalary)}원`,
|
||||
icon: Banknote,
|
||||
iconColor: 'text-blue-500',
|
||||
},
|
||||
{
|
||||
label: '총 수당',
|
||||
value: `${formatCurrency(totalAllowance)}원`,
|
||||
icon: Briefcase,
|
||||
iconColor: 'text-purple-500',
|
||||
},
|
||||
{
|
||||
label: '초과근무',
|
||||
value: `${formatCurrency(totalOvertime)}원`,
|
||||
icon: Timer,
|
||||
iconColor: 'text-orange-500',
|
||||
},
|
||||
{
|
||||
label: '상여',
|
||||
value: `${formatCurrency(totalBonus)}원`,
|
||||
icon: Gift,
|
||||
iconColor: 'text-pink-500',
|
||||
},
|
||||
{
|
||||
label: '총 공제',
|
||||
value: `${formatCurrency(totalDeduction)}원`,
|
||||
icon: MinusCircle,
|
||||
iconColor: 'text-red-500',
|
||||
},
|
||||
];
|
||||
}, [salaryData]);
|
||||
|
||||
// ===== 테이블 컬럼 (부서, 직책, 이름, 직급, 기본급, 수당, 초과근무, 상여, 공제, 실지급액, 일자, 상태, 작업) =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => [
|
||||
{ key: 'department', label: '부서' },
|
||||
{ key: 'position', label: '직책' },
|
||||
{ key: 'name', label: '이름' },
|
||||
{ key: 'rank', label: '직급' },
|
||||
{ key: 'baseSalary', label: '기본급', className: 'text-right' },
|
||||
{ key: 'allowance', label: '수당', className: 'text-right' },
|
||||
{ key: 'overtime', label: '초과근무', className: 'text-right' },
|
||||
{ key: 'bonus', label: '상여', className: 'text-right' },
|
||||
{ key: 'deduction', label: '공제', className: 'text-right' },
|
||||
{ key: 'netPayment', label: '실지급액', className: 'text-right' },
|
||||
{ key: 'paymentDate', label: '일자', className: 'text-center' },
|
||||
{ key: 'status', label: '상태', className: 'text-center' },
|
||||
{ key: 'action', label: '작업', className: 'text-center w-[80px]' },
|
||||
], []);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: SalaryRecord, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
|
||||
return (
|
||||
<TableRow key={item.id} className="hover:bg-muted/50">
|
||||
<TableCell className="text-center">
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(item.id)} />
|
||||
</TableCell>
|
||||
<TableCell>{item.department}</TableCell>
|
||||
<TableCell>{item.position}</TableCell>
|
||||
<TableCell className="font-medium">{item.employeeName}</TableCell>
|
||||
<TableCell>{item.rank}</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(item.baseSalary)}원</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(item.allowance)}원</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(item.overtime)}원</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(item.bonus)}원</TableCell>
|
||||
<TableCell className="text-right text-red-600">-{formatCurrency(item.deduction)}원</TableCell>
|
||||
<TableCell className="text-right font-medium text-green-600">{formatCurrency(item.netPayment)}원</TableCell>
|
||||
<TableCell className="text-center">{item.paymentDate}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge className={PAYMENT_STATUS_COLORS[item.status]}>
|
||||
{PAYMENT_STATUS_LABELS[item.status]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
title="수정"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection, handleViewDetail]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: SalaryRecord,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id}
|
||||
title={item.employeeName}
|
||||
headerBadges={
|
||||
<Badge className={PAYMENT_STATUS_COLORS[item.status]}>
|
||||
{PAYMENT_STATUS_LABELS[item.status]}
|
||||
</Badge>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="부서" value={item.department} />
|
||||
<InfoField label="직급" value={item.rank} />
|
||||
<InfoField label="기본급" value={`${formatCurrency(item.baseSalary)}원`} />
|
||||
<InfoField label="수당" value={`${formatCurrency(item.allowance)}원`} />
|
||||
<InfoField label="초과근무" value={`${formatCurrency(item.overtime)}원`} />
|
||||
<InfoField label="상여" value={`${formatCurrency(item.bonus)}원`} />
|
||||
<InfoField label="공제" value={`-${formatCurrency(item.deduction)}원`} />
|
||||
<InfoField label="실지급액" value={`${formatCurrency(item.netPayment)}원`} />
|
||||
<InfoField label="지급일" value={item.paymentDate} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
수정
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}, [handleViewDetail]);
|
||||
|
||||
// ===== 헤더 액션 =====
|
||||
const headerActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 날짜 범위 선택 */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-[140px]"
|
||||
/>
|
||||
<span className="text-muted-foreground">~</span>
|
||||
<Input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="w-[140px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 지급완료/지급예정 버튼 - 선택된 항목이 있을 때만 표시 */}
|
||||
{selectedItems.size > 0 && (
|
||||
<>
|
||||
<Button variant="default" onClick={handleMarkCompleted}>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
지급완료
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleMarkScheduled}>
|
||||
<Clock className="h-4 w-4 mr-2" />
|
||||
지급예정
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button variant="outline" onClick={() => console.log('엑셀 다운로드')}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
엑셀 다운로드
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 정렬 필터 =====
|
||||
const extraFilters = (
|
||||
<Select value={sortOption} onValueChange={(v) => setSortOption(v as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(SORT_OPTIONS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>{label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="급여관리"
|
||||
description="직원들의 급여 현황을 관리합니다"
|
||||
icon={DollarSign}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="이름, 부서 검색..."
|
||||
extraFilters={extraFilters}
|
||||
tabs={tabs}
|
||||
activeTab={activeTab}
|
||||
onTabChange={setActiveTab}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: SalaryRecord) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 급여 상세 다이얼로그 */}
|
||||
<SalaryDetailDialog
|
||||
open={detailDialogOpen}
|
||||
onOpenChange={setDetailDialogOpen}
|
||||
salaryDetail={selectedSalaryDetail}
|
||||
onSave={handleSaveDetail}
|
||||
onAddPaymentItem={handleAddPaymentItem}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
100
src/components/hr/SalaryManagement/types.ts
Normal file
100
src/components/hr/SalaryManagement/types.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* 급여관리 타입 정의
|
||||
*/
|
||||
|
||||
// 급여 상태 타입
|
||||
export type PaymentStatus = 'scheduled' | 'completed';
|
||||
|
||||
// 정렬 옵션 타입
|
||||
export type SortOption = 'rank' | 'name' | 'department' | 'paymentDate';
|
||||
|
||||
// 급여 레코드 인터페이스
|
||||
export interface SalaryRecord {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string;
|
||||
rank: string;
|
||||
baseSalary: number; // 기본급
|
||||
allowance: number; // 수당
|
||||
overtime: number; // 초과근무
|
||||
bonus: number; // 상여
|
||||
deduction: number; // 공제
|
||||
netPayment: number; // 실지급액
|
||||
paymentDate: string; // 지급일
|
||||
status: PaymentStatus; // 상태
|
||||
year: number; // 년도
|
||||
month: number; // 월
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// 급여 상세 정보 인터페이스
|
||||
export interface SalaryDetail {
|
||||
// 기본 정보
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string;
|
||||
rank: string;
|
||||
|
||||
// 급여 정보
|
||||
baseSalary: number; // 본봉
|
||||
|
||||
// 수당 내역
|
||||
allowances: {
|
||||
positionAllowance: number; // 직책수당
|
||||
overtimeAllowance: number; // 초과근무수당
|
||||
mealAllowance: number; // 식대
|
||||
transportAllowance: number; // 교통비
|
||||
otherAllowance: number; // 기타수당
|
||||
};
|
||||
|
||||
// 공제 내역
|
||||
deductions: {
|
||||
nationalPension: number; // 국민연금
|
||||
healthInsurance: number; // 건강보험
|
||||
longTermCare: number; // 장기요양보험
|
||||
employmentInsurance: number; // 고용보험
|
||||
incomeTax: number; // 소득세
|
||||
localIncomeTax: number; // 지방소득세
|
||||
otherDeduction: number; // 기타공제
|
||||
};
|
||||
|
||||
// 합계
|
||||
totalAllowance: number; // 수당 합계
|
||||
totalDeduction: number; // 공제 합계
|
||||
netPayment: number; // 실지급액
|
||||
|
||||
// 추가 정보
|
||||
paymentDate: string;
|
||||
status: PaymentStatus;
|
||||
year: number;
|
||||
month: number;
|
||||
}
|
||||
|
||||
// 상태 라벨
|
||||
export const PAYMENT_STATUS_LABELS: Record<PaymentStatus, string> = {
|
||||
scheduled: '지급예정',
|
||||
completed: '지급완료',
|
||||
};
|
||||
|
||||
// 상태 색상
|
||||
export const PAYMENT_STATUS_COLORS: Record<PaymentStatus, string> = {
|
||||
scheduled: 'bg-blue-100 text-blue-800',
|
||||
completed: 'bg-green-100 text-green-800',
|
||||
};
|
||||
|
||||
// 정렬 옵션 라벨
|
||||
export const SORT_OPTIONS: Record<SortOption, string> = {
|
||||
rank: '직급순',
|
||||
name: '이름순',
|
||||
department: '부서순',
|
||||
paymentDate: '지급일순',
|
||||
};
|
||||
|
||||
// 금액 포맷 유틸리티
|
||||
export const formatCurrency = (amount: number): string => {
|
||||
return new Intl.NumberFormat('ko-KR').format(amount);
|
||||
};
|
||||
224
src/components/hr/VacationManagement/VacationAdjustDialog.tsx
Normal file
224
src/components/hr/VacationManagement/VacationAdjustDialog.tsx
Normal file
@@ -0,0 +1,224 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, Minus } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import type { VacationUsageRecord, VacationAdjustment, VacationType } from './types';
|
||||
import { VACATION_TYPE_LABELS } from './types';
|
||||
|
||||
interface VacationAdjustDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
record: VacationUsageRecord | null;
|
||||
onSave: (adjustments: VacationAdjustment[]) => void;
|
||||
}
|
||||
|
||||
interface AdjustmentState {
|
||||
annual: number;
|
||||
monthly: number;
|
||||
reward: number;
|
||||
other: number;
|
||||
}
|
||||
|
||||
export function VacationAdjustDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
record,
|
||||
onSave,
|
||||
}: VacationAdjustDialogProps) {
|
||||
const [adjustments, setAdjustments] = useState<AdjustmentState>({
|
||||
annual: 0,
|
||||
monthly: 0,
|
||||
reward: 0,
|
||||
other: 0,
|
||||
});
|
||||
|
||||
// 다이얼로그가 열릴 때 조정값 초기화
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setAdjustments({
|
||||
annual: 0,
|
||||
monthly: 0,
|
||||
reward: 0,
|
||||
other: 0,
|
||||
});
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// 조정값 증가
|
||||
const handleIncrease = (type: VacationType) => {
|
||||
setAdjustments(prev => ({
|
||||
...prev,
|
||||
[type]: prev[type] + 1,
|
||||
}));
|
||||
};
|
||||
|
||||
// 조정값 감소
|
||||
const handleDecrease = (type: VacationType) => {
|
||||
setAdjustments(prev => ({
|
||||
...prev,
|
||||
[type]: prev[type] - 1,
|
||||
}));
|
||||
};
|
||||
|
||||
// 조정값 직접 입력
|
||||
const handleInputChange = (type: VacationType, value: string) => {
|
||||
const numValue = parseInt(value, 10);
|
||||
if (!isNaN(numValue)) {
|
||||
setAdjustments(prev => ({
|
||||
...prev,
|
||||
[type]: numValue,
|
||||
}));
|
||||
} else if (value === '' || value === '-') {
|
||||
setAdjustments(prev => ({
|
||||
...prev,
|
||||
[type]: 0,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
// 저장 핸들러
|
||||
const handleSave = () => {
|
||||
const adjustmentList: VacationAdjustment[] = [];
|
||||
|
||||
(Object.keys(adjustments) as VacationType[]).forEach((type) => {
|
||||
if (adjustments[type] !== 0) {
|
||||
adjustmentList.push({
|
||||
vacationType: type,
|
||||
adjustment: adjustments[type],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
onSave(adjustmentList);
|
||||
};
|
||||
|
||||
// 취소 핸들러
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
if (!record) return null;
|
||||
|
||||
const vacationTypes: VacationType[] = ['annual', 'monthly', 'reward', 'other'];
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 조정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 사원 정보 */}
|
||||
<div className="bg-muted/50 rounded-lg p-4 mb-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{record.department} / {record.employeeName} / {record.rank}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 조정 테이블 */}
|
||||
<div className="py-2">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[100px]">휴가종류</TableHead>
|
||||
<TableHead className="text-center">총일수</TableHead>
|
||||
<TableHead className="text-center">사용일수</TableHead>
|
||||
<TableHead className="text-center">잔여일수</TableHead>
|
||||
<TableHead className="text-center w-[150px]">조정</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{vacationTypes.map((type) => {
|
||||
const info = record[type];
|
||||
const adjustment = adjustments[type];
|
||||
const newTotal = info.total + adjustment;
|
||||
const newRemaining = info.remaining + adjustment;
|
||||
|
||||
return (
|
||||
<TableRow key={type}>
|
||||
<TableCell className="font-medium">
|
||||
{VACATION_TYPE_LABELS[type]}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<span className={adjustment !== 0 ? 'line-through text-muted-foreground mr-2' : ''}>
|
||||
{info.total}
|
||||
</span>
|
||||
{adjustment !== 0 && (
|
||||
<span className={adjustment > 0 ? 'text-green-600' : 'text-red-600'}>
|
||||
{newTotal}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{info.used}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<span className={adjustment !== 0 ? 'line-through text-muted-foreground mr-2' : ''}>
|
||||
{info.remaining}
|
||||
</span>
|
||||
{adjustment !== 0 && (
|
||||
<span className={adjustment > 0 ? 'text-green-600' : 'text-red-600'}>
|
||||
{newRemaining}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleDecrease(type)}
|
||||
>
|
||||
<Minus className="h-4 w-4" />
|
||||
</Button>
|
||||
<Input
|
||||
type="text"
|
||||
value={adjustment}
|
||||
onChange={(e) => handleInputChange(type, e.target.value)}
|
||||
className="w-16 h-8 text-center"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleIncrease(type)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
162
src/components/hr/VacationManagement/VacationGrantDialog.tsx
Normal file
162
src/components/hr/VacationManagement/VacationGrantDialog.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { VacationGrantFormData, VacationType } from './types';
|
||||
import { VACATION_TYPE_LABELS } from './types';
|
||||
|
||||
interface VacationGrantDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSave: (data: VacationGrantFormData) => void;
|
||||
}
|
||||
|
||||
const mockEmployees = [
|
||||
{ id: '1', name: '김철수', department: '개발팀' },
|
||||
{ id: '2', name: '이영희', department: '디자인팀' },
|
||||
{ id: '3', name: '박민수', department: '기획팀' },
|
||||
{ id: '4', name: '정수진', department: '영업팀' },
|
||||
{ id: '5', name: '최동현', department: '인사팀' },
|
||||
];
|
||||
|
||||
export function VacationGrantDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSave,
|
||||
}: VacationGrantDialogProps) {
|
||||
const [formData, setFormData] = useState<VacationGrantFormData>({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
grantDays: 1,
|
||||
reason: '',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setFormData({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
grantDays: 1,
|
||||
reason: '',
|
||||
});
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const handleSave = () => {
|
||||
if (!formData.employeeId) {
|
||||
alert('사원을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (formData.grantDays < 1) {
|
||||
alert('부여 일수는 1 이상이어야 합니다.');
|
||||
return;
|
||||
}
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 부여 등록</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
{/* 사원 선택 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="employee">사원 선택</Label>
|
||||
<Select
|
||||
value={formData.employeeId}
|
||||
onValueChange={(value) => setFormData(prev => ({ ...prev, employeeId: value }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="사원을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{mockEmployees.map((emp) => (
|
||||
<SelectItem key={emp.id} value={emp.id}>
|
||||
{emp.name} ({emp.department})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 휴가 유형 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="vacationType">휴가 유형</Label>
|
||||
<Select
|
||||
value={formData.vacationType}
|
||||
onValueChange={(value) => setFormData(prev => ({ ...prev, vacationType: value as VacationType }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(VACATION_TYPE_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 부여 일수 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="grantDays">부여 일수</Label>
|
||||
<Input
|
||||
id="grantDays"
|
||||
type="number"
|
||||
min={1}
|
||||
value={formData.grantDays}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, grantDays: parseInt(e.target.value) || 1 }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 사유 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="reason">사유</Label>
|
||||
<Textarea
|
||||
id="reason"
|
||||
placeholder="부여 사유를 입력하세요 (선택)"
|
||||
value={formData.reason || ''}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, reason: e.target.value }))}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
등록
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
200
src/components/hr/VacationManagement/VacationRegisterDialog.tsx
Normal file
200
src/components/hr/VacationManagement/VacationRegisterDialog.tsx
Normal file
@@ -0,0 +1,200 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type {
|
||||
VacationFormData,
|
||||
VacationTypeConfig,
|
||||
EmployeeOption,
|
||||
VacationType,
|
||||
} from './types';
|
||||
|
||||
interface VacationRegisterDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
employees: EmployeeOption[];
|
||||
vacationTypes: VacationTypeConfig[];
|
||||
onSave: (data: VacationFormData) => void;
|
||||
}
|
||||
|
||||
export function VacationRegisterDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
employees,
|
||||
vacationTypes,
|
||||
onSave,
|
||||
}: VacationRegisterDialogProps) {
|
||||
const [formData, setFormData] = useState<VacationFormData>({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
days: 0,
|
||||
memo: '',
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
// 다이얼로그가 열릴 때 폼 초기화
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setFormData({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
days: 0,
|
||||
memo: '',
|
||||
});
|
||||
setErrors({});
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// 폼 유효성 검사
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!formData.employeeId) {
|
||||
newErrors.employeeId = '사원을 선택해주세요';
|
||||
}
|
||||
|
||||
if (!formData.vacationType) {
|
||||
newErrors.vacationType = '휴가 종류를 선택해주세요';
|
||||
}
|
||||
|
||||
if (formData.days <= 0) {
|
||||
newErrors.days = '지급 일수를 입력해주세요';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// 저장 핸들러
|
||||
const handleSave = () => {
|
||||
if (validateForm()) {
|
||||
onSave(formData);
|
||||
}
|
||||
};
|
||||
|
||||
// 취소 핸들러
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 등록</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
{/* 사원 선택 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="employee">
|
||||
사원 선택 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Select
|
||||
value={formData.employeeId}
|
||||
onValueChange={(value) => setFormData((prev: VacationFormData) => ({ ...prev, employeeId: value }))}
|
||||
>
|
||||
<SelectTrigger id="employee" className={errors.employeeId ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="사원을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{employees.map((employee) => (
|
||||
<SelectItem key={employee.id} value={employee.id}>
|
||||
{employee.department} / {employee.name} / {employee.rank}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.employeeId && (
|
||||
<p className="text-sm text-red-500">{errors.employeeId}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 휴가 종류 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="vacationType">
|
||||
휴가 종류 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Select
|
||||
value={formData.vacationType}
|
||||
onValueChange={(value) => setFormData((prev: VacationFormData) => ({ ...prev, vacationType: value as VacationType }))}
|
||||
>
|
||||
<SelectTrigger id="vacationType" className={errors.vacationType ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="휴가 종류를 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{vacationTypes.map((type) => (
|
||||
<SelectItem key={type.id} value={type.type}>
|
||||
{type.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.vacationType && (
|
||||
<p className="text-sm text-red-500">{errors.vacationType}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 지급 일수 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="days">
|
||||
지급 일수 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="days"
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.5"
|
||||
value={formData.days || ''}
|
||||
onChange={(e) => setFormData((prev: VacationFormData) => ({ ...prev, days: parseFloat(e.target.value) || 0 }))}
|
||||
className={errors.days ? 'border-red-500' : ''}
|
||||
placeholder="일수를 입력하세요"
|
||||
/>
|
||||
{errors.days && (
|
||||
<p className="text-sm text-red-500">{errors.days}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 비고 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="memo">비고</Label>
|
||||
<Textarea
|
||||
id="memo"
|
||||
value={formData.memo || ''}
|
||||
onChange={(e) => setFormData((prev: VacationFormData) => ({ ...prev, memo: e.target.value }))}
|
||||
placeholder="비고를 입력하세요 (선택)"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
등록
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
232
src/components/hr/VacationManagement/VacationRequestDialog.tsx
Normal file
232
src/components/hr/VacationManagement/VacationRequestDialog.tsx
Normal file
@@ -0,0 +1,232 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { format, differenceInDays } from 'date-fns';
|
||||
import { CalendarIcon } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { VacationRequestFormData, VacationType } from './types';
|
||||
import { VACATION_TYPE_LABELS } from './types';
|
||||
|
||||
interface VacationRequestDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSave: (data: VacationRequestFormData) => void;
|
||||
}
|
||||
|
||||
const mockEmployees = [
|
||||
{ id: '1', name: '김철수', department: '개발팀' },
|
||||
{ id: '2', name: '이영희', department: '디자인팀' },
|
||||
{ id: '3', name: '박민수', department: '기획팀' },
|
||||
{ id: '4', name: '정수진', department: '영업팀' },
|
||||
{ id: '5', name: '최동현', department: '인사팀' },
|
||||
];
|
||||
|
||||
export function VacationRequestDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSave,
|
||||
}: VacationRequestDialogProps) {
|
||||
const [formData, setFormData] = useState<VacationRequestFormData>({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
vacationDays: 1,
|
||||
});
|
||||
const [startDate, setStartDate] = useState<Date | undefined>();
|
||||
const [endDate, setEndDate] = useState<Date | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setFormData({
|
||||
employeeId: '',
|
||||
vacationType: 'annual',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
vacationDays: 1,
|
||||
});
|
||||
setStartDate(undefined);
|
||||
setEndDate(undefined);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (startDate && endDate) {
|
||||
const days = differenceInDays(endDate, startDate) + 1;
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
startDate: format(startDate, 'yyyy-MM-dd'),
|
||||
endDate: format(endDate, 'yyyy-MM-dd'),
|
||||
vacationDays: days > 0 ? days : 1,
|
||||
}));
|
||||
}
|
||||
}, [startDate, endDate]);
|
||||
|
||||
const handleSave = () => {
|
||||
if (!formData.employeeId) {
|
||||
alert('사원을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!startDate || !endDate) {
|
||||
alert('휴가 기간을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
if (endDate < startDate) {
|
||||
alert('종료일은 시작일 이후여야 합니다.');
|
||||
return;
|
||||
}
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 신청</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
{/* 사원 선택 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="employee">사원 선택</Label>
|
||||
<Select
|
||||
value={formData.employeeId}
|
||||
onValueChange={(value) => setFormData(prev => ({ ...prev, employeeId: value }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="사원을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{mockEmployees.map((emp) => (
|
||||
<SelectItem key={emp.id} value={emp.id}>
|
||||
{emp.name} ({emp.department})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 휴가 유형 */}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="vacationType">휴가 유형</Label>
|
||||
<Select
|
||||
value={formData.vacationType}
|
||||
onValueChange={(value) => setFormData(prev => ({ ...prev, vacationType: value as VacationType }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(VACATION_TYPE_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 시작일 */}
|
||||
<div className="grid gap-2">
|
||||
<Label>시작일</Label>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'w-full justify-start text-left font-normal',
|
||||
!startDate && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{startDate ? format(startDate, 'yyyy-MM-dd') : '시작일 선택'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={startDate}
|
||||
onSelect={setStartDate}
|
||||
initialFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
{/* 종료일 */}
|
||||
<div className="grid gap-2">
|
||||
<Label>종료일</Label>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'w-full justify-start text-left font-normal',
|
||||
!endDate && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{endDate ? format(endDate, 'yyyy-MM-dd') : '종료일 선택'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={endDate}
|
||||
onSelect={setEndDate}
|
||||
disabled={(date) => startDate ? date < startDate : false}
|
||||
initialFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
{/* 휴가 일수 (자동 계산) */}
|
||||
{startDate && endDate && (
|
||||
<div className="grid gap-2">
|
||||
<Label>휴가 일수</Label>
|
||||
<div className="p-3 bg-muted rounded-md text-center font-medium">
|
||||
{formData.vacationDays}일
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
신청
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import type { VacationTypeConfig, VacationType } from './types';
|
||||
|
||||
interface VacationTypeSettingsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
vacationTypes: VacationTypeConfig[];
|
||||
onSave: (types: VacationTypeConfig[]) => void;
|
||||
}
|
||||
|
||||
export function VacationTypeSettingsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
vacationTypes,
|
||||
onSave,
|
||||
}: VacationTypeSettingsDialogProps) {
|
||||
const [localTypes, setLocalTypes] = useState<VacationTypeConfig[]>([]);
|
||||
|
||||
// 다이얼로그가 열릴 때 로컬 상태 초기화
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setLocalTypes([...vacationTypes]);
|
||||
}
|
||||
}, [open, vacationTypes]);
|
||||
|
||||
// 사용여부 토글
|
||||
const handleToggleActive = (id: string) => {
|
||||
setLocalTypes(prev =>
|
||||
prev.map(type =>
|
||||
type.id === id ? { ...type, isActive: !type.isActive } : type
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// 이름 변경
|
||||
const handleNameChange = (id: string, name: string) => {
|
||||
setLocalTypes(prev =>
|
||||
prev.map(type =>
|
||||
type.id === id ? { ...type, name } : type
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// 설명 변경
|
||||
const handleDescriptionChange = (id: string, description: string) => {
|
||||
setLocalTypes(prev =>
|
||||
prev.map(type =>
|
||||
type.id === id ? { ...type, description } : type
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// 휴가종류 추가
|
||||
const handleAddType = () => {
|
||||
const newId = String(Date.now());
|
||||
const newType: VacationTypeConfig = {
|
||||
id: newId,
|
||||
name: '새 휴가종류',
|
||||
type: 'other' as VacationType,
|
||||
isActive: true,
|
||||
description: '',
|
||||
};
|
||||
setLocalTypes(prev => [...prev, newType]);
|
||||
};
|
||||
|
||||
// 휴가종류 삭제
|
||||
const handleDeleteType = (id: string) => {
|
||||
// 기본 4개 타입은 삭제 불가
|
||||
const defaultTypeIds = ['1', '2', '3', '4'];
|
||||
if (defaultTypeIds.includes(id)) {
|
||||
return;
|
||||
}
|
||||
setLocalTypes(prev => prev.filter(type => type.id !== id));
|
||||
};
|
||||
|
||||
// 저장 핸들러
|
||||
const handleSave = () => {
|
||||
onSave(localTypes);
|
||||
};
|
||||
|
||||
// 취소 핸들러
|
||||
const handleCancel = () => {
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// 기본 타입인지 확인 (삭제 불가)
|
||||
const isDefaultType = (id: string) => {
|
||||
return ['1', '2', '3', '4'].includes(id);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[700px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>휴가 종류 설정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-4">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[150px]">휴가종류명</TableHead>
|
||||
<TableHead className="w-[100px] text-center">사용여부</TableHead>
|
||||
<TableHead>설명</TableHead>
|
||||
<TableHead className="w-[60px] text-center">삭제</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{localTypes.map((type) => (
|
||||
<TableRow key={type.id}>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={type.name}
|
||||
onChange={(e) => handleNameChange(type.id, e.target.value)}
|
||||
className="h-8"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<div className="flex justify-center">
|
||||
<Switch
|
||||
checked={type.isActive}
|
||||
onCheckedChange={() => handleToggleActive(type.id)}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={type.description || ''}
|
||||
onChange={(e) => handleDescriptionChange(type.id, e.target.value)}
|
||||
placeholder="설명을 입력하세요"
|
||||
className="h-8"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDeleteType(type.id)}
|
||||
disabled={isDefaultType(type.id)}
|
||||
className={isDefaultType(type.id) ? 'opacity-30 cursor-not-allowed' : 'text-red-500 hover:text-red-700'}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
{/* 휴가종류 추가 버튼 */}
|
||||
<div className="mt-4">
|
||||
<Button variant="outline" onClick={handleAddType} className="w-full">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
휴가종류 추가
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
571
src/components/hr/VacationManagement/index.tsx
Normal file
571
src/components/hr/VacationManagement/index.tsx
Normal file
@@ -0,0 +1,571 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
Download,
|
||||
Plus,
|
||||
Calendar,
|
||||
Check,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
type StatCard,
|
||||
type TabOption,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { VacationGrantDialog } from './VacationGrantDialog';
|
||||
import { VacationRequestDialog } from './VacationRequestDialog';
|
||||
import type {
|
||||
MainTabType,
|
||||
VacationUsageRecord,
|
||||
VacationGrantRecord,
|
||||
VacationRequestRecord,
|
||||
SortOption,
|
||||
VacationType,
|
||||
RequestStatus,
|
||||
} from './types';
|
||||
import {
|
||||
MAIN_TAB_LABELS,
|
||||
SORT_OPTIONS,
|
||||
VACATION_TYPE_LABELS,
|
||||
REQUEST_STATUS_LABELS,
|
||||
REQUEST_STATUS_COLORS,
|
||||
} from './types';
|
||||
|
||||
// ===== Mock 데이터 생성 =====
|
||||
const generateUsageData = (): VacationUsageRecord[] => {
|
||||
const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
|
||||
const positions = ['팀장', '파트장', '선임', '주임', '사원'];
|
||||
const ranks = ['부장', '차장', '과장', '대리', '사원'];
|
||||
|
||||
// 휴가 일수 포맷: "15일", "12일3시간" 등
|
||||
const usedVacations = ['12일3시간', '8일', '5일4시간', '10일', '3일2시간', '7일5시간', '9일', '6일1시간', '4일', '11일6시간'];
|
||||
const remainingVacations = ['2일5시간', '7일', '9일4시간', '5일', '11일6시간', '7일3시간', '6일', '8일7시간', '11일', '3일2시간'];
|
||||
const grantedVacations = ['0일', '3일', '2일', '1일', '4일', '0일', '2일', '3일', '1일', '0일'];
|
||||
|
||||
return Array.from({ length: 10 }, (_, i) => ({
|
||||
id: `usage-${i + 1}`,
|
||||
employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
|
||||
employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현', '한승우', '송예진'][i],
|
||||
department: departments[i % departments.length],
|
||||
position: positions[i % positions.length],
|
||||
rank: ranks[i % ranks.length],
|
||||
hireDate: format(new Date(2020 + (i % 5), i % 12, (i % 28) + 1), 'yyyy-MM-dd'),
|
||||
baseVacation: '15일',
|
||||
grantedVacation: grantedVacations[i],
|
||||
usedVacation: usedVacations[i],
|
||||
remainingVacation: remainingVacations[i],
|
||||
// 휴가 유형별 상세 (조정 다이얼로그용)
|
||||
annual: { total: 15, used: 10 + (i % 5), remaining: 5 - (i % 5) },
|
||||
monthly: { total: 3, used: i % 3, remaining: 3 - (i % 3) },
|
||||
reward: { total: i % 4, used: 0, remaining: i % 4 },
|
||||
other: { total: 0, used: 0, remaining: 0 },
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}));
|
||||
};
|
||||
|
||||
const generateGrantData = (): VacationGrantRecord[] => {
|
||||
const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
|
||||
const positions = ['팀장', '파트장', '선임', '주임', '사원'];
|
||||
const ranks = ['부장', '차장', '과장', '대리', '사원'];
|
||||
const vacationTypes: VacationType[] = ['annual', 'monthly', 'reward', 'other'];
|
||||
const reasons = ['연차 부여', '포상 휴가', '특별 휴가', '경조사 휴가', ''];
|
||||
|
||||
return Array.from({ length: 8 }, (_, i) => ({
|
||||
id: `grant-${i + 1}`,
|
||||
employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
|
||||
employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현'][i],
|
||||
department: departments[i % departments.length],
|
||||
position: positions[i % positions.length],
|
||||
rank: ranks[i % ranks.length],
|
||||
vacationType: vacationTypes[i % vacationTypes.length],
|
||||
grantDate: format(new Date(2025, 11, (i % 28) + 1), 'yyyy-MM-dd'),
|
||||
grantDays: Math.floor(Math.random() * 5) + 1,
|
||||
reason: reasons[i % reasons.length],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}));
|
||||
};
|
||||
|
||||
const generateRequestData = (): VacationRequestRecord[] => {
|
||||
const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
|
||||
const positions = ['팀장', '파트장', '선임', '주임', '사원'];
|
||||
const ranks = ['부장', '차장', '과장', '대리', '사원'];
|
||||
const statuses: RequestStatus[] = ['pending', 'approved', 'rejected'];
|
||||
|
||||
return Array.from({ length: 7 }, (_, i) => {
|
||||
const startDate = new Date(2025, 11, (i % 28) + 1);
|
||||
const endDate = new Date(startDate);
|
||||
endDate.setDate(endDate.getDate() + Math.floor(Math.random() * 5) + 1);
|
||||
|
||||
return {
|
||||
id: `request-${i + 1}`,
|
||||
employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
|
||||
employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호'][i],
|
||||
department: departments[i % departments.length],
|
||||
position: positions[i % positions.length],
|
||||
rank: ranks[i % ranks.length],
|
||||
startDate: format(startDate, 'yyyy-MM-dd'),
|
||||
endDate: format(endDate, 'yyyy-MM-dd'),
|
||||
vacationDays: Math.floor(Math.random() * 5) + 1,
|
||||
status: statuses[i % statuses.length],
|
||||
requestDate: format(new Date(2025, 11, i + 1), 'yyyy-MM-dd'),
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export function VacationManagement() {
|
||||
// ===== 상태 관리 =====
|
||||
const [mainTab, setMainTab] = useState<MainTabType>('usage');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortOption, setSortOption] = useState<SortOption>('rank');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 날짜 범위 상태 (input type="date" 용)
|
||||
const [startDate, setStartDate] = useState('2025-12-01');
|
||||
const [endDate, setEndDate] = useState('2025-12-31');
|
||||
|
||||
// 다이얼로그 상태
|
||||
const [grantDialogOpen, setGrantDialogOpen] = useState(false);
|
||||
const [requestDialogOpen, setRequestDialogOpen] = useState(false);
|
||||
|
||||
// Mock 데이터
|
||||
const [usageData] = useState<VacationUsageRecord[]>(generateUsageData);
|
||||
const [grantData] = useState<VacationGrantRecord[]>(generateGrantData);
|
||||
const [requestData] = useState<VacationRequestRecord[]>(generateRequestData);
|
||||
|
||||
// ===== 탭 변경 핸들러 =====
|
||||
const handleMainTabChange = useCallback((value: string) => {
|
||||
setMainTab(value as MainTabType);
|
||||
setSelectedItems(new Set());
|
||||
setSearchQuery('');
|
||||
setCurrentPage(1);
|
||||
}, []);
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
const toggleSelection = useCallback((id: string) => {
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(id)) newSet.delete(id);
|
||||
else newSet.add(id);
|
||||
return newSet;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
const currentData = mainTab === 'usage' ? filteredUsageData : mainTab === 'grant' ? filteredGrantData : filteredRequestData;
|
||||
if (selectedItems.size === currentData.length && currentData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(currentData.map(item => item.id)));
|
||||
}
|
||||
}, [mainTab, selectedItems.size]);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredUsageData = useMemo(() => {
|
||||
return usageData.filter(item =>
|
||||
item.employeeName.includes(searchQuery) ||
|
||||
item.department.includes(searchQuery)
|
||||
);
|
||||
}, [usageData, searchQuery]);
|
||||
|
||||
const filteredGrantData = useMemo(() => {
|
||||
return grantData.filter(item =>
|
||||
item.employeeName.includes(searchQuery) ||
|
||||
item.department.includes(searchQuery)
|
||||
);
|
||||
}, [grantData, searchQuery]);
|
||||
|
||||
const filteredRequestData = useMemo(() => {
|
||||
return requestData.filter(item =>
|
||||
item.employeeName.includes(searchQuery) ||
|
||||
item.department.includes(searchQuery)
|
||||
);
|
||||
}, [requestData, searchQuery]);
|
||||
|
||||
// ===== 현재 탭 데이터 =====
|
||||
const currentData = useMemo(() => {
|
||||
switch (mainTab) {
|
||||
case 'usage': return filteredUsageData;
|
||||
case 'grant': return filteredGrantData;
|
||||
case 'request': return filteredRequestData;
|
||||
default: return [];
|
||||
}
|
||||
}, [mainTab, filteredUsageData, filteredGrantData, filteredRequestData]);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return currentData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [currentData, currentPage, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(currentData.length / itemsPerPage);
|
||||
|
||||
// ===== 승인/거절 핸들러 =====
|
||||
const handleApprove = useCallback(() => {
|
||||
console.log('승인:', Array.from(selectedItems));
|
||||
setSelectedItems(new Set());
|
||||
}, [selectedItems]);
|
||||
|
||||
const handleReject = useCallback(() => {
|
||||
console.log('거절:', Array.from(selectedItems));
|
||||
setSelectedItems(new Set());
|
||||
}, [selectedItems]);
|
||||
|
||||
// ===== 통계 카드 (스크린샷: 연차 N명, 월차 N명, 포상휴가 N명, 기타휴가 N명) =====
|
||||
const statCards: StatCard[] = useMemo(() => [
|
||||
{ label: '연차', value: `${usageData.length}명`, icon: Calendar, iconColor: 'text-blue-500' },
|
||||
{ label: '월차', value: `${usageData.filter(u => u.grantedVacation !== '0일').length}명`, icon: Calendar, iconColor: 'text-green-500' },
|
||||
{ label: '포상휴가', value: `${grantData.filter(g => g.vacationType === 'reward').length}명`, icon: Calendar, iconColor: 'text-purple-500' },
|
||||
{ label: '기타휴가', value: `${grantData.filter(g => g.vacationType === 'other').length}명`, icon: Calendar, iconColor: 'text-orange-500' },
|
||||
], [usageData, grantData]);
|
||||
|
||||
// ===== 탭 옵션 (카드 아래에 표시됨) =====
|
||||
const tabs: TabOption[] = useMemo(() => [
|
||||
{ value: 'usage', label: MAIN_TAB_LABELS.usage, count: usageData.length, color: 'blue' },
|
||||
{ value: 'grant', label: MAIN_TAB_LABELS.grant, count: grantData.length, color: 'green' },
|
||||
{ value: 'request', label: MAIN_TAB_LABELS.request, count: requestData.length, color: 'purple' },
|
||||
], [usageData.length, grantData.length, requestData.length]);
|
||||
|
||||
// ===== 테이블 컬럼 (탭별) =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => {
|
||||
if (mainTab === 'usage') {
|
||||
// 휴가 사용현황: 부서|직책|이름|직급|입사일|기본|부여|사용|잔액
|
||||
return [
|
||||
{ key: 'department', label: '부서' },
|
||||
{ key: 'position', label: '직책' },
|
||||
{ key: 'name', label: '이름' },
|
||||
{ key: 'rank', label: '직급' },
|
||||
{ key: 'hireDate', label: '입사일' },
|
||||
{ key: 'base', label: '기본', className: 'text-center' },
|
||||
{ key: 'granted', label: '부여', className: 'text-center' },
|
||||
{ key: 'used', label: '사용', className: 'text-center' },
|
||||
{ key: 'remaining', label: '잔여', className: 'text-center' },
|
||||
];
|
||||
} else if (mainTab === 'grant') {
|
||||
// 휴가 부여현황: 부서|직책|이름|직급|유형|부여일|부여휴가일수|사유
|
||||
return [
|
||||
{ key: 'department', label: '부서' },
|
||||
{ key: 'position', label: '직책' },
|
||||
{ key: 'name', label: '이름' },
|
||||
{ key: 'rank', label: '직급' },
|
||||
{ key: 'type', label: '유형' },
|
||||
{ key: 'grantDate', label: '부여일' },
|
||||
{ key: 'grantDays', label: '부여휴가일수', className: 'text-center' },
|
||||
{ key: 'reason', label: '사유' },
|
||||
];
|
||||
} else {
|
||||
// 휴가 신청현황: 부서|직책|이름|직급|휴가기간|휴가일수|상태|신청일
|
||||
return [
|
||||
{ key: 'department', label: '부서' },
|
||||
{ key: 'position', label: '직책' },
|
||||
{ key: 'name', label: '이름' },
|
||||
{ key: 'rank', label: '직급' },
|
||||
{ key: 'period', label: '휴가기간' },
|
||||
{ key: 'days', label: '휴가일수', className: 'text-center' },
|
||||
{ key: 'status', label: '상태', className: 'text-center' },
|
||||
{ key: 'requestDate', label: '신청일' },
|
||||
];
|
||||
}
|
||||
}, [mainTab]);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: any, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id);
|
||||
|
||||
if (mainTab === 'usage') {
|
||||
const record = item as VacationUsageRecord;
|
||||
return (
|
||||
<TableRow key={record.id} className="hover:bg-muted/50">
|
||||
<TableCell className="text-center">
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
|
||||
</TableCell>
|
||||
<TableCell>{record.department}</TableCell>
|
||||
<TableCell>{record.position}</TableCell>
|
||||
<TableCell className="font-medium">{record.employeeName}</TableCell>
|
||||
<TableCell>{record.rank}</TableCell>
|
||||
<TableCell>{format(new Date(record.hireDate), 'yyyy-MM-dd')}</TableCell>
|
||||
<TableCell className="text-center">{record.baseVacation}</TableCell>
|
||||
<TableCell className="text-center">{record.grantedVacation}</TableCell>
|
||||
<TableCell className="text-center">{record.usedVacation}</TableCell>
|
||||
<TableCell className="text-center font-medium">{record.remainingVacation}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
} else if (mainTab === 'grant') {
|
||||
const record = item as VacationGrantRecord;
|
||||
return (
|
||||
<TableRow key={record.id} className="hover:bg-muted/50">
|
||||
<TableCell className="text-center">
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
|
||||
</TableCell>
|
||||
<TableCell>{record.department}</TableCell>
|
||||
<TableCell>{record.position}</TableCell>
|
||||
<TableCell className="font-medium">{record.employeeName}</TableCell>
|
||||
<TableCell>{record.rank}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline">{VACATION_TYPE_LABELS[record.vacationType]}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{format(new Date(record.grantDate), 'yyyy-MM-dd')}</TableCell>
|
||||
<TableCell className="text-center">{record.grantDays}일</TableCell>
|
||||
<TableCell className="text-muted-foreground">{record.reason || '-'}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
} else {
|
||||
const record = item as VacationRequestRecord;
|
||||
return (
|
||||
<TableRow key={record.id} className="hover:bg-muted/50">
|
||||
<TableCell className="text-center">
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
|
||||
</TableCell>
|
||||
<TableCell>{record.department}</TableCell>
|
||||
<TableCell>{record.position}</TableCell>
|
||||
<TableCell className="font-medium">{record.employeeName}</TableCell>
|
||||
<TableCell>{record.rank}</TableCell>
|
||||
<TableCell>
|
||||
{format(new Date(record.startDate), 'yyyy-MM-dd')} ~ {format(new Date(record.endDate), 'yyyy-MM-dd')}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{record.vacationDays}일</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge className={REQUEST_STATUS_COLORS[record.status]}>
|
||||
{REQUEST_STATUS_LABELS[record.status]}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{format(new Date(record.requestDate), 'yyyy-MM-dd')}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
}, [mainTab, selectedItems, toggleSelection]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: any,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
if (mainTab === 'usage') {
|
||||
const record = item as VacationUsageRecord;
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={record.id}
|
||||
title={record.employeeName}
|
||||
headerBadges={<Badge variant="outline">{record.department}</Badge>}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="직급" value={record.rank} />
|
||||
<InfoField label="입사일" value={record.hireDate} />
|
||||
<InfoField label="기본" value={record.baseVacation} />
|
||||
<InfoField label="부여" value={record.grantedVacation} />
|
||||
<InfoField label="사용" value={record.usedVacation} />
|
||||
<InfoField label="잔여" value={record.remainingVacation} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
} else if (mainTab === 'grant') {
|
||||
const record = item as VacationGrantRecord;
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={record.id}
|
||||
title={record.employeeName}
|
||||
headerBadges={<Badge variant="outline">{VACATION_TYPE_LABELS[record.vacationType]}</Badge>}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="부서" value={record.department} />
|
||||
<InfoField label="직급" value={record.rank} />
|
||||
<InfoField label="부여일" value={record.grantDate} />
|
||||
<InfoField label="일수" value={`${record.grantDays}일`} />
|
||||
{record.reason && <InfoField label="사유" value={record.reason} />}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
const record = item as VacationRequestRecord;
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={record.id}
|
||||
title={record.employeeName}
|
||||
headerBadges={
|
||||
<Badge className={REQUEST_STATUS_COLORS[record.status]}>
|
||||
{REQUEST_STATUS_LABELS[record.status]}
|
||||
</Badge>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="부서" value={record.department} />
|
||||
<InfoField label="직급" value={record.rank} />
|
||||
<InfoField label="기간" value={`${record.startDate} ~ ${record.endDate}`} />
|
||||
<InfoField label="일수" value={`${record.vacationDays}일`} />
|
||||
<InfoField label="신청일" value={record.requestDate} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
record.status === 'pending' && (
|
||||
<div className="flex gap-2">
|
||||
<Button variant="default" className="flex-1" onClick={handleApprove}>
|
||||
<Check className="w-4 h-4 mr-2" /> 승인
|
||||
</Button>
|
||||
<Button variant="outline" className="flex-1" onClick={handleReject}>
|
||||
<X className="w-4 h-4 mr-2" /> 거절
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}, [mainTab, handleApprove, handleReject]);
|
||||
|
||||
// ===== 헤더 액션 (달력 + 버튼들) =====
|
||||
const headerActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* 날짜 범위 선택 - 브라우저 기본 달력 사용 */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-[140px]"
|
||||
/>
|
||||
<span className="text-muted-foreground">~</span>
|
||||
<Input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="w-[140px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 탭별 액션 버튼 */}
|
||||
{mainTab === 'grant' && (
|
||||
<Button onClick={() => setGrantDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
부여등록
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{mainTab === 'request' && (
|
||||
<>
|
||||
<Button onClick={() => setRequestDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
휴가신청
|
||||
</Button>
|
||||
{selectedItems.size > 0 && (
|
||||
<>
|
||||
<Button variant="default" onClick={handleApprove}>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
승인
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={handleReject}>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
거절
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button variant="outline" onClick={() => console.log('엑셀 다운로드')}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
엑셀 다운로드
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 정렬 필터 =====
|
||||
const extraFilters = (
|
||||
<Select value={sortOption} onValueChange={(v) => setSortOption(v as SortOption)}>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(SORT_OPTIONS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>{label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* IntegratedListTemplateV2 - 카드 아래에 탭 표시됨 */}
|
||||
<IntegratedListTemplateV2
|
||||
title="휴가관리"
|
||||
description="직원들의 휴가 현황을 관리합니다"
|
||||
icon={Calendar}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="이름, 부서 검색..."
|
||||
extraFilters={extraFilters}
|
||||
tabs={tabs}
|
||||
activeTab={mainTab}
|
||||
onTabChange={handleMainTabChange}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={currentData.length}
|
||||
allData={currentData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: any) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: currentData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 다이얼로그 */}
|
||||
<VacationGrantDialog
|
||||
open={grantDialogOpen}
|
||||
onOpenChange={setGrantDialogOpen}
|
||||
onSave={(data) => {
|
||||
console.log('부여 등록:', data);
|
||||
setGrantDialogOpen(false);
|
||||
}}
|
||||
/>
|
||||
|
||||
<VacationRequestDialog
|
||||
open={requestDialogOpen}
|
||||
onOpenChange={setRequestDialogOpen}
|
||||
onSave={(data) => {
|
||||
console.log('휴가 신청:', data);
|
||||
setRequestDialogOpen(false);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
175
src/components/hr/VacationManagement/types.ts
Normal file
175
src/components/hr/VacationManagement/types.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* 휴가관리 타입 정의
|
||||
* 3개 메인 탭: 휴가 사용현황, 휴가 부여현황, 휴가 신청현황
|
||||
*/
|
||||
|
||||
// ===== 메인 탭 타입 =====
|
||||
export type MainTabType = 'usage' | 'grant' | 'request';
|
||||
|
||||
// 휴가 유형
|
||||
export type VacationType = 'annual' | 'monthly' | 'reward' | 'other';
|
||||
|
||||
// 정렬 옵션
|
||||
export type SortOption = 'rank' | 'deptAsc' | 'deptDesc' | 'nameAsc' | 'nameDesc';
|
||||
|
||||
// 휴가 신청 상태
|
||||
export type RequestStatus = 'pending' | 'approved' | 'rejected';
|
||||
|
||||
// ===== 탭 1: 휴가 사용현황 =====
|
||||
// 휴가 유형별 상세 정보
|
||||
export interface VacationTypeDetail {
|
||||
total: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
}
|
||||
|
||||
// 테이블 컬럼: 부서 | 직책 | 이름 | 직급 | 입사일 | 기본 | 부여 | 사용 | 잔여
|
||||
export interface VacationUsageRecord {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string; // 직책
|
||||
rank: string; // 직급
|
||||
hireDate: string; // 입사일
|
||||
baseVacation: string; // 기본 (예: "15일")
|
||||
grantedVacation: string; // 부여 (예: "3일")
|
||||
usedVacation: string; // 사용 (예: "12일3시간")
|
||||
remainingVacation: string; // 잔여 (예: "2일5시간")
|
||||
// 휴가 유형별 상세 (조정 다이얼로그용)
|
||||
annual: VacationTypeDetail;
|
||||
monthly: VacationTypeDetail;
|
||||
reward: VacationTypeDetail;
|
||||
other: VacationTypeDetail;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ===== 탭 2: 휴가 부여현황 =====
|
||||
// 테이블 컬럼: 부서 | 직책 | 이름 | 직급 | 유형 | 부여일 | 부여휴가일수 | 사유
|
||||
export interface VacationGrantRecord {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string; // 직책
|
||||
rank: string; // 직급
|
||||
vacationType: VacationType; // 유형
|
||||
grantDate: string; // 부여일
|
||||
grantDays: number; // 부여휴가일수
|
||||
reason?: string; // 사유
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ===== 탭 3: 휴가 신청현황 =====
|
||||
// 테이블 컬럼: 부서 | 직책 | 이름 | 직급 | 휴가기간 | 휴가일수 | 상태 | 신청일
|
||||
export interface VacationRequestRecord {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
employeeName: string;
|
||||
department: string;
|
||||
position: string; // 직책
|
||||
rank: string; // 직급
|
||||
startDate: string; // 휴가기간 시작
|
||||
endDate: string; // 휴가기간 종료
|
||||
vacationDays: number; // 휴가일수
|
||||
status: RequestStatus; // 상태
|
||||
requestDate: string; // 신청일
|
||||
vacationType?: VacationType;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ===== 폼 데이터 =====
|
||||
export interface VacationFormData {
|
||||
employeeId: string;
|
||||
vacationType: VacationType;
|
||||
days: number;
|
||||
memo?: string;
|
||||
}
|
||||
|
||||
export interface VacationGrantFormData {
|
||||
employeeId: string;
|
||||
vacationType: VacationType;
|
||||
grantDays: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface VacationRequestFormData {
|
||||
employeeId: string;
|
||||
vacationType: VacationType;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
vacationDays: number;
|
||||
}
|
||||
|
||||
export interface VacationAdjustment {
|
||||
vacationType: VacationType;
|
||||
adjustment: number;
|
||||
}
|
||||
|
||||
export interface VacationTypeConfig {
|
||||
id: string;
|
||||
name: string;
|
||||
type: VacationType;
|
||||
isActive: boolean;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface EmployeeOption {
|
||||
id: string;
|
||||
name: string;
|
||||
department: string;
|
||||
position: string;
|
||||
rank: string;
|
||||
}
|
||||
|
||||
// ===== 상수 정의 =====
|
||||
|
||||
export const MAIN_TAB_LABELS: Record<MainTabType, string> = {
|
||||
usage: '휴가 사용현황',
|
||||
grant: '휴가 부여현황',
|
||||
request: '휴가 신청현황',
|
||||
};
|
||||
|
||||
export const VACATION_TYPE_LABELS: Record<VacationType, string> = {
|
||||
annual: '연차',
|
||||
monthly: '월차',
|
||||
reward: '포상휴가',
|
||||
other: '기타',
|
||||
};
|
||||
|
||||
export const VACATION_TYPE_COLORS: Record<VacationType, string> = {
|
||||
annual: 'blue',
|
||||
monthly: 'green',
|
||||
reward: 'purple',
|
||||
other: 'orange',
|
||||
};
|
||||
|
||||
export const REQUEST_STATUS_LABELS: Record<RequestStatus, string> = {
|
||||
pending: '대기',
|
||||
approved: '승인',
|
||||
rejected: '반려',
|
||||
};
|
||||
|
||||
export const REQUEST_STATUS_COLORS: Record<RequestStatus, string> = {
|
||||
pending: 'bg-yellow-100 text-yellow-800',
|
||||
approved: 'bg-green-100 text-green-800',
|
||||
rejected: 'bg-red-100 text-red-800',
|
||||
};
|
||||
|
||||
export const SORT_OPTIONS: Record<SortOption, string> = {
|
||||
rank: '직급순',
|
||||
deptAsc: '부서명 오름차순',
|
||||
deptDesc: '부서명 내림차순',
|
||||
nameAsc: '이름 오름차순',
|
||||
nameDesc: '이름 내림차순',
|
||||
};
|
||||
|
||||
export const DEFAULT_VACATION_TYPES: VacationTypeConfig[] = [
|
||||
{ id: '1', name: '연차', type: 'annual', isActive: true, description: '연간 유급 휴가' },
|
||||
{ id: '2', name: '월차', type: 'monthly', isActive: true, description: '월간 유급 휴가' },
|
||||
{ id: '3', name: '포상휴가', type: 'reward', isActive: true, description: '성과에 따른 포상 휴가' },
|
||||
{ id: '4', name: '기타', type: 'other', isActive: true, description: '기타 휴가' },
|
||||
];
|
||||
@@ -136,9 +136,12 @@ export function DrawingCanvas({
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return { x: 0, y: 0 };
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
// 실제 캔버스 크기와 표시 크기의 비율 계산
|
||||
const scaleX = canvas.width / rect.width;
|
||||
const scaleY = canvas.height / rect.height;
|
||||
return {
|
||||
x: e.clientX - rect.left,
|
||||
y: e.clientY - rect.top,
|
||||
x: (e.clientX - rect.left) * scaleX,
|
||||
y: (e.clientY - rect.top) * scaleY,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -80,22 +80,6 @@ export function DropdownField({
|
||||
// 옵션이 없으면 드롭다운을 disabled로 표시
|
||||
const hasOptions = options.length > 0;
|
||||
|
||||
// 디버깅: 단위 필드 값 추적
|
||||
if (isUnitField) {
|
||||
console.log('[DropdownField] 단위 필드 디버깅:', {
|
||||
fieldKey,
|
||||
fieldName: field.field_name,
|
||||
rawValue: value,
|
||||
stringValue,
|
||||
isUnitField,
|
||||
unitOptionsCount: unitOptions?.length || 0,
|
||||
unitOptions: unitOptions?.slice(0, 3), // 처음 3개만
|
||||
optionsCount: options.length,
|
||||
options: options.slice(0, 3), // 처음 3개만
|
||||
valueInOptions: options.some(o => o.value === stringValue),
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Label htmlFor={fieldKey}>
|
||||
|
||||
@@ -72,17 +72,6 @@ export function useConditionalDisplay(
|
||||
}
|
||||
});
|
||||
|
||||
// 디버깅: 조건부 표시 설정 확인
|
||||
console.log('[useConditionalDisplay] 트리거 필드 목록:', triggers.map(t => ({
|
||||
fieldKey: t.fieldKey,
|
||||
fieldId: t.fieldId,
|
||||
fieldConditions: t.condition.fieldConditions?.map(fc => ({
|
||||
expectedValue: fc.expectedValue,
|
||||
targetFieldIds: fc.targetFieldIds,
|
||||
targetSectionIds: fc.targetSectionIds,
|
||||
})),
|
||||
})));
|
||||
|
||||
return triggers;
|
||||
}, [structure]);
|
||||
|
||||
@@ -102,15 +91,6 @@ export function useConditionalDisplay(
|
||||
// 현재 값과 기대값이 일치하는지 확인
|
||||
const isMatch = String(currentValue) === fc.expectedValue;
|
||||
|
||||
// 디버깅: 조건 매칭 확인
|
||||
console.log('[useConditionalDisplay] 조건 매칭 체크:', {
|
||||
triggerFieldKey: trigger.fieldKey,
|
||||
currentValue: String(currentValue),
|
||||
expectedValue: fc.expectedValue,
|
||||
isMatch,
|
||||
targetFieldIds: fc.targetFieldIds,
|
||||
});
|
||||
|
||||
if (isMatch) {
|
||||
// 일치하면 타겟 섹션/필드 활성화
|
||||
if (fc.targetSectionIds) {
|
||||
@@ -124,8 +104,6 @@ export function useConditionalDisplay(
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[useConditionalDisplay] 활성화된 필드 ID:', [...activeFieldIds]);
|
||||
|
||||
return { activeSectionIds, activeFieldIds };
|
||||
}, [triggerFields, formData]);
|
||||
|
||||
|
||||
@@ -178,7 +178,6 @@ export function useDynamicFormState(
|
||||
|
||||
// 폼 초기화
|
||||
const resetForm = useCallback((newInitialData?: DynamicFormData) => {
|
||||
console.log('[useDynamicFormState] resetForm 호출됨:', newInitialData);
|
||||
setFormData(newInitialData || {});
|
||||
setErrors({});
|
||||
setIsSubmitting(false);
|
||||
|
||||
@@ -398,127 +398,38 @@ export default function DynamicItemForm({
|
||||
}
|
||||
}, [selectedItemType, structure, mode, resetForm]);
|
||||
|
||||
// Edit 모드: structure 로드 후 initialData를 field_key 형식으로 변환
|
||||
// 2025-12-04: initialData 키(item_name)와 structure의 field_key(98_item_name)가 다른 문제 해결
|
||||
// Edit 모드: initialData를 폼에 직접 로드
|
||||
// 2025-12-09: field_key 통일로 복잡한 매핑 로직 제거
|
||||
// 백엔드에서 field_key 그대로 응답하므로 직접 사용 가능
|
||||
const [isEditDataMapped, setIsEditDataMapped] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode !== 'edit' || !structure || !initialData) return;
|
||||
console.log('[DynamicItemForm] Edit useEffect 체크:', {
|
||||
mode,
|
||||
hasStructure: !!structure,
|
||||
hasInitialData: !!initialData,
|
||||
isEditDataMapped,
|
||||
structureSections: structure?.sections?.length,
|
||||
});
|
||||
|
||||
// 이미 매핑된 데이터가 formData에 있으면 스킵 (98_unit 같은 field_key 형식)
|
||||
// StrictMode 리렌더에서도 안전하게 동작
|
||||
const hasFieldKeyData = Object.keys(formData).some(key => /^\d+_/.test(key));
|
||||
if (hasFieldKeyData) {
|
||||
console.log('[DynamicItemForm] Edit mode: 이미 field_key 형식 데이터 있음, 매핑 스킵');
|
||||
return;
|
||||
}
|
||||
if (mode !== 'edit' || !structure || !initialData || isEditDataMapped) return;
|
||||
|
||||
console.log('[DynamicItemForm] Edit mode: mapping initialData to field_key format');
|
||||
console.log('[DynamicItemForm] Edit mode: initialData 직접 로드 (field_key 통일됨)');
|
||||
console.log('[DynamicItemForm] initialData:', initialData);
|
||||
|
||||
// initialData의 간단한 키를 structure의 field_key로 매핑
|
||||
// 예: { item_name: '테스트' } → { '98_item_name': '테스트' }
|
||||
const mappedData: DynamicFormData = {};
|
||||
|
||||
// field_key에서 실제 필드명 추출하는 함수
|
||||
// 예: '98_item_name' → 'item_name', '110_품목명' → '품목명'
|
||||
const extractFieldName = (fieldKey: string): string => {
|
||||
const underscoreIndex = fieldKey.indexOf('_');
|
||||
if (underscoreIndex > 0) {
|
||||
return fieldKey.substring(underscoreIndex + 1);
|
||||
}
|
||||
return fieldKey;
|
||||
};
|
||||
|
||||
// structure에서 모든 필드의 field_key 수집
|
||||
const fieldKeyMap: Record<string, string> = {}; // 간단한 키 → field_key 매핑
|
||||
|
||||
// 영문 → 한글 필드명 별칭 (API 응답 키 → structure field_name 매핑)
|
||||
// API는 영문 키(unit, note)로 응답하지만, structure field_key는 한글(단위, 비고) 포함
|
||||
const fieldAliases: Record<string, string> = {
|
||||
'unit': '단위',
|
||||
'note': '비고',
|
||||
'remarks': '비고', // Material 모델은 remarks 사용
|
||||
'item_name': '품목명',
|
||||
'specification': '규격',
|
||||
'description': '설명',
|
||||
};
|
||||
|
||||
// structure의 field_key들 확인
|
||||
const fieldKeys: string[] = [];
|
||||
structure.sections.forEach((section) => {
|
||||
section.fields.forEach((f) => {
|
||||
const field = f.field;
|
||||
const fieldKey = field.field_key || `field_${field.id}`;
|
||||
const simpleName = extractFieldName(fieldKey);
|
||||
fieldKeyMap[simpleName] = fieldKey;
|
||||
|
||||
// field_name도 매핑에 추가 (한글 필드명 지원)
|
||||
if (field.field_name) {
|
||||
fieldKeyMap[field.field_name] = fieldKey;
|
||||
}
|
||||
fieldKeys.push(f.field.field_key || `field_${f.field.id}`);
|
||||
});
|
||||
});
|
||||
console.log('[DynamicItemForm] structure field_keys:', fieldKeys);
|
||||
console.log('[DynamicItemForm] initialData keys:', Object.keys(initialData));
|
||||
|
||||
structure.directFields.forEach((f) => {
|
||||
const field = f.field;
|
||||
const fieldKey = field.field_key || `field_${field.id}`;
|
||||
const simpleName = extractFieldName(fieldKey);
|
||||
fieldKeyMap[simpleName] = fieldKey;
|
||||
|
||||
if (field.field_name) {
|
||||
fieldKeyMap[field.field_name] = fieldKey;
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[DynamicItemForm] fieldKeyMap:', fieldKeyMap);
|
||||
|
||||
// initialData를 field_key 형식으로 변환
|
||||
Object.entries(initialData).forEach(([key, value]) => {
|
||||
// 이미 field_key 형식인 경우 그대로 사용
|
||||
if (key.includes('_') && /^\d+_/.test(key)) {
|
||||
mappedData[key] = value;
|
||||
}
|
||||
// 간단한 키인 경우 field_key로 변환
|
||||
else if (fieldKeyMap[key]) {
|
||||
mappedData[fieldKeyMap[key]] = value;
|
||||
}
|
||||
// 영문 → 한글 별칭으로 시도 (API 응답 키 → structure field_name)
|
||||
else if (fieldAliases[key] && fieldKeyMap[fieldAliases[key]]) {
|
||||
mappedData[fieldKeyMap[fieldAliases[key]]] = value;
|
||||
console.log(`[DynamicItemForm] 별칭 매핑: ${key} → ${fieldAliases[key]} → ${fieldKeyMap[fieldAliases[key]]}`);
|
||||
}
|
||||
// 매핑 없는 경우 그대로 유지
|
||||
else {
|
||||
mappedData[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
// 추가: 폼 구조의 모든 필드를 순회하면서, initialData에서 해당 값 직접 찾아서 설정
|
||||
// (fieldKeyMap에 매핑이 없는 경우를 위한 fallback)
|
||||
Object.entries(fieldKeyMap).forEach(([simpleName, fieldKey]) => {
|
||||
// 아직 매핑 안된 필드인데 initialData에 값이 있으면 설정
|
||||
if (mappedData[fieldKey] === undefined && initialData[simpleName] !== undefined) {
|
||||
mappedData[fieldKey] = initialData[simpleName];
|
||||
}
|
||||
});
|
||||
|
||||
// 추가: 영문 별칭을 역으로 검색하여 매핑 (한글 field_name → 영문 API 키)
|
||||
// 예: fieldKeyMap에 '단위'가 있고, initialData에 'unit'이 있으면 매핑
|
||||
Object.entries(fieldAliases).forEach(([englishKey, koreanKey]) => {
|
||||
const targetFieldKey = fieldKeyMap[koreanKey];
|
||||
if (targetFieldKey && mappedData[targetFieldKey] === undefined && initialData[englishKey] !== undefined) {
|
||||
mappedData[targetFieldKey] = initialData[englishKey];
|
||||
console.log(`[DynamicItemForm] 별칭 fallback 매핑: ${englishKey} → ${koreanKey} → ${targetFieldKey}`);
|
||||
}
|
||||
});
|
||||
|
||||
console.log('========== [DynamicItemForm] Edit 모드 데이터 매핑 ==========');
|
||||
console.log('specification 관련 키:', Object.keys(mappedData).filter(k => k.includes('specification') || k.includes('규격')));
|
||||
console.log('is_active 관련 키:', Object.keys(mappedData).filter(k => k.includes('active') || k.includes('상태')));
|
||||
console.log('매핑된 데이터:', mappedData);
|
||||
console.log('==============================================================');
|
||||
|
||||
// 변환된 데이터로 폼 리셋
|
||||
resetForm(mappedData);
|
||||
// field_key가 통일되었으므로 initialData를 그대로 사용
|
||||
// 기존 레거시 데이터(98_unit 형식)도 그대로 동작
|
||||
resetForm(initialData);
|
||||
setIsEditDataMapped(true);
|
||||
}, [mode, structure, initialData, isEditDataMapped, resetForm]);
|
||||
|
||||
@@ -1202,82 +1113,22 @@ export default function DynamicItemForm({
|
||||
return;
|
||||
}
|
||||
|
||||
// field_key → 백엔드 필드명 매핑
|
||||
// field_key 형식: "{id}_{key}" (예: "98_item_name", "110_품목명")
|
||||
// 백엔드 필드명으로 변환 필요
|
||||
// 2025-12-03: 한글 field_key 지원 추가
|
||||
const fieldKeyToBackendKey: Record<string, string> = {
|
||||
'item_name': 'name',
|
||||
'productName': 'name', // FG(제품) 품목명 필드
|
||||
'품목명': 'name', // 한글 field_key 지원
|
||||
'specification': 'spec',
|
||||
'standard': 'spec', // 규격 대체 필드명
|
||||
'규격': 'spec', // 한글 field_key 지원
|
||||
'사양': 'spec', // 한글 대체
|
||||
'unit': 'unit',
|
||||
'단위': 'unit', // 한글 field_key 지원
|
||||
'note': 'note',
|
||||
'비고': 'note', // 한글 field_key 지원
|
||||
'description': 'description',
|
||||
'설명': 'description', // 한글 field_key 지원
|
||||
'part_type': 'part_type',
|
||||
'부품유형': 'part_type', // 한글 field_key 지원
|
||||
'부품 유형': 'part_type', // 공백 포함 한글
|
||||
'is_active': 'is_active',
|
||||
'status': 'is_active',
|
||||
'active': 'is_active',
|
||||
'품목상태': 'is_active', // 한글 field_key 지원
|
||||
'품목 상태': 'is_active', // 공백 포함 한글
|
||||
'상태': 'is_active', // 짧은 한글
|
||||
};
|
||||
// 2025-12-09: field_key 통일로 변환 로직 제거
|
||||
// formData의 field_key가 백엔드 필드명과 일치하므로 직접 사용
|
||||
console.log('[DynamicItemForm] 저장 시 formData:', formData);
|
||||
|
||||
// formData를 백엔드 필드명으로 변환
|
||||
console.log('========== [DynamicItemForm] 저장 시 formData ==========');
|
||||
console.log('specification 관련:', Object.entries(formData).filter(([k]) => k.includes('specification') || k.includes('규격')));
|
||||
console.log('is_active 관련:', Object.entries(formData).filter(([k]) => k.includes('active') || k.includes('상태')));
|
||||
console.log('전체 formData:', formData);
|
||||
console.log('=========================================================');
|
||||
// is_active 필드만 boolean 변환 (드롭다운 값 → boolean)
|
||||
const convertedData: Record<string, any> = {};
|
||||
Object.entries(formData).forEach(([key, value]) => {
|
||||
// "{id}_{fieldKey}" 형식 체크: 숫자로 시작하고 _가 있는 경우
|
||||
// 예: "98_item_name" → true, "item_name" → false
|
||||
const isFieldKeyFormat = /^\d+_/.test(key);
|
||||
|
||||
if (isFieldKeyFormat) {
|
||||
// "{id}_{fieldKey}" 형식에서 fieldKey 추출
|
||||
const underscoreIndex = key.indexOf('_');
|
||||
const fieldKey = key.substring(underscoreIndex + 1);
|
||||
const backendKey = fieldKeyToBackendKey[fieldKey] || fieldKey;
|
||||
|
||||
// is_active 필드는 boolean으로 변환
|
||||
if (backendKey === 'is_active') {
|
||||
// "활성", true, "true", "1", 1 등을 true로, 나머지는 false로
|
||||
const isActive = value === true || value === 'true' || value === '1' ||
|
||||
value === 1 || value === '활성' || value === 'active';
|
||||
console.log(`[DynamicItemForm] is_active 변환: key=${key}, value=${value}(${typeof value}) → isActive=${isActive}`);
|
||||
convertedData[backendKey] = isActive;
|
||||
} else {
|
||||
convertedData[backendKey] = value;
|
||||
}
|
||||
if (key === 'is_active' || key.endsWith('_is_active')) {
|
||||
// "활성", true, "true", "1", 1 등을 true로, 나머지는 false로
|
||||
const isActive = value === true || value === 'true' || value === '1' ||
|
||||
value === 1 || value === '활성' || value === 'active';
|
||||
convertedData[key] = isActive;
|
||||
} else {
|
||||
// field_key 형식이 아닌 경우, 매핑 테이블에서 변환 시도
|
||||
const backendKey = fieldKeyToBackendKey[key] || key;
|
||||
|
||||
if (backendKey === 'is_active') {
|
||||
const isActive = value === true || value === 'true' || value === '1' ||
|
||||
value === 1 || value === '활성' || value === 'active';
|
||||
console.log(`[DynamicItemForm] is_active 변환 (non-field_key): key=${key}, value=${value}(${typeof value}) → isActive=${isActive}`);
|
||||
convertedData[backendKey] = isActive;
|
||||
} else {
|
||||
convertedData[backendKey] = value;
|
||||
}
|
||||
convertedData[key] = value;
|
||||
}
|
||||
});
|
||||
console.log('========== [DynamicItemForm] convertedData 결과 ==========');
|
||||
console.log('is_active:', convertedData.is_active);
|
||||
console.log('specification:', convertedData.spec || convertedData.specification);
|
||||
console.log('전체:', convertedData);
|
||||
console.log('===========================================================');
|
||||
|
||||
// 품목명 값 추출 (품목코드와 품목명 모두 필요)
|
||||
// 2025-12-04: 절곡 부품은 별도 품목명 필드(bendingFieldKeys.itemName) 사용
|
||||
@@ -1333,7 +1184,8 @@ export default function DynamicItemForm({
|
||||
}
|
||||
|
||||
// 품목 유형 및 BOM 데이터 추가
|
||||
const submitData: DynamicFormData = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const submitData = {
|
||||
...convertedData,
|
||||
// 백엔드 필드명 사용
|
||||
product_type: selectedItemType, // item_type → product_type
|
||||
@@ -1373,7 +1225,7 @@ export default function DynamicItemForm({
|
||||
...(selectedItemType === 'FG' && !convertedData.unit ? {
|
||||
unit: 'EA',
|
||||
} : {}),
|
||||
};
|
||||
} as DynamicFormData;
|
||||
|
||||
// console.log('[DynamicItemForm] 제출 데이터:', submitData);
|
||||
|
||||
@@ -1392,9 +1244,9 @@ export default function DynamicItemForm({
|
||||
console.log('[DynamicItemForm] 전개도 파일 업로드 시작:', bendingDiagramFile.name);
|
||||
await uploadItemFile(itemId, bendingDiagramFile, 'bending_diagram', {
|
||||
bendingDetails: bendingDetails.length > 0 ? bendingDetails.map(d => ({
|
||||
angle: d.angle || 0,
|
||||
length: d.width || 0,
|
||||
type: d.direction || '',
|
||||
angle: d.aAngle || 0,
|
||||
length: d.input || 0,
|
||||
type: d.shaded ? 'shaded' : 'normal',
|
||||
})) : undefined,
|
||||
});
|
||||
console.log('[DynamicItemForm] 전개도 파일 업로드 성공');
|
||||
@@ -1924,6 +1776,25 @@ export default function DynamicItemForm({
|
||||
onOpenChange={setIsDrawingOpen}
|
||||
onSave={(imageData) => {
|
||||
setBendingDiagram(imageData);
|
||||
|
||||
// Base64 string을 File 객체로 변환 (업로드용)
|
||||
// 2025-12-06: 드로잉 방식에서도 파일 업로드 지원
|
||||
try {
|
||||
const byteString = atob(imageData.split(',')[1]);
|
||||
const mimeType = imageData.split(',')[0].split(':')[1].split(';')[0];
|
||||
const arrayBuffer = new ArrayBuffer(byteString.length);
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
for (let i = 0; i < byteString.length; i++) {
|
||||
uint8Array[i] = byteString.charCodeAt(i);
|
||||
}
|
||||
const blob = new Blob([uint8Array], { type: mimeType });
|
||||
const file = new File([blob], `bending_diagram_${Date.now()}.png`, { type: mimeType });
|
||||
setBendingDiagramFile(file);
|
||||
console.log('[DynamicItemForm] 드로잉 캔버스 → File 변환 성공:', file.name);
|
||||
} catch (error) {
|
||||
console.error('[DynamicItemForm] 드로잉 캔버스 → File 변환 실패:', error);
|
||||
}
|
||||
|
||||
setIsDrawingOpen(false);
|
||||
}}
|
||||
initialImage={bendingDiagram}
|
||||
|
||||
@@ -118,7 +118,7 @@ export interface BOMSearchState {
|
||||
/**
|
||||
* 동적 폼 필드 값 타입
|
||||
*/
|
||||
export type DynamicFieldValue = string | number | boolean | null | undefined | Record<string, unknown>[] | Record<string, unknown>;
|
||||
export type DynamicFieldValue = string | number | boolean | string[] | null | undefined | Record<string, unknown>[] | Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* 동적 폼 데이터 (field_key를 key로 사용)
|
||||
|
||||
@@ -256,23 +256,20 @@ export default function ItemDetailClient({ item }: ItemDetailClientProps) {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{item.category1 && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">품목명</Label>
|
||||
<p className="mt-1">
|
||||
<Badge variant="outline" className="bg-indigo-50 text-indigo-700">
|
||||
{item.category1 === 'guide_rail' ? '가이드레일' :
|
||||
item.category1 === 'case' ? '케이스' :
|
||||
item.category1 === 'bottom_finish' ? '하단마감재' :
|
||||
item.category1}
|
||||
</Badge>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{item.installationType && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">설치 유형</Label>
|
||||
<p className="mt-1">
|
||||
{/* 품목명 - itemName 표시 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">품목명</Label>
|
||||
<p className="mt-1">
|
||||
<Badge variant="outline" className="bg-indigo-50 text-indigo-700">
|
||||
{item.itemName}
|
||||
</Badge>
|
||||
</p>
|
||||
</div>
|
||||
{/* 설치 유형 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">설치 유형</Label>
|
||||
<p className="mt-1">
|
||||
{item.installationType ? (
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700">
|
||||
{item.installationType === 'wall' ? '벽면형 (R)' :
|
||||
item.installationType === 'side' ? '측면형 (S)' :
|
||||
@@ -280,19 +277,41 @@ export default function ItemDetailClient({ item }: ItemDetailClientProps) {
|
||||
item.installationType === 'iron' ? '철재 (T)' :
|
||||
item.installationType}
|
||||
</Badge>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{item.assemblyType && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">마감</Label>
|
||||
<p className="mt-1">
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
{/* 마감 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">마감</Label>
|
||||
<p className="mt-1">
|
||||
{item.assemblyType ? (
|
||||
<code className="text-sm bg-gray-100 px-2 py-1 rounded">
|
||||
{item.assemblyType}
|
||||
</code>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
{/* 길이 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">길이</Label>
|
||||
<p className="mt-1 font-medium">
|
||||
{item.assemblyLength || item.length ? `${item.assemblyLength || item.length}mm` : '-'}
|
||||
</p>
|
||||
</div>
|
||||
{/* 측면 규격 */}
|
||||
<div>
|
||||
<Label className="text-muted-foreground">측면 규격</Label>
|
||||
<p className="mt-1">
|
||||
{item.sideSpecWidth && item.sideSpecHeight
|
||||
? `${item.sideSpecWidth} × ${item.sideSpecHeight}mm`
|
||||
: '-'}
|
||||
</p>
|
||||
</div>
|
||||
{/* 재질 (있으면) */}
|
||||
{item.material && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">재질</Label>
|
||||
@@ -303,20 +322,6 @@ export default function ItemDetailClient({ item }: ItemDetailClientProps) {
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{item.assemblyLength && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">길이</Label>
|
||||
<p className="mt-1 font-medium">{item.assemblyLength}mm</p>
|
||||
</div>
|
||||
)}
|
||||
{item.sideSpecWidth && item.sideSpecHeight && (
|
||||
<div>
|
||||
<Label className="text-muted-foreground">측면 규격</Label>
|
||||
<p className="mt-1">
|
||||
{item.sideSpecWidth} × {item.sideSpecHeight}mm
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -355,10 +360,9 @@ export default function ItemDetailClient({ item }: ItemDetailClientProps) {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 절곡품/조립품 전개도 정보 */}
|
||||
{/* 절곡품/조립품 전개도 정보 - 조립부품은 항상 표시 */}
|
||||
{item.itemType === 'PT' &&
|
||||
(item.partType === 'BENDING' || item.partType === 'ASSEMBLY') &&
|
||||
(item.bendingDiagram || (item.bendingDetails && item.bendingDetails.length > 0)) && (
|
||||
(item.partType === 'BENDING' || item.partType === 'ASSEMBLY') && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="flex items-center gap-2 text-base md:text-lg">
|
||||
|
||||
@@ -172,7 +172,7 @@ export default function PartForm({
|
||||
value={selectedPartType}
|
||||
onValueChange={handlePartTypeChange}
|
||||
>
|
||||
<SelectTrigger className={errors.partType ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).partType ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="부품 유형을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -181,12 +181,12 @@ export default function PartForm({
|
||||
<SelectItem value="PURCHASED">구매 부품 (Purchased Part)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.partType && (
|
||||
{(errors as any).partType && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.partType.message}
|
||||
{(errors as any).partType.message}
|
||||
</p>
|
||||
)}
|
||||
{!errors.partType && selectedPartType === 'BENDING' && (
|
||||
{!(errors as any).partType && selectedPartType === 'BENDING' && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
* 절곡 부품은 전개도(바라시)만 있으며, 부품 구성(BOM)은 사용하지 않습니다.
|
||||
</p>
|
||||
|
||||
@@ -18,6 +18,11 @@ import { X } from 'lucide-react';
|
||||
import type { UseFormRegister, UseFormSetValue, UseFormGetValues, FieldErrors } from 'react-hook-form';
|
||||
import type { CreateItemFormData } from '@/lib/utils/validation';
|
||||
|
||||
// ProductForm에서 사용하는 확장 타입 (productName 포함)
|
||||
type ProductFormErrors = FieldErrors<CreateItemFormData> & {
|
||||
productName?: { message?: string };
|
||||
};
|
||||
|
||||
interface ProductFormProps {
|
||||
productName: string;
|
||||
setProductName: (value: string) => void;
|
||||
@@ -35,7 +40,7 @@ interface ProductFormProps {
|
||||
register: UseFormRegister<CreateItemFormData>;
|
||||
setValue: UseFormSetValue<CreateItemFormData>;
|
||||
getValues: UseFormGetValues<CreateItemFormData>;
|
||||
errors: FieldErrors<CreateItemFormData>;
|
||||
errors: ProductFormErrors;
|
||||
}
|
||||
|
||||
export default function ProductForm({
|
||||
|
||||
@@ -134,7 +134,7 @@ export default function BendingPartForm({
|
||||
setValue('material', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.material ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).material ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="재질을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -144,9 +144,9 @@ export default function BendingPartForm({
|
||||
<SelectItem value="SUS 1.5T">SUS 1.5T</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.material && (
|
||||
{(errors as any).material && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.material.message}
|
||||
{(errors as any).material.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -165,16 +165,16 @@ export default function BendingPartForm({
|
||||
}}
|
||||
placeholder="전개도 상세를 입력해주세요"
|
||||
readOnly={bendingDetailsLength > 0}
|
||||
className={`${bendingDetailsLength > 0 ? "bg-blue-50 font-medium" : ""} ${errors.length ? 'border-red-500' : ''}`}
|
||||
className={`${bendingDetailsLength > 0 ? "bg-blue-50 font-medium" : ""} ${(errors as any).length ? 'border-red-500' : ''}`}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">mm</span>
|
||||
</div>
|
||||
{errors.length && (
|
||||
{(errors as any).length && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.length.message}
|
||||
{(errors as any).length.message}
|
||||
</p>
|
||||
)}
|
||||
{!errors.length && bendingDetailsLength > 0 && (
|
||||
{!(errors as any).length && bendingDetailsLength > 0 && (
|
||||
<p className="text-xs text-blue-600 mt-1">
|
||||
* 전개도 상세 입력의 합계가 자동 반영됩니다
|
||||
</p>
|
||||
@@ -192,7 +192,7 @@ export default function BendingPartForm({
|
||||
setValue('bendingLength', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.bendingLength ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).bendingLength ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="모양&길이를 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -210,9 +210,9 @@ export default function BendingPartForm({
|
||||
<SelectItem value="4300">4300mm</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.bendingLength && (
|
||||
{(errors as any).bendingLength && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.bendingLength.message}
|
||||
{(errors as any).bendingLength.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -119,7 +119,7 @@ export default function PurchasedPartForm({
|
||||
setValue('electricOpenerPower', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.electricOpenerPower ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).electricOpenerPower ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="전원을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -127,9 +127,9 @@ export default function PurchasedPartForm({
|
||||
<SelectItem value="380V">380V</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.electricOpenerPower && (
|
||||
{(errors as any).electricOpenerPower && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.electricOpenerPower.message}
|
||||
{(errors as any).electricOpenerPower.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -144,7 +144,7 @@ export default function PurchasedPartForm({
|
||||
setValue('electricOpenerCapacity', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.electricOpenerCapacity ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).electricOpenerCapacity ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="용량을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -157,9 +157,9 @@ export default function PurchasedPartForm({
|
||||
<SelectItem value="1000">1000 KG</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.electricOpenerCapacity && (
|
||||
{(errors as any).electricOpenerCapacity && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.electricOpenerCapacity.message}
|
||||
{(errors as any).electricOpenerCapacity.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -182,7 +182,7 @@ export default function PurchasedPartForm({
|
||||
setValue('motorVoltage', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.motorVoltage ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).motorVoltage ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="전압을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -190,9 +190,9 @@ export default function PurchasedPartForm({
|
||||
<SelectItem value="380">380V</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.motorVoltage && (
|
||||
{(errors as any).motorVoltage && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.motorVoltage.message}
|
||||
{(errors as any).motorVoltage.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -211,7 +211,7 @@ export default function PurchasedPartForm({
|
||||
setValue('chainSpec', value);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className={errors.chainSpec ? 'border-red-500' : ''}>
|
||||
<SelectTrigger className={(errors as any).chainSpec ? 'border-red-500' : ''}>
|
||||
<SelectValue placeholder="규격을 선택하세요" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -221,9 +221,9 @@ export default function PurchasedPartForm({
|
||||
<SelectItem value="80">80</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{errors.chainSpec && (
|
||||
{(errors as any).chainSpec && (
|
||||
<p className="text-xs text-red-500 mt-1">
|
||||
{errors.chainSpec.message}
|
||||
{(errors as any).chainSpec.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -194,7 +194,6 @@ export default function ItemListClient() {
|
||||
console.log('[Delete] 응답:', { status: response.status, result });
|
||||
|
||||
if (response.ok && result.success) {
|
||||
alert('품목이 삭제되었습니다.');
|
||||
refresh();
|
||||
} else {
|
||||
throw new Error(result.message || '삭제에 실패했습니다.');
|
||||
|
||||
@@ -62,7 +62,7 @@ export interface Column<T> {
|
||||
format?: (value: any) => string | number;
|
||||
}
|
||||
|
||||
interface DataTableProps<T> {
|
||||
interface DataTableProps<T extends object> {
|
||||
columns: Column<T>[];
|
||||
data: T[];
|
||||
keyField: keyof T;
|
||||
@@ -203,7 +203,7 @@ function getAlignClass(column: Column<any>): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function DataTable<T>({
|
||||
export function DataTable<T extends object>({
|
||||
columns,
|
||||
data,
|
||||
keyField,
|
||||
|
||||
@@ -20,7 +20,7 @@ export function PageLayout({ children, maxWidth = "full", versionInfo }: PageLay
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`p-4 md:p-6 space-y-4 md:space-y-6 ${maxWidthClasses[maxWidth]} mx-auto w-full relative`}>
|
||||
<div className={`p-3 md:p-6 pb-0 space-y-3 md:space-y-6 flex flex-col ${maxWidthClasses[maxWidth]} mx-auto w-full relative`}>
|
||||
{versionInfo && (
|
||||
<div className="absolute top-4 right-4 z-10">
|
||||
{versionInfo}
|
||||
|
||||
@@ -65,6 +65,7 @@ interface PricingFormClientProps {
|
||||
itemInfo?: ItemInfo;
|
||||
initialData?: PricingData;
|
||||
onSave?: (data: PricingData, isRevision?: boolean, revisionReason?: string) => Promise<void>;
|
||||
onFinalize?: (id: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function PricingFormClient({
|
||||
@@ -72,6 +73,7 @@ export function PricingFormClient({
|
||||
itemInfo,
|
||||
initialData,
|
||||
onSave,
|
||||
onFinalize,
|
||||
}: PricingFormClientProps) {
|
||||
const router = useRouter();
|
||||
const isEditMode = mode === 'edit';
|
||||
@@ -264,30 +266,9 @@ export function PricingFormClient({
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const finalizedData: PricingData = {
|
||||
...initialData,
|
||||
effectiveDate,
|
||||
receiveDate: receiveDate || undefined,
|
||||
author: author || undefined,
|
||||
purchasePrice: purchasePrice || undefined,
|
||||
processingCost: processingCost || undefined,
|
||||
loss: loss || undefined,
|
||||
roundingRule: roundingRule || undefined,
|
||||
roundingUnit: roundingUnit || undefined,
|
||||
marginRate: marginRate || undefined,
|
||||
salesPrice: salesPrice || undefined,
|
||||
supplier: supplier || undefined,
|
||||
note: note || undefined,
|
||||
isFinal: true,
|
||||
finalizedDate: new Date().toISOString(),
|
||||
finalizedBy: '관리자',
|
||||
status: 'finalized',
|
||||
updatedAt: new Date().toISOString(),
|
||||
updatedBy: '관리자',
|
||||
};
|
||||
|
||||
if (onSave) {
|
||||
await onSave(finalizedData);
|
||||
if (onFinalize) {
|
||||
// 서버 액션으로 확정 처리
|
||||
await onFinalize(initialData.id);
|
||||
}
|
||||
|
||||
toast.success('단가가 최종 확정되었습니다.');
|
||||
@@ -295,6 +276,7 @@ export function PricingFormClient({
|
||||
router.push('/sales/pricing-management');
|
||||
} catch (error) {
|
||||
toast.error('확정 중 오류가 발생했습니다.');
|
||||
console.error(error);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
|
||||
@@ -153,7 +153,9 @@ export function PricingListClient({
|
||||
|
||||
// 네비게이션 핸들러
|
||||
const handleRegister = (item: PricingListItem) => {
|
||||
router.push(`/sales/pricing-management/create?itemId=${item.itemId}&itemCode=${item.itemCode}`);
|
||||
// itemTypeCode를 URL 파라미터에 포함 (PRODUCT 또는 MATERIAL)
|
||||
const itemTypeCode = item.itemTypeCode || 'MATERIAL';
|
||||
router.push(`/sales/pricing-management/create?itemId=${item.itemId}&itemCode=${item.itemCode}&itemTypeCode=${itemTypeCode}`);
|
||||
};
|
||||
|
||||
const handleEdit = (item: PricingListItem) => {
|
||||
@@ -414,7 +416,7 @@ export function PricingListClient({
|
||||
|
||||
return (
|
||||
<IntegratedListTemplateV2<PricingListItem>
|
||||
title="단가 관리"
|
||||
title="단가 목록"
|
||||
description="품목별 매입단가, 판매단가 및 마진을 관리합니다"
|
||||
icon={DollarSign}
|
||||
headerActions={headerActions}
|
||||
|
||||
511
src/components/pricing/actions.ts
Normal file
511
src/components/pricing/actions.ts
Normal file
@@ -0,0 +1,511 @@
|
||||
/**
|
||||
* 단가관리 서버 액션
|
||||
*
|
||||
* API Endpoints:
|
||||
* - GET /api/v1/pricing - 목록 조회
|
||||
* - GET /api/v1/pricing/{id} - 상세 조회
|
||||
* - POST /api/v1/pricing - 등록
|
||||
* - PUT /api/v1/pricing/{id} - 수정
|
||||
* - DELETE /api/v1/pricing/{id} - 삭제
|
||||
* - POST /api/v1/pricing/{id}/finalize - 확정
|
||||
* - GET /api/v1/pricing/{id}/revisions - 이력 조회
|
||||
*/
|
||||
|
||||
'use server';
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
import type { PricingData, ItemInfo } from './types';
|
||||
|
||||
// API 응답 타입
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data: T;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// 단가 API 응답 데이터 타입
|
||||
interface PriceApiData {
|
||||
id: number;
|
||||
tenant_id: number;
|
||||
item_type_code: 'PRODUCT' | 'MATERIAL';
|
||||
item_id: number;
|
||||
client_group_id: number | null;
|
||||
purchase_price: string | null;
|
||||
processing_cost: string | null;
|
||||
loss_rate: string | null;
|
||||
margin_rate: string | null;
|
||||
sales_price: string | null;
|
||||
rounding_rule: 'round' | 'ceil' | 'floor';
|
||||
rounding_unit: number;
|
||||
supplier: string | null;
|
||||
effective_from: string;
|
||||
effective_to: string | null;
|
||||
status: 'draft' | 'active' | 'finalized';
|
||||
is_final: boolean;
|
||||
finalized_at: string | null;
|
||||
finalized_by: number | null;
|
||||
note: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
client_group?: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
product?: {
|
||||
id: number;
|
||||
product_code: string;
|
||||
product_name: string;
|
||||
specification: string | null;
|
||||
unit: string;
|
||||
product_type: string;
|
||||
};
|
||||
material?: {
|
||||
id: number;
|
||||
item_code: string;
|
||||
item_name: string;
|
||||
specification: string | null;
|
||||
unit: string;
|
||||
product_type: string;
|
||||
};
|
||||
revisions?: Array<{
|
||||
id: number;
|
||||
revision_number: number;
|
||||
changed_at: string;
|
||||
changed_by: number;
|
||||
change_reason: string | null;
|
||||
before_snapshot: Record<string, unknown> | null;
|
||||
after_snapshot: Record<string, unknown>;
|
||||
changed_by_user?: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* API 헤더 생성
|
||||
*/
|
||||
async function getApiHeaders(): Promise<HeadersInit> {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get('access_token')?.value;
|
||||
|
||||
return {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : '',
|
||||
'X-API-KEY': process.env.NEXT_PUBLIC_API_KEY || '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* API 데이터 → 프론트엔드 타입 변환
|
||||
*/
|
||||
function transformApiToFrontend(apiData: PriceApiData): PricingData {
|
||||
const product = apiData.product;
|
||||
const material = apiData.material;
|
||||
|
||||
const itemCode = product?.product_code || material?.item_code || `ITEM-${apiData.item_id}`;
|
||||
const itemName = product?.product_name || material?.item_name || '품목명 없음';
|
||||
const specification = product?.specification || material?.specification || undefined;
|
||||
const unit = product?.unit || material?.unit || 'EA';
|
||||
const itemType = product?.product_type || material?.product_type || 'PT';
|
||||
|
||||
// 리비전 변환
|
||||
const revisions = apiData.revisions?.map((rev) => ({
|
||||
revisionNumber: rev.revision_number,
|
||||
revisionDate: rev.changed_at,
|
||||
revisionBy: rev.changed_by_user?.name || `User ${rev.changed_by}`,
|
||||
revisionReason: rev.change_reason || undefined,
|
||||
previousData: rev.before_snapshot as unknown as PricingData,
|
||||
})) || [];
|
||||
|
||||
return {
|
||||
id: String(apiData.id),
|
||||
itemId: String(apiData.item_id),
|
||||
itemCode,
|
||||
itemName,
|
||||
itemType,
|
||||
specification,
|
||||
unit,
|
||||
effectiveDate: apiData.effective_from,
|
||||
purchasePrice: apiData.purchase_price ? parseFloat(apiData.purchase_price) : undefined,
|
||||
processingCost: apiData.processing_cost ? parseFloat(apiData.processing_cost) : undefined,
|
||||
loss: apiData.loss_rate ? parseFloat(apiData.loss_rate) : undefined,
|
||||
roundingRule: apiData.rounding_rule || 'round',
|
||||
roundingUnit: apiData.rounding_unit || 1,
|
||||
marginRate: apiData.margin_rate ? parseFloat(apiData.margin_rate) : undefined,
|
||||
salesPrice: apiData.sales_price ? parseFloat(apiData.sales_price) : undefined,
|
||||
supplier: apiData.supplier || undefined,
|
||||
note: apiData.note || undefined,
|
||||
currentRevision: revisions.length,
|
||||
isFinal: apiData.is_final,
|
||||
revisions,
|
||||
finalizedDate: apiData.finalized_at || undefined,
|
||||
status: apiData.status,
|
||||
createdAt: apiData.created_at,
|
||||
createdBy: '관리자',
|
||||
updatedAt: apiData.updated_at,
|
||||
updatedBy: '관리자',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 프론트엔드 데이터 → API 요청 형식 변환
|
||||
*/
|
||||
function transformFrontendToApi(data: PricingData, itemTypeCode: 'PRODUCT' | 'MATERIAL' = 'MATERIAL'): Record<string, unknown> {
|
||||
return {
|
||||
item_type_code: itemTypeCode,
|
||||
item_id: parseInt(data.itemId),
|
||||
purchase_price: data.purchasePrice || null,
|
||||
processing_cost: data.processingCost || null,
|
||||
loss_rate: data.loss || null,
|
||||
margin_rate: data.marginRate || null,
|
||||
sales_price: data.salesPrice || null,
|
||||
rounding_rule: data.roundingRule || 'round',
|
||||
rounding_unit: data.roundingUnit || 1,
|
||||
supplier: data.supplier || null,
|
||||
effective_from: data.effectiveDate,
|
||||
effective_to: null,
|
||||
note: data.note || null,
|
||||
status: data.status || 'draft',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 상세 조회
|
||||
*/
|
||||
export async function getPricingById(id: string): Promise<PricingData | null> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${id}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[PricingActions] GET pricing error:', response.status);
|
||||
return null;
|
||||
}
|
||||
|
||||
const result: ApiResponse<PriceApiData> = await response.json();
|
||||
console.log('[PricingActions] GET pricing response:', result);
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return transformApiToFrontend(result.data);
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] getPricingById error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 품목 정보 조회 (품목기준관리 API)
|
||||
*/
|
||||
export async function getItemInfo(itemId: string): Promise<ItemInfo | null> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
// materials API로 자재 정보 조회
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/materials/${itemId}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
// materials에서 못 찾으면 products에서 조회
|
||||
const productResponse = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/products/${itemId}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!productResponse.ok) {
|
||||
console.error('[PricingActions] Item not found:', itemId);
|
||||
return null;
|
||||
}
|
||||
|
||||
const productResult = await productResponse.json();
|
||||
if (!productResult.success || !productResult.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const product = productResult.data;
|
||||
return {
|
||||
id: String(product.id),
|
||||
itemCode: product.product_code,
|
||||
itemName: product.product_name,
|
||||
itemType: product.product_type || 'FG',
|
||||
specification: product.specification || undefined,
|
||||
unit: product.unit || 'EA',
|
||||
};
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
if (!result.success || !result.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const material = result.data;
|
||||
return {
|
||||
id: String(material.id),
|
||||
itemCode: material.item_code,
|
||||
itemName: material.item_name,
|
||||
itemType: material.product_type || 'RM',
|
||||
specification: material.specification || undefined,
|
||||
unit: material.unit || 'EA',
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] getItemInfo error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 등록
|
||||
*/
|
||||
export async function createPricing(
|
||||
data: PricingData,
|
||||
itemTypeCode: 'PRODUCT' | 'MATERIAL' = 'MATERIAL'
|
||||
): Promise<{ success: boolean; data?: PricingData; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = transformFrontendToApi(data, itemTypeCode);
|
||||
|
||||
console.log('[PricingActions] POST pricing request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] POST pricing response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '단가 등록에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] createPricing error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 수정
|
||||
*/
|
||||
export async function updatePricing(
|
||||
id: string,
|
||||
data: PricingData,
|
||||
changeReason?: string
|
||||
): Promise<{ success: boolean; data?: PricingData; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = {
|
||||
...transformFrontendToApi(data),
|
||||
change_reason: changeReason || null,
|
||||
};
|
||||
|
||||
console.log('[PricingActions] PUT pricing request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${id}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] PUT pricing response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '단가 수정에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] updatePricing error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 삭제
|
||||
*/
|
||||
export async function deletePricing(id: string): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${id}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] DELETE pricing response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '단가 삭제에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] deletePricing error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 확정
|
||||
*/
|
||||
export async function finalizePricing(id: string): Promise<{ success: boolean; data?: PricingData; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${id}/finalize`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] POST finalize response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '단가 확정에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] finalizePricing error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단가 이력 조회
|
||||
*/
|
||||
export async function getPricingRevisions(priceId: string): Promise<{
|
||||
success: boolean;
|
||||
data?: Array<{
|
||||
revisionNumber: number;
|
||||
revisionDate: string;
|
||||
revisionBy: string;
|
||||
revisionReason?: string;
|
||||
beforeSnapshot: Record<string, unknown> | null;
|
||||
afterSnapshot: Record<string, unknown>;
|
||||
}>;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/pricing/${priceId}/revisions`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[PricingActions] GET revisions response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '이력 조회에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const revisions = result.data.data?.map((rev: {
|
||||
revision_number: number;
|
||||
changed_at: string;
|
||||
changed_by: number;
|
||||
change_reason: string | null;
|
||||
before_snapshot: Record<string, unknown> | null;
|
||||
after_snapshot: Record<string, unknown>;
|
||||
changed_by_user?: { name: string };
|
||||
}) => ({
|
||||
revisionNumber: rev.revision_number,
|
||||
revisionDate: rev.changed_at,
|
||||
revisionBy: rev.changed_by_user?.name || `User ${rev.changed_by}`,
|
||||
revisionReason: rev.change_reason || undefined,
|
||||
beforeSnapshot: rev.before_snapshot,
|
||||
afterSnapshot: rev.after_snapshot,
|
||||
})) || [];
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: revisions,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[PricingActions] getPricingRevisions error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,14 @@ export { PricingFormClient } from './PricingFormClient';
|
||||
export { PricingHistoryDialog } from './PricingHistoryDialog';
|
||||
export { PricingRevisionDialog } from './PricingRevisionDialog';
|
||||
export { PricingFinalizeDialog } from './PricingFinalizeDialog';
|
||||
|
||||
// Server Actions
|
||||
export {
|
||||
getPricingById,
|
||||
getItemInfo,
|
||||
createPricing,
|
||||
updatePricing,
|
||||
deletePricing,
|
||||
finalizePricing,
|
||||
getPricingRevisions,
|
||||
} from './actions';
|
||||
|
||||
@@ -122,6 +122,7 @@ export interface PricingListItem {
|
||||
status: PricingStatus | 'not_registered';
|
||||
currentRevision: number;
|
||||
isFinal: boolean;
|
||||
itemTypeCode?: 'PRODUCT' | 'MATERIAL'; // API 등록 시 필요 (PRODUCT 또는 MATERIAL)
|
||||
}
|
||||
|
||||
// ===== 유틸리티 타입 =====
|
||||
|
||||
@@ -52,6 +52,9 @@ export interface QuoteItem {
|
||||
quantity: number; // 수량 (QTY)
|
||||
wingSize: string; // 마구리 날개치수 (WS)
|
||||
inspectionFee: number; // 검사비 (INSP)
|
||||
unitPrice?: number; // 단가
|
||||
totalAmount?: number; // 합계
|
||||
installType?: string; // 설치유형
|
||||
}
|
||||
|
||||
// 견적 폼 데이터 타입
|
||||
|
||||
138
src/components/settings/LeavePolicyManagement/index.tsx
Normal file
138
src/components/settings/LeavePolicyManagement/index.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { CalendarDays } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
// 기준 타입
|
||||
type StandardType = 'fiscal' | 'hire';
|
||||
|
||||
// 월 옵션 (1~12월)
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => ({
|
||||
value: (i + 1).toString(),
|
||||
label: `${i + 1}월`,
|
||||
}));
|
||||
|
||||
// 일 옵션 (1~31일)
|
||||
const DAY_OPTIONS = Array.from({ length: 31 }, (_, i) => ({
|
||||
value: (i + 1).toString(),
|
||||
label: `${i + 1}일`,
|
||||
}));
|
||||
|
||||
export function LeavePolicyManagement() {
|
||||
// 기준 설정 (회계연도 / 입사일)
|
||||
const [standardType, setStandardType] = useState<StandardType>('fiscal');
|
||||
// 기준일 (월, 일)
|
||||
const [month, setMonth] = useState('1');
|
||||
const [day, setDay] = useState('1');
|
||||
|
||||
// 저장
|
||||
const handleSave = () => {
|
||||
const settings = {
|
||||
standardType,
|
||||
month: parseInt(month),
|
||||
day: parseInt(day),
|
||||
};
|
||||
console.log('저장할 설정:', settings);
|
||||
toast.success('휴가 정책이 저장되었습니다.');
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
{/* 헤더 + 저장 버튼 */}
|
||||
<div className="flex items-start justify-between">
|
||||
<PageHeader
|
||||
title="휴가관리"
|
||||
description="휴가 항목을 관리합니다"
|
||||
icon={CalendarDays}
|
||||
/>
|
||||
<Button onClick={handleSave}>
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 기본 정보 카드 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-6">기본 정보</h3>
|
||||
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
{/* 기준 셀렉트 */}
|
||||
<div className="space-y-2">
|
||||
<Label>기준</Label>
|
||||
<Select value={standardType} onValueChange={(v: StandardType) => setStandardType(v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="fiscal">회계연도</SelectItem>
|
||||
<SelectItem value="hire">입사일</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 기준일 셀렉트 (월/일) */}
|
||||
<div className="space-y-2">
|
||||
<Label>기준일</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
value={month}
|
||||
onValueChange={setMonth}
|
||||
disabled={standardType === 'hire'}
|
||||
>
|
||||
<SelectTrigger className="w-24">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MONTH_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={day}
|
||||
onValueChange={setDay}
|
||||
disabled={standardType === 'hire'}
|
||||
>
|
||||
<SelectTrigger className="w-24">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DAY_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 안내 문구 */}
|
||||
<div className="mt-6 text-sm text-muted-foreground space-y-1">
|
||||
<p>! 휴가 기준일 설정에 따라서 휴가 조회 범위 및 자동 휴가 부여 정책의 기본 값이 변경됩니다.</p>
|
||||
<ul className="list-disc list-inside ml-2 space-y-1">
|
||||
<li>입사일 기준: 사원의 입사일 기준으로 휴가를 부여하고 조회할 수 있습니다.</li>
|
||||
<li>회계연도 기준: 회사의 회계연도 기준으로 휴가를 부여하고 조회할 수 있습니다.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
49
src/components/settings/LeavePolicyManagement/types.ts
Normal file
49
src/components/settings/LeavePolicyManagement/types.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 휴가관리(기준정보) 타입 정의 (PDF 57페이지 기준)
|
||||
*/
|
||||
|
||||
// 휴가 기준 유형
|
||||
export type LeaveStandardType = 'fiscal' | 'hire'; // 회계연도 / 입사일
|
||||
|
||||
export const LEAVE_STANDARD_TYPE_LABELS: Record<LeaveStandardType, string> = {
|
||||
fiscal: '회계연도',
|
||||
hire: '입사일',
|
||||
};
|
||||
|
||||
// 휴가 정책 설정
|
||||
export interface LeavePolicySettings {
|
||||
standardType: LeaveStandardType; // 기준
|
||||
fiscalStartMonth: number; // 기준일 (월) - 회계연도 기준일 때만 사용
|
||||
fiscalStartDay: number; // 기준일 (일)
|
||||
defaultAnnualLeave: number; // 기본 연차 일수
|
||||
additionalLeavePerYear: number; // 근속년수당 추가 연차
|
||||
maxAnnualLeave: number; // 최대 연차 일수
|
||||
carryOverEnabled: boolean; // 이월 허용 여부
|
||||
carryOverMaxDays: number; // 최대 이월 일수
|
||||
carryOverExpiryMonths: number; // 이월 연차 소멸 기간 (개월)
|
||||
}
|
||||
|
||||
// 기본 설정값
|
||||
export const DEFAULT_LEAVE_POLICY: LeavePolicySettings = {
|
||||
standardType: 'fiscal',
|
||||
fiscalStartMonth: 1,
|
||||
fiscalStartDay: 1,
|
||||
defaultAnnualLeave: 15,
|
||||
additionalLeavePerYear: 1,
|
||||
maxAnnualLeave: 25,
|
||||
carryOverEnabled: true,
|
||||
carryOverMaxDays: 10,
|
||||
carryOverExpiryMonths: 3,
|
||||
};
|
||||
|
||||
// 월 옵션
|
||||
export const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => ({
|
||||
value: i + 1,
|
||||
label: `${i + 1}월`,
|
||||
}));
|
||||
|
||||
// 일 옵션
|
||||
export const DAY_OPTIONS = Array.from({ length: 31 }, (_, i) => ({
|
||||
value: i + 1,
|
||||
label: `${i + 1}일`,
|
||||
}));
|
||||
@@ -0,0 +1,482 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { ChevronDown, ChevronRight, Shield, ArrowLeft } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import type { Permission, MenuPermission, PermissionType } from './types';
|
||||
|
||||
interface PermissionDetailProps {
|
||||
permission: Permission;
|
||||
onBack: () => void;
|
||||
onSave: (permission: Permission) => void;
|
||||
onDelete?: (permission: Permission) => void;
|
||||
}
|
||||
|
||||
// 메뉴 구조 타입 (localStorage user.menu와 동일한 구조)
|
||||
interface SerializableMenuItem {
|
||||
id: string;
|
||||
label: string;
|
||||
iconName: string;
|
||||
path: string;
|
||||
children?: SerializableMenuItem[];
|
||||
}
|
||||
|
||||
// 권한 타입 (기획서 기준: 전체 제외)
|
||||
const PERMISSION_TYPES: PermissionType[] = ['view', 'create', 'update', 'delete', 'approve', 'export', 'manage'];
|
||||
const PERMISSION_LABELS_MAP: Record<PermissionType, string> = {
|
||||
view: '조회',
|
||||
create: '생성',
|
||||
update: '수정',
|
||||
delete: '삭제',
|
||||
approve: '승인',
|
||||
export: '내보내기',
|
||||
manage: '관리',
|
||||
};
|
||||
|
||||
// 제외할 메뉴 ID 목록 (시스템 설정 하위 메뉴)
|
||||
const EXCLUDED_MENU_IDS = ['database', 'system-monitoring', 'security-management', 'system-settings'];
|
||||
|
||||
// 메뉴 필터링 함수 (제외 목록에 있는 메뉴 제거)
|
||||
const filterExcludedMenus = (menus: SerializableMenuItem[]): SerializableMenuItem[] => {
|
||||
return menus
|
||||
.filter(menu => !EXCLUDED_MENU_IDS.includes(menu.id))
|
||||
.map(menu => {
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
const filteredChildren = menu.children.filter(
|
||||
child => !EXCLUDED_MENU_IDS.includes(child.id)
|
||||
);
|
||||
// 자식이 모두 필터링되면 부모도 제거
|
||||
if (filteredChildren.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return { ...menu, children: filteredChildren };
|
||||
}
|
||||
return menu;
|
||||
})
|
||||
.filter((menu): menu is SerializableMenuItem => menu !== null);
|
||||
};
|
||||
|
||||
// localStorage에서 메뉴 데이터 가져오기
|
||||
const getMenuFromLocalStorage = (): SerializableMenuItem[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
|
||||
try {
|
||||
const userDataStr = localStorage.getItem('user');
|
||||
if (userDataStr) {
|
||||
const userData = JSON.parse(userDataStr);
|
||||
if (userData.menu && Array.isArray(userData.menu)) {
|
||||
// 제외 목록 필터링 적용
|
||||
return filterExcludedMenus(userData.menu);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load menu from localStorage:', error);
|
||||
}
|
||||
|
||||
// 기본 메뉴 (user.menu가 없는 경우)
|
||||
return [
|
||||
{ id: 'dashboard', label: '대시보드', iconName: 'layout-dashboard', path: '/dashboard' },
|
||||
{
|
||||
id: 'sales',
|
||||
label: '판매관리',
|
||||
iconName: 'shopping-cart',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'customer-management', label: '거래처관리', iconName: 'building-2', path: '/sales/client-management-sales-admin' },
|
||||
{ id: 'quote-management', label: '견적관리', iconName: 'receipt', path: '/sales/quote-management' },
|
||||
{ id: 'pricing-management', label: '단가관리', iconName: 'dollar-sign', path: '/sales/pricing-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'master-data',
|
||||
label: '기준정보',
|
||||
iconName: 'settings',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'item-master', label: '품목기준관리', iconName: 'package', path: '/master-data/item-master-data-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'hr',
|
||||
label: '인사관리',
|
||||
iconName: 'users',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'vacation-management', label: '휴가관리', iconName: 'calendar', path: '/hr/vacation-management' },
|
||||
{ id: 'salary-management', label: '급여관리', iconName: 'wallet', path: '/hr/salary-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'settings',
|
||||
label: '기준정보 설정',
|
||||
iconName: 'settings-2',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'ranks', label: '직급관리', iconName: 'badge', path: '/settings/ranks' },
|
||||
{ id: 'titles', label: '직책관리', iconName: 'user-cog', path: '/settings/titles' },
|
||||
{ id: 'permissions', label: '권한관리', iconName: 'shield', path: '/settings/permissions' },
|
||||
],
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
// 메뉴 구조를 flat한 MenuPermission 배열로 변환
|
||||
const convertMenuToPermissions = (
|
||||
menus: SerializableMenuItem[],
|
||||
existingPermissions: MenuPermission[]
|
||||
): MenuPermission[] => {
|
||||
const result: MenuPermission[] = [];
|
||||
|
||||
const processMenu = (menu: SerializableMenuItem, parentId?: string) => {
|
||||
// 기존 권한 데이터 찾기
|
||||
const existing = existingPermissions.find(ep => ep.menuId === menu.id);
|
||||
|
||||
result.push({
|
||||
menuId: menu.id,
|
||||
menuName: menu.label,
|
||||
parentMenuId: parentId,
|
||||
permissions: existing?.permissions || {},
|
||||
});
|
||||
|
||||
// 자식 메뉴 처리
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
menu.children.forEach(child => processMenu(child, menu.id));
|
||||
}
|
||||
};
|
||||
|
||||
menus.forEach(menu => processMenu(menu));
|
||||
return result;
|
||||
};
|
||||
|
||||
export function PermissionDetail({ permission, onBack, onSave, onDelete }: PermissionDetailProps) {
|
||||
const [name, setName] = useState(permission.name);
|
||||
const [status, setStatus] = useState(permission.status);
|
||||
const [menuStructure, setMenuStructure] = useState<SerializableMenuItem[]>([]);
|
||||
const [menuPermissions, setMenuPermissions] = useState<MenuPermission[]>([]);
|
||||
const [expandedMenus, setExpandedMenus] = useState<Set<string>>(new Set());
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
|
||||
// 메뉴 구조 로드 (localStorage에서)
|
||||
useEffect(() => {
|
||||
const menus = getMenuFromLocalStorage();
|
||||
setMenuStructure(menus);
|
||||
|
||||
// 기존 권한 데이터와 메뉴 구조 병합
|
||||
const permissions = convertMenuToPermissions(menus, permission.menuPermissions);
|
||||
setMenuPermissions(permissions);
|
||||
|
||||
// 기본적으로 모든 부모 메뉴 접힌 상태로 시작
|
||||
setExpandedMenus(new Set());
|
||||
}, [permission.menuPermissions]);
|
||||
|
||||
// 부모 메뉴 접기/펼치기
|
||||
const toggleMenuExpand = (menuId: string) => {
|
||||
setExpandedMenus(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(menuId)) {
|
||||
newSet.delete(menuId);
|
||||
} else {
|
||||
newSet.add(menuId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
// 메뉴가 부모 메뉴인지 확인
|
||||
const isParentMenu = (menuId: string): boolean => {
|
||||
const menu = menuStructure.find(m => m.id === menuId);
|
||||
return !!(menu?.children && menu.children.length > 0);
|
||||
};
|
||||
|
||||
// 권한 토글 (자동 저장)
|
||||
const handlePermissionToggle = (menuId: string, permType: PermissionType) => {
|
||||
const newMenuPermissions = menuPermissions.map(mp =>
|
||||
mp.menuId === menuId
|
||||
? {
|
||||
...mp,
|
||||
permissions: {
|
||||
...mp.permissions,
|
||||
[permType]: !mp.permissions[permType],
|
||||
},
|
||||
}
|
||||
: mp
|
||||
);
|
||||
setMenuPermissions(newMenuPermissions);
|
||||
|
||||
onSave({
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions: newMenuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
// 전체 선택/해제 (열 기준) - 헤더 체크박스
|
||||
const handleColumnSelectAll = (permType: PermissionType, checked: boolean) => {
|
||||
const newMenuPermissions = menuPermissions.map(mp => ({
|
||||
...mp,
|
||||
permissions: {
|
||||
...mp.permissions,
|
||||
[permType]: checked,
|
||||
},
|
||||
}));
|
||||
setMenuPermissions(newMenuPermissions);
|
||||
|
||||
onSave({
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions: newMenuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
// 기본 정보 변경
|
||||
const handleNameChange = (newName: string) => setName(newName);
|
||||
|
||||
const handleNameBlur = () => {
|
||||
if (name !== permission.name) {
|
||||
onSave({
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleStatusChange = (newStatus: 'active' | 'hidden') => {
|
||||
setStatus(newStatus);
|
||||
onSave({
|
||||
...permission,
|
||||
name,
|
||||
status: newStatus,
|
||||
menuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
// 삭제
|
||||
const handleDelete = () => setDeleteDialogOpen(true);
|
||||
|
||||
const confirmDelete = () => {
|
||||
onDelete?.(permission);
|
||||
setDeleteDialogOpen(false);
|
||||
onBack();
|
||||
};
|
||||
|
||||
// 메뉴 행 렌더링 (재귀적으로 부모-자식 처리)
|
||||
const renderMenuRows = () => {
|
||||
const rows: React.ReactElement[] = [];
|
||||
|
||||
menuStructure.forEach(menu => {
|
||||
const mp = menuPermissions.find(p => p.menuId === menu.id);
|
||||
if (!mp) return;
|
||||
|
||||
const hasChildren = menu.children && menu.children.length > 0;
|
||||
const isExpanded = expandedMenus.has(menu.id);
|
||||
|
||||
// 부모 메뉴 행
|
||||
rows.push(
|
||||
<TableRow key={menu.id} className="hover:bg-muted/50">
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
{hasChildren && (
|
||||
<button
|
||||
onClick={() => toggleMenuExpand(menu.id)}
|
||||
className="p-0.5 hover:bg-accent rounded"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
<span>{menu.label}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableCell key={pt} className="text-center">
|
||||
<Checkbox
|
||||
checked={mp.permissions[pt] || false}
|
||||
onCheckedChange={() => handlePermissionToggle(menu.id, pt)}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
// 자식 메뉴 행 (펼쳐진 경우에만)
|
||||
if (hasChildren && isExpanded) {
|
||||
menu.children?.forEach(child => {
|
||||
const childMp = menuPermissions.find(p => p.menuId === child.id);
|
||||
if (!childMp) return;
|
||||
|
||||
rows.push(
|
||||
<TableRow key={child.id} className="hover:bg-muted/50">
|
||||
<TableCell className="pl-10 text-muted-foreground">
|
||||
- {child.label}
|
||||
</TableCell>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableCell key={pt} className="text-center">
|
||||
<Checkbox
|
||||
checked={childMp.permissions[pt] || false}
|
||||
onCheckedChange={() => handlePermissionToggle(child.id, pt)}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
{/* 페이지 헤더 */}
|
||||
<PageHeader
|
||||
title="권한 상세"
|
||||
description="권한 상세 정보를 관리합니다"
|
||||
icon={Shield}
|
||||
actions={
|
||||
<Button variant="ghost" size="sm" onClick={onBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록으로
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 삭제/수정 버튼 (타이틀 아래, 기본정보 위) */}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={handleDelete}>
|
||||
삭제
|
||||
</Button>
|
||||
<Button onClick={() => onBack()}>
|
||||
수정
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 기본 정보 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">기본 정보</h3>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="perm-name">권한명</Label>
|
||||
<Input
|
||||
id="perm-name"
|
||||
value={name}
|
||||
onChange={(e) => handleNameChange(e.target.value)}
|
||||
onBlur={handleNameBlur}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="perm-status">상태</Label>
|
||||
<Select value={status} onValueChange={handleStatusChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="active">공개</SelectItem>
|
||||
<SelectItem value="hidden">숨김</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 메뉴별 권한 설정 테이블 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">메뉴</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="border-b">
|
||||
<TableHead className="w-64 py-4">메뉴</TableHead>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableHead key={pt} className="text-center w-24 py-4">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<span className="text-sm font-medium">{PERMISSION_LABELS_MAP[pt]}</span>
|
||||
<Checkbox
|
||||
checked={menuPermissions.length > 0 && menuPermissions.every(mp => mp.permissions[pt])}
|
||||
onCheckedChange={(checked) => handleColumnSelectAll(pt, !!checked)}
|
||||
/>
|
||||
</div>
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{renderMenuRows()}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>권한 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{permission.name}" 권한을 삭제하시겠습니까?
|
||||
<br />
|
||||
<span className="text-destructive">
|
||||
이 권한을 사용 중인 사원이 있으면 해당 사원의 권한이 초기화됩니다.
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,659 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ChevronDown, ChevronRight, Shield, ArrowLeft, Trash2, Save } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import type { Permission, MenuPermission, PermissionType } from './types';
|
||||
|
||||
interface PermissionDetailClientProps {
|
||||
permissionId: string;
|
||||
isNew?: boolean;
|
||||
}
|
||||
|
||||
// 메뉴 구조 타입 (localStorage user.menu와 동일한 구조)
|
||||
interface SerializableMenuItem {
|
||||
id: string;
|
||||
label: string;
|
||||
iconName: string;
|
||||
path: string;
|
||||
children?: SerializableMenuItem[];
|
||||
}
|
||||
|
||||
// 권한 타입 (기획서 기준: 전체 제외)
|
||||
const PERMISSION_TYPES: PermissionType[] = ['view', 'create', 'update', 'delete', 'approve', 'export', 'manage'];
|
||||
const PERMISSION_LABELS_MAP: Record<PermissionType, string> = {
|
||||
view: '조회',
|
||||
create: '생성',
|
||||
update: '수정',
|
||||
delete: '삭제',
|
||||
approve: '승인',
|
||||
export: '내보내기',
|
||||
manage: '관리',
|
||||
};
|
||||
|
||||
// 제외할 메뉴 ID 목록 (시스템 설정 하위 메뉴)
|
||||
const EXCLUDED_MENU_IDS = ['database', 'system-monitoring', 'security-management', 'system-settings'];
|
||||
|
||||
// 메뉴 필터링 함수 (제외 목록에 있는 메뉴 제거)
|
||||
const filterExcludedMenus = (menus: SerializableMenuItem[]): SerializableMenuItem[] => {
|
||||
return menus
|
||||
.filter(menu => !EXCLUDED_MENU_IDS.includes(menu.id))
|
||||
.map(menu => {
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
const filteredChildren = menu.children.filter(
|
||||
child => !EXCLUDED_MENU_IDS.includes(child.id)
|
||||
);
|
||||
// 자식이 모두 필터링되면 부모도 제거
|
||||
if (filteredChildren.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return { ...menu, children: filteredChildren };
|
||||
}
|
||||
return menu;
|
||||
})
|
||||
.filter((menu): menu is SerializableMenuItem => menu !== null);
|
||||
};
|
||||
|
||||
// localStorage에서 메뉴 데이터 가져오기
|
||||
const getMenuFromLocalStorage = (): SerializableMenuItem[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
|
||||
try {
|
||||
const userDataStr = localStorage.getItem('user');
|
||||
if (userDataStr) {
|
||||
const userData = JSON.parse(userDataStr);
|
||||
if (userData.menu && Array.isArray(userData.menu)) {
|
||||
// 제외 목록 필터링 적용
|
||||
return filterExcludedMenus(userData.menu);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load menu from localStorage:', error);
|
||||
}
|
||||
|
||||
// 기본 메뉴 (user.menu가 없는 경우)
|
||||
return [
|
||||
{ id: 'dashboard', label: '대시보드', iconName: 'layout-dashboard', path: '/dashboard' },
|
||||
{
|
||||
id: 'sales',
|
||||
label: '판매관리',
|
||||
iconName: 'shopping-cart',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'customer-management', label: '거래처관리', iconName: 'building-2', path: '/sales/client-management-sales-admin' },
|
||||
{ id: 'quote-management', label: '견적관리', iconName: 'receipt', path: '/sales/quote-management' },
|
||||
{ id: 'pricing-management', label: '단가관리', iconName: 'dollar-sign', path: '/sales/pricing-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'master-data',
|
||||
label: '기준정보',
|
||||
iconName: 'settings',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'item-master', label: '품목기준관리', iconName: 'package', path: '/master-data/item-master-data-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'hr',
|
||||
label: '인사관리',
|
||||
iconName: 'users',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'vacation-management', label: '휴가관리', iconName: 'calendar', path: '/hr/vacation-management' },
|
||||
{ id: 'salary-management', label: '급여관리', iconName: 'wallet', path: '/hr/salary-management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'settings',
|
||||
label: '기준정보 설정',
|
||||
iconName: 'settings-2',
|
||||
path: '#',
|
||||
children: [
|
||||
{ id: 'ranks', label: '직급관리', iconName: 'badge', path: '/settings/ranks' },
|
||||
{ id: 'titles', label: '직책관리', iconName: 'user-cog', path: '/settings/titles' },
|
||||
{ id: 'permissions', label: '권한관리', iconName: 'shield', path: '/settings/permissions' },
|
||||
],
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
// 메뉴 구조를 flat한 MenuPermission 배열로 변환
|
||||
const convertMenuToPermissions = (
|
||||
menus: SerializableMenuItem[],
|
||||
existingPermissions: MenuPermission[]
|
||||
): MenuPermission[] => {
|
||||
const result: MenuPermission[] = [];
|
||||
|
||||
const processMenu = (menu: SerializableMenuItem, parentId?: string) => {
|
||||
// 기존 권한 데이터 찾기
|
||||
const existing = existingPermissions.find(ep => ep.menuId === menu.id);
|
||||
|
||||
result.push({
|
||||
menuId: menu.id,
|
||||
menuName: menu.label,
|
||||
parentMenuId: parentId,
|
||||
permissions: existing?.permissions || {},
|
||||
});
|
||||
|
||||
// 자식 메뉴 처리
|
||||
if (menu.children && menu.children.length > 0) {
|
||||
menu.children.forEach(child => processMenu(child, menu.id));
|
||||
}
|
||||
};
|
||||
|
||||
menus.forEach(menu => processMenu(menu));
|
||||
return result;
|
||||
};
|
||||
|
||||
// localStorage 키
|
||||
const PERMISSIONS_STORAGE_KEY = 'buddy_permissions';
|
||||
|
||||
// 기본 권한 데이터
|
||||
const defaultPermissions: Permission[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: '관리자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '일반사용자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-01-15T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: '인사담당자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-02-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: '결재담당자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-02-15T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
name: '게스트',
|
||||
status: 'hidden',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-03-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
// localStorage에서 권한 데이터 로드
|
||||
const loadPermissions = (): Permission[] => {
|
||||
if (typeof window === 'undefined') return defaultPermissions;
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem(PERMISSIONS_STORAGE_KEY);
|
||||
if (stored) {
|
||||
return JSON.parse(stored);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load permissions:', error);
|
||||
}
|
||||
return defaultPermissions;
|
||||
};
|
||||
|
||||
// localStorage에 권한 데이터 저장
|
||||
const savePermissions = (permissions: Permission[]) => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
try {
|
||||
localStorage.setItem(PERMISSIONS_STORAGE_KEY, JSON.stringify(permissions));
|
||||
// 커스텀 이벤트 발생 (목록 페이지에서 감지)
|
||||
window.dispatchEvent(new CustomEvent('permissionsUpdated', { detail: permissions }));
|
||||
} catch (error) {
|
||||
console.error('Failed to save permissions:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export function PermissionDetailClient({ permissionId, isNew = false }: PermissionDetailClientProps) {
|
||||
const router = useRouter();
|
||||
const [permission, setPermission] = useState<Permission | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [status, setStatus] = useState<'active' | 'hidden'>('active');
|
||||
const [menuStructure, setMenuStructure] = useState<SerializableMenuItem[]>([]);
|
||||
const [menuPermissions, setMenuPermissions] = useState<MenuPermission[]>([]);
|
||||
const [expandedMenus, setExpandedMenus] = useState<Set<string>>(new Set());
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaved, setIsSaved] = useState(!isNew); // 새 권한은 저장 전 상태
|
||||
|
||||
// 권한 데이터 로드
|
||||
useEffect(() => {
|
||||
const menus = getMenuFromLocalStorage();
|
||||
setMenuStructure(menus);
|
||||
|
||||
if (isNew) {
|
||||
// 새 권한 등록 모드
|
||||
setName('');
|
||||
setStatus('active');
|
||||
const emptyPermissions = convertMenuToPermissions(menus, []);
|
||||
setMenuPermissions(emptyPermissions);
|
||||
setPermission(null);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 기존 권한 수정 모드
|
||||
const permissions = loadPermissions();
|
||||
const found = permissions.find(p => p.id.toString() === permissionId);
|
||||
|
||||
if (found) {
|
||||
setPermission(found);
|
||||
setName(found.name);
|
||||
setStatus(found.status);
|
||||
|
||||
// 기존 권한 데이터와 메뉴 구조 병합
|
||||
const mergedPermissions = convertMenuToPermissions(menus, found.menuPermissions);
|
||||
setMenuPermissions(mergedPermissions);
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
}, [permissionId, isNew]);
|
||||
|
||||
// 뒤로가기
|
||||
const handleBack = useCallback(() => {
|
||||
router.push('/settings/permissions');
|
||||
}, [router]);
|
||||
|
||||
// 부모 메뉴 접기/펼치기
|
||||
const toggleMenuExpand = (menuId: string) => {
|
||||
setExpandedMenus(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(menuId)) {
|
||||
newSet.delete(menuId);
|
||||
} else {
|
||||
newSet.add(menuId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
// 권한 저장 (기존 권한 수정 시)
|
||||
const savePermission = useCallback((updatedPermission: Permission) => {
|
||||
const permissions = loadPermissions();
|
||||
const updatedPermissions = permissions.map(p =>
|
||||
p.id === updatedPermission.id ? updatedPermission : p
|
||||
);
|
||||
savePermissions(updatedPermissions);
|
||||
setPermission(updatedPermission);
|
||||
}, []);
|
||||
|
||||
// 새 권한 저장
|
||||
const handleSaveNew = useCallback(() => {
|
||||
if (!name.trim()) {
|
||||
alert('권한명을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
const permissions = loadPermissions();
|
||||
const newId = Math.max(...permissions.map(p => p.id), 0) + 1;
|
||||
const newPermission: Permission = {
|
||||
id: newId,
|
||||
name: name.trim(),
|
||||
status,
|
||||
menuPermissions,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const updatedPermissions = [...permissions, newPermission];
|
||||
savePermissions(updatedPermissions);
|
||||
setPermission(newPermission);
|
||||
setIsSaved(true);
|
||||
|
||||
// 저장 후 상세 페이지로 이동 (URL 변경)
|
||||
router.replace(`/settings/permissions/${newId}`);
|
||||
}, [name, status, menuPermissions, router]);
|
||||
|
||||
// 권한 토글 (기존 권한은 자동 저장, 새 권한은 상태만 업데이트)
|
||||
const handlePermissionToggle = (menuId: string, permType: PermissionType) => {
|
||||
const newMenuPermissions = menuPermissions.map(mp =>
|
||||
mp.menuId === menuId
|
||||
? {
|
||||
...mp,
|
||||
permissions: {
|
||||
...mp.permissions,
|
||||
[permType]: !mp.permissions[permType],
|
||||
},
|
||||
}
|
||||
: mp
|
||||
);
|
||||
setMenuPermissions(newMenuPermissions);
|
||||
|
||||
// 기존 권한인 경우에만 자동 저장
|
||||
if (permission && isSaved) {
|
||||
const updatedPermission = {
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions: newMenuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
savePermission(updatedPermission);
|
||||
}
|
||||
};
|
||||
|
||||
// 전체 선택/해제 (열 기준) - 헤더 체크박스
|
||||
const handleColumnSelectAll = (permType: PermissionType, checked: boolean) => {
|
||||
const newMenuPermissions = menuPermissions.map(mp => ({
|
||||
...mp,
|
||||
permissions: {
|
||||
...mp.permissions,
|
||||
[permType]: checked,
|
||||
},
|
||||
}));
|
||||
setMenuPermissions(newMenuPermissions);
|
||||
|
||||
// 기존 권한인 경우에만 자동 저장
|
||||
if (permission && isSaved) {
|
||||
const updatedPermission = {
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions: newMenuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
savePermission(updatedPermission);
|
||||
}
|
||||
};
|
||||
|
||||
// 기본 정보 변경
|
||||
const handleNameBlur = () => {
|
||||
// 새 권한 모드에서는 저장하지 않음
|
||||
if (!permission || !isSaved || name === permission.name) return;
|
||||
|
||||
const updatedPermission = {
|
||||
...permission,
|
||||
name,
|
||||
status,
|
||||
menuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
savePermission(updatedPermission);
|
||||
};
|
||||
|
||||
const handleStatusChange = (newStatus: 'active' | 'hidden') => {
|
||||
setStatus(newStatus);
|
||||
|
||||
// 기존 권한인 경우에만 자동 저장
|
||||
if (permission && isSaved) {
|
||||
const updatedPermission = {
|
||||
...permission,
|
||||
name,
|
||||
status: newStatus,
|
||||
menuPermissions,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
savePermission(updatedPermission);
|
||||
}
|
||||
};
|
||||
|
||||
// 삭제
|
||||
const handleDelete = () => setDeleteDialogOpen(true);
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (!permission) return;
|
||||
|
||||
const permissions = loadPermissions();
|
||||
const updatedPermissions = permissions.filter(p => p.id !== permission.id);
|
||||
savePermissions(updatedPermissions);
|
||||
setDeleteDialogOpen(false);
|
||||
handleBack();
|
||||
};
|
||||
|
||||
// 메뉴 행 렌더링 (재귀적으로 부모-자식 처리)
|
||||
const renderMenuRows = () => {
|
||||
const rows: React.ReactElement[] = [];
|
||||
|
||||
menuStructure.forEach(menu => {
|
||||
const mp = menuPermissions.find(p => p.menuId === menu.id);
|
||||
if (!mp) return;
|
||||
|
||||
const hasChildren = menu.children && menu.children.length > 0;
|
||||
const isExpanded = expandedMenus.has(menu.id);
|
||||
|
||||
// 부모 메뉴 행
|
||||
rows.push(
|
||||
<TableRow key={menu.id} className="hover:bg-muted/50">
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
{hasChildren && (
|
||||
<button
|
||||
onClick={() => toggleMenuExpand(menu.id)}
|
||||
className="p-0.5 hover:bg-accent rounded"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
<span>{menu.label}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableCell key={pt} className="text-center">
|
||||
<Checkbox
|
||||
checked={mp.permissions[pt] || false}
|
||||
onCheckedChange={() => handlePermissionToggle(menu.id, pt)}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
// 자식 메뉴 행 (펼쳐진 경우에만)
|
||||
if (hasChildren && isExpanded) {
|
||||
menu.children?.forEach(child => {
|
||||
const childMp = menuPermissions.find(p => p.menuId === child.id);
|
||||
if (!childMp) return;
|
||||
|
||||
rows.push(
|
||||
<TableRow key={child.id} className="hover:bg-muted/50">
|
||||
<TableCell className="pl-10 text-muted-foreground">
|
||||
- {child.label}
|
||||
</TableCell>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableCell key={pt} className="text-center">
|
||||
<Checkbox
|
||||
checked={childMp.permissions[pt] || false}
|
||||
onCheckedChange={() => handlePermissionToggle(child.id, pt)}
|
||||
/>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="text-muted-foreground">로딩 중...</div>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
// 새 권한 등록 모드가 아닌데 권한을 찾지 못한 경우
|
||||
if (!permission && !isNew) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="flex flex-col items-center justify-center h-64 gap-4">
|
||||
<div className="text-muted-foreground">권한을 찾을 수 없습니다.</div>
|
||||
<Button onClick={handleBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록으로 돌아가기
|
||||
</Button>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
{/* 페이지 헤더 */}
|
||||
<PageHeader
|
||||
title={isNew ? '권한 등록' : '권한 상세'}
|
||||
description={isNew ? '새 권한을 등록합니다' : '권한 상세 정보를 관리합니다'}
|
||||
icon={Shield}
|
||||
actions={
|
||||
<Button variant="ghost" size="sm" onClick={handleBack}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
목록으로
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 저장/삭제 버튼 */}
|
||||
<div className="flex justify-end gap-2">
|
||||
{isNew ? (
|
||||
<Button onClick={handleSaveNew}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="destructive" onClick={handleDelete}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
삭제
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 기본 정보 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">기본 정보</h3>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="perm-name">권한명</Label>
|
||||
<Input
|
||||
id="perm-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={handleNameBlur}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="perm-status">상태</Label>
|
||||
<Select value={status} onValueChange={handleStatusChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="active">공개</SelectItem>
|
||||
<SelectItem value="hidden">숨김</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 메뉴별 권한 설정 테이블 */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">메뉴</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="border-b">
|
||||
<TableHead className="w-64 py-4">메뉴</TableHead>
|
||||
{PERMISSION_TYPES.map(pt => (
|
||||
<TableHead key={pt} className="text-center w-24 py-4">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<span className="text-sm font-medium">{PERMISSION_LABELS_MAP[pt]}</span>
|
||||
<Checkbox
|
||||
checked={menuPermissions.length > 0 && menuPermissions.every(mp => mp.permissions[pt])}
|
||||
onCheckedChange={(checked) => handleColumnSelectAll(pt, !!checked)}
|
||||
/>
|
||||
</div>
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{renderMenuRows()}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
{!isNew && permission && (
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>권한 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{permission.name}" 권한을 삭제하시겠습니까?
|
||||
<br />
|
||||
<span className="text-destructive">
|
||||
이 권한을 사용 중인 사원이 있으면 해당 사원의 권한이 초기화됩니다.
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { PermissionDialogProps } from './types';
|
||||
|
||||
/**
|
||||
* 권한 추가/수정 다이얼로그
|
||||
*/
|
||||
export function PermissionDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
mode,
|
||||
permission,
|
||||
onSubmit
|
||||
}: PermissionDialogProps) {
|
||||
const [name, setName] = useState('');
|
||||
const [status, setStatus] = useState<'active' | 'hidden'>('active');
|
||||
|
||||
// 다이얼로그 열릴 때 초기값 설정
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
if (mode === 'edit' && permission) {
|
||||
setName(permission.name);
|
||||
setStatus(permission.status);
|
||||
} else {
|
||||
setName('');
|
||||
setStatus('active');
|
||||
}
|
||||
}
|
||||
}, [isOpen, mode, permission]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) {
|
||||
onSubmit({ name: name.trim(), status });
|
||||
setName('');
|
||||
setStatus('active');
|
||||
}
|
||||
};
|
||||
|
||||
const dialogTitle = mode === 'add' ? '권한 등록' : '권한 수정';
|
||||
const submitText = mode === 'add' ? '등록' : '수정';
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dialogTitle}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="space-y-4 py-4">
|
||||
{/* 권한명 입력 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="permission-name">권한명</Label>
|
||||
<Input
|
||||
id="permission-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="권한명을 입력하세요"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 상태 선택 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="permission-status">상태</Label>
|
||||
<Select value={status} onValueChange={(value: 'active' | 'hidden') => setStatus(value)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="active">공개</SelectItem>
|
||||
<SelectItem value="hidden">숨김</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" disabled={!name.trim()}>
|
||||
{submitText}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
492
src/components/settings/PermissionManagement/index.tsx
Normal file
492
src/components/settings/PermissionManagement/index.tsx
Normal file
@@ -0,0 +1,492 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
Shield,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Settings,
|
||||
Eye,
|
||||
EyeOff,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { TableRow, TableCell } from '@/components/ui/table';
|
||||
import {
|
||||
IntegratedListTemplateV2,
|
||||
type TableColumn,
|
||||
type StatCard,
|
||||
type TabOption,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import type { Permission } from './types';
|
||||
|
||||
// localStorage 키
|
||||
const PERMISSIONS_STORAGE_KEY = 'buddy_permissions';
|
||||
|
||||
/**
|
||||
* 기본 권한 데이터 (PDF 54페이지 기준)
|
||||
*/
|
||||
const defaultPermissions: Permission[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: '관리자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '일반사용자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-01-15T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: '인사담당자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-02-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: '결재담당자',
|
||||
status: 'active',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-02-15T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
name: '게스트',
|
||||
status: 'hidden',
|
||||
menuPermissions: [],
|
||||
createdAt: '2025-03-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
// localStorage에서 권한 데이터 로드
|
||||
const loadPermissions = (): Permission[] => {
|
||||
if (typeof window === 'undefined') return defaultPermissions;
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem(PERMISSIONS_STORAGE_KEY);
|
||||
if (stored) {
|
||||
return JSON.parse(stored);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load permissions:', error);
|
||||
}
|
||||
return defaultPermissions;
|
||||
};
|
||||
|
||||
// localStorage에 권한 데이터 저장
|
||||
const savePermissions = (permissions: Permission[]) => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
try {
|
||||
localStorage.setItem(PERMISSIONS_STORAGE_KEY, JSON.stringify(permissions));
|
||||
} catch (error) {
|
||||
console.error('Failed to save permissions:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export function PermissionManagement() {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 권한 데이터
|
||||
const [permissions, setPermissions] = useState<Permission[]>(defaultPermissions);
|
||||
|
||||
// 삭제 확인 다이얼로그
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [permissionToDelete, setPermissionToDelete] = useState<Permission | null>(null);
|
||||
const [isBulkDelete, setIsBulkDelete] = useState(false);
|
||||
|
||||
// localStorage에서 초기 데이터 로드
|
||||
useEffect(() => {
|
||||
setPermissions(loadPermissions());
|
||||
}, []);
|
||||
|
||||
// 권한 변경 감지 (상세 페이지에서 변경 시)
|
||||
useEffect(() => {
|
||||
const handlePermissionsUpdated = (event: CustomEvent<Permission[]>) => {
|
||||
setPermissions(event.detail);
|
||||
};
|
||||
|
||||
window.addEventListener('permissionsUpdated', handlePermissionsUpdated as EventListener);
|
||||
return () => {
|
||||
window.removeEventListener('permissionsUpdated', handlePermissionsUpdated as EventListener);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ===== 탭 상태 =====
|
||||
const [activeTab, setActiveTab] = useState('all');
|
||||
|
||||
// ===== 체크박스 핸들러 =====
|
||||
const toggleSelection = useCallback((id: string) => {
|
||||
setSelectedItems(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(id)) newSet.delete(id);
|
||||
else newSet.add(id);
|
||||
return newSet;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === filteredData.length && filteredData.length > 0) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(filteredData.map(item => item.id.toString())));
|
||||
}
|
||||
}, [selectedItems.size]);
|
||||
|
||||
// ===== 필터링된 데이터 =====
|
||||
const filteredData = useMemo(() => {
|
||||
let result = permissions;
|
||||
|
||||
// 탭 필터
|
||||
if (activeTab === 'active') {
|
||||
result = result.filter(item => item.status === 'active');
|
||||
} else if (activeTab === 'hidden') {
|
||||
result = result.filter(item => item.status === 'hidden');
|
||||
}
|
||||
|
||||
// 검색 필터
|
||||
if (searchQuery) {
|
||||
result = result.filter(item =>
|
||||
item.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [permissions, searchQuery, activeTab]);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
return filteredData.slice(startIndex, startIndex + itemsPerPage);
|
||||
}, [filteredData, currentPage, itemsPerPage]);
|
||||
|
||||
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
|
||||
|
||||
// ===== 핸들러 =====
|
||||
const handleAdd = () => {
|
||||
// 새 권한 등록 페이지로 이동 (저장 전까지 목록에 추가 안됨)
|
||||
router.push('/settings/permissions/new');
|
||||
};
|
||||
|
||||
const handleEdit = (permission: Permission, e?: React.MouseEvent) => {
|
||||
e?.stopPropagation();
|
||||
// 상세 페이지로 라우팅
|
||||
router.push(`/settings/permissions/${permission.id}`);
|
||||
};
|
||||
|
||||
const handleViewDetail = (permission: Permission) => {
|
||||
// 상세 페이지로 라우팅
|
||||
router.push(`/settings/permissions/${permission.id}`);
|
||||
};
|
||||
|
||||
const handleDelete = (permission: Permission, e?: React.MouseEvent) => {
|
||||
e?.stopPropagation();
|
||||
setPermissionToDelete(permission);
|
||||
setIsBulkDelete(false);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleBulkDelete = () => {
|
||||
if (selectedItems.size === 0) return;
|
||||
setIsBulkDelete(true);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const confirmDelete = () => {
|
||||
let updatedPermissions: Permission[];
|
||||
if (isBulkDelete) {
|
||||
updatedPermissions = permissions.filter(p => !selectedItems.has(p.id.toString()));
|
||||
setSelectedItems(new Set());
|
||||
} else if (permissionToDelete) {
|
||||
updatedPermissions = permissions.filter(p => p.id !== permissionToDelete.id);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
setPermissions(updatedPermissions);
|
||||
savePermissions(updatedPermissions);
|
||||
setDeleteDialogOpen(false);
|
||||
setPermissionToDelete(null);
|
||||
};
|
||||
|
||||
// ===== 날짜 포맷 =====
|
||||
const formatDate = (dateStr: string) => {
|
||||
return format(new Date(dateStr), 'yyyy-MM-dd');
|
||||
};
|
||||
|
||||
// ===== 탭 설정 =====
|
||||
const tabs: TabOption[] = useMemo(() => {
|
||||
const activeCount = permissions.filter(p => p.status === 'active').length;
|
||||
const hiddenCount = permissions.filter(p => p.status === 'hidden').length;
|
||||
|
||||
return [
|
||||
{ value: 'all', label: '전체', count: permissions.length, color: 'blue' },
|
||||
{ value: 'active', label: '공개', count: activeCount, color: 'green' },
|
||||
{ value: 'hidden', label: '숨김', count: hiddenCount, color: 'gray' },
|
||||
];
|
||||
}, [permissions]);
|
||||
|
||||
// ===== 통계 카드 =====
|
||||
const statCards: StatCard[] = useMemo(() => {
|
||||
const totalCount = permissions.length;
|
||||
const activeCount = permissions.filter(p => p.status === 'active').length;
|
||||
const hiddenCount = permissions.filter(p => p.status === 'hidden').length;
|
||||
|
||||
return [
|
||||
{
|
||||
label: '전체 권한',
|
||||
value: totalCount,
|
||||
icon: Shield,
|
||||
iconColor: 'text-blue-500',
|
||||
},
|
||||
{
|
||||
label: '공개',
|
||||
value: activeCount,
|
||||
icon: Eye,
|
||||
iconColor: 'text-green-500',
|
||||
},
|
||||
{
|
||||
label: '숨김',
|
||||
value: hiddenCount,
|
||||
icon: EyeOff,
|
||||
iconColor: 'text-gray-500',
|
||||
},
|
||||
];
|
||||
}, [permissions]);
|
||||
|
||||
// ===== 테이블 컬럼 =====
|
||||
const tableColumns: TableColumn[] = useMemo(() => {
|
||||
const baseColumns: TableColumn[] = [
|
||||
{ key: 'index', label: '번호', className: 'text-center w-[80px]' },
|
||||
{ key: 'name', label: '권한', className: 'flex-1' },
|
||||
{ key: 'status', label: '상태', className: 'text-center flex-1' },
|
||||
{ key: 'createdAt', label: '등록일시', className: 'text-center flex-1' },
|
||||
];
|
||||
|
||||
// 체크박스 선택 시에만 작업 컬럼 표시
|
||||
if (selectedItems.size > 0) {
|
||||
baseColumns.push({ key: 'action', label: '작업', className: 'text-center flex-1' });
|
||||
}
|
||||
|
||||
return baseColumns;
|
||||
}, [selectedItems.size]);
|
||||
|
||||
// ===== 테이블 행 렌더링 =====
|
||||
const renderTableRow = useCallback((item: Permission, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(item.id.toString());
|
||||
const hasSelection = selectedItems.size > 0;
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={item.id}
|
||||
className="hover:bg-muted/50 cursor-pointer"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={() => toggleSelection(item.id.toString())}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-muted-foreground">
|
||||
{globalIndex}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{item.name}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge variant={item.status === 'active' ? 'default' : 'secondary'}>
|
||||
{item.status === 'active' ? '공개' : '숨김'}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{formatDate(item.createdAt)}</TableCell>
|
||||
{hasSelection && (
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex justify-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
className="h-8 w-8 p-0"
|
||||
title="권한 설정"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => handleEdit(item, e)}
|
||||
className="h-8 w-8 p-0"
|
||||
title="수정"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => handleDelete(item, e)}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
title="삭제"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, toggleSelection]);
|
||||
|
||||
// ===== 모바일 카드 렌더링 =====
|
||||
const renderMobileCard = useCallback((
|
||||
item: Permission,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<ListMobileCard
|
||||
id={item.id.toString()}
|
||||
title={item.name}
|
||||
headerBadges={
|
||||
<Badge variant={item.status === 'active' ? 'default' : 'secondary'}>
|
||||
{item.status === 'active' ? '공개' : '숨김'}
|
||||
</Badge>
|
||||
}
|
||||
isSelected={isSelected}
|
||||
onToggleSelection={onToggle}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoField label="상태" value={item.status === 'active' ? '공개' : '숨김'} />
|
||||
<InfoField label="등록일" value={formatDate(item.createdAt)} />
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
onClick={() => handleViewDetail(item)}
|
||||
>
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
권한 설정
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(item)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}, []);
|
||||
|
||||
// ===== 헤더 액션 =====
|
||||
const headerActions = (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{selectedItems.size > 0 && (
|
||||
<Button variant="destructive" onClick={handleBulkDelete}>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
선택 삭제 ({selectedItems.size})
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleAdd}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
권한 등록
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
// ===== 목록 화면 =====
|
||||
return (
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="권한관리"
|
||||
description="사용자 권한을 관리합니다"
|
||||
icon={Shield}
|
||||
headerActions={headerActions}
|
||||
stats={statCards}
|
||||
searchValue={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
searchPlaceholder="권한명 검색..."
|
||||
tabs={tabs}
|
||||
activeTab={activeTab}
|
||||
onTabChange={setActiveTab}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredData.length}
|
||||
allData={filteredData}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={toggleSelection}
|
||||
onToggleSelectAll={toggleSelectAll}
|
||||
getItemId={(item: Permission) => item.id.toString()}
|
||||
onBulkDelete={handleBulkDelete}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredData.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>권한 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{isBulkDelete
|
||||
? `선택한 ${selectedItems.size}개의 권한을 삭제하시겠습니까?`
|
||||
: `"${permissionToDelete?.name}" 권한을 삭제하시겠습니까?`
|
||||
}
|
||||
<br />
|
||||
<span className="text-destructive">
|
||||
이 권한을 사용 중인 사원이 있으면 해당 사원의 권한이 초기화됩니다.
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
45
src/components/settings/PermissionManagement/types.ts
Normal file
45
src/components/settings/PermissionManagement/types.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 권한 타입 정의 (PDF 54-55페이지 기준)
|
||||
*/
|
||||
|
||||
// 권한 유형
|
||||
export type PermissionType = 'view' | 'create' | 'update' | 'delete' | 'approve' | 'export' | 'manage';
|
||||
|
||||
// 메뉴별 권한 설정
|
||||
export interface MenuPermission {
|
||||
menuId: string;
|
||||
menuName: string;
|
||||
parentMenuId?: string;
|
||||
permissions: {
|
||||
[key in PermissionType]?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
// 권한 그룹
|
||||
export interface Permission {
|
||||
id: number;
|
||||
name: string;
|
||||
status: 'active' | 'hidden'; // 공개/숨김
|
||||
menuPermissions: MenuPermission[];
|
||||
createdAt: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface PermissionDialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
mode: 'add' | 'edit';
|
||||
permission?: Permission;
|
||||
onSubmit: (data: { name: string; status: 'active' | 'hidden' }) => void;
|
||||
}
|
||||
|
||||
// 권한 라벨 매핑
|
||||
export const PERMISSION_LABELS: Record<PermissionType, string> = {
|
||||
view: '조회',
|
||||
create: '생성',
|
||||
update: '수정',
|
||||
delete: '삭제',
|
||||
approve: '승인',
|
||||
export: '내보내기',
|
||||
manage: '관리',
|
||||
};
|
||||
84
src/components/settings/RankManagement/RankDialog.tsx
Normal file
84
src/components/settings/RankManagement/RankDialog.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import type { RankDialogProps } from './types';
|
||||
|
||||
/**
|
||||
* 직급 추가/수정 다이얼로그
|
||||
*/
|
||||
export function RankDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
mode,
|
||||
rank,
|
||||
onSubmit
|
||||
}: RankDialogProps) {
|
||||
const [name, setName] = useState('');
|
||||
|
||||
// 다이얼로그 열릴 때 초기값 설정
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
if (mode === 'edit' && rank) {
|
||||
setName(rank.name);
|
||||
} else {
|
||||
setName('');
|
||||
}
|
||||
}
|
||||
}, [isOpen, mode, rank]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) {
|
||||
onSubmit(name.trim());
|
||||
setName('');
|
||||
}
|
||||
};
|
||||
|
||||
const title = mode === 'add' ? '직급 추가' : '직급 수정';
|
||||
const submitText = mode === 'add' ? '등록' : '수정';
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="space-y-4 py-4">
|
||||
{/* 직급명 입력 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="rank-name">직급명</Label>
|
||||
<Input
|
||||
id="rank-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="직급명을 입력하세요"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" disabled={!name.trim()}>
|
||||
{submitText}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
272
src/components/settings/RankManagement/index.tsx
Normal file
272
src/components/settings/RankManagement/index.tsx
Normal file
@@ -0,0 +1,272 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { Award, Plus, GripVertical, Pencil, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { RankDialog } from './RankDialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import type { Rank } from './types';
|
||||
|
||||
/**
|
||||
* 기본 직급 데이터 (PDF 51페이지 기준)
|
||||
*/
|
||||
const defaultRanks: Rank[] = [
|
||||
{ id: 1, name: '사원', order: 1 },
|
||||
{ id: 2, name: '대리', order: 2 },
|
||||
{ id: 3, name: '과장', order: 3 },
|
||||
{ id: 4, name: '차장', order: 4 },
|
||||
{ id: 5, name: '부장', order: 5 },
|
||||
{ id: 6, name: '이사', order: 6 },
|
||||
{ id: 7, name: '상무', order: 7 },
|
||||
{ id: 8, name: '전무', order: 8 },
|
||||
{ id: 9, name: '부사장', order: 9 },
|
||||
{ id: 10, name: '사장', order: 10 },
|
||||
{ id: 11, name: '회장', order: 11 },
|
||||
];
|
||||
|
||||
export function RankManagement() {
|
||||
// 직급 데이터
|
||||
const [ranks, setRanks] = useState<Rank[]>(defaultRanks);
|
||||
|
||||
// 입력 필드
|
||||
const [newRankName, setNewRankName] = useState('');
|
||||
|
||||
// 다이얼로그 상태
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [dialogMode, setDialogMode] = useState<'add' | 'edit'>('add');
|
||||
const [selectedRank, setSelectedRank] = useState<Rank | undefined>();
|
||||
|
||||
// 삭제 확인 다이얼로그
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [rankToDelete, setRankToDelete] = useState<Rank | null>(null);
|
||||
|
||||
// 드래그 상태
|
||||
const [draggedItem, setDraggedItem] = useState<number | null>(null);
|
||||
|
||||
// 직급 추가 (입력 필드에서 직접)
|
||||
const handleQuickAdd = () => {
|
||||
if (!newRankName.trim()) return;
|
||||
|
||||
const newId = Math.max(...ranks.map(r => r.id), 0) + 1;
|
||||
const newOrder = Math.max(...ranks.map(r => r.order), 0) + 1;
|
||||
|
||||
setRanks(prev => [...prev, {
|
||||
id: newId,
|
||||
name: newRankName.trim(),
|
||||
order: newOrder,
|
||||
}]);
|
||||
setNewRankName('');
|
||||
};
|
||||
|
||||
// 직급 수정 다이얼로그 열기
|
||||
const handleEdit = (rank: Rank) => {
|
||||
setSelectedRank(rank);
|
||||
setDialogMode('edit');
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
// 직급 삭제 확인
|
||||
const handleDelete = (rank: Rank) => {
|
||||
setRankToDelete(rank);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// 삭제 실행
|
||||
const confirmDelete = () => {
|
||||
if (rankToDelete) {
|
||||
setRanks(prev => prev.filter(r => r.id !== rankToDelete.id));
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setRankToDelete(null);
|
||||
};
|
||||
|
||||
// 다이얼로그 제출
|
||||
const handleDialogSubmit = (name: string) => {
|
||||
if (dialogMode === 'edit' && selectedRank) {
|
||||
setRanks(prev => prev.map(r =>
|
||||
r.id === selectedRank.id ? { ...r, name } : r
|
||||
));
|
||||
}
|
||||
setDialogOpen(false);
|
||||
};
|
||||
|
||||
// 드래그 시작
|
||||
const handleDragStart = (e: React.DragEvent, index: number) => {
|
||||
setDraggedItem(index);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
};
|
||||
|
||||
// 드래그 종료
|
||||
const handleDragEnd = () => {
|
||||
setDraggedItem(null);
|
||||
};
|
||||
|
||||
// 드래그 오버
|
||||
const handleDragOver = (e: React.DragEvent, index: number) => {
|
||||
e.preventDefault();
|
||||
if (draggedItem === null || draggedItem === index) return;
|
||||
|
||||
const newRanks = [...ranks];
|
||||
const draggedRank = newRanks[draggedItem];
|
||||
newRanks.splice(draggedItem, 1);
|
||||
newRanks.splice(index, 0, draggedRank);
|
||||
|
||||
// 순서 업데이트
|
||||
const reorderedRanks = newRanks.map((rank, idx) => ({
|
||||
...rank,
|
||||
order: idx + 1
|
||||
}));
|
||||
|
||||
setRanks(reorderedRanks);
|
||||
setDraggedItem(index);
|
||||
};
|
||||
|
||||
// 키보드로 추가 (한글 IME 조합 중에는 무시)
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
|
||||
handleQuickAdd();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
<PageHeader
|
||||
title="직급관리"
|
||||
description="사원의 직급을 관리합니다. 드래그하여 순서를 변경할 수 있습니다."
|
||||
icon={Award}
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 직급 추가 입력 영역 */}
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newRankName}
|
||||
onChange={(e) => setNewRankName(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="직급명을 입력하세요"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={handleQuickAdd} disabled={!newRankName.trim()}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
추가
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 직급 목록 */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="divide-y">
|
||||
{ranks.map((rank, index) => (
|
||||
<div
|
||||
key={rank.id}
|
||||
draggable
|
||||
onDragStart={(e) => handleDragStart(e, index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragOver={(e) => handleDragOver(e, index)}
|
||||
className={`flex items-center gap-3 px-4 py-3 hover:bg-muted/50 transition-colors cursor-move ${
|
||||
draggedItem === index ? 'opacity-50 bg-muted' : ''
|
||||
}`}
|
||||
>
|
||||
{/* 드래그 핸들 */}
|
||||
<GripVertical className="h-5 w-5 text-muted-foreground flex-shrink-0" />
|
||||
|
||||
{/* 순서 번호 */}
|
||||
<span className="text-sm text-muted-foreground w-8">
|
||||
{index + 1}
|
||||
</span>
|
||||
|
||||
{/* 직급명 */}
|
||||
<span className="flex-1 font-medium">{rank.name}</span>
|
||||
|
||||
{/* 액션 버튼 */}
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(rank)}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
<span className="sr-only">수정</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(rank)}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<span className="sr-only">삭제</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{ranks.length === 0 && (
|
||||
<div className="px-4 py-8 text-center text-muted-foreground">
|
||||
등록된 직급이 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 안내 문구 */}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
※ 직급 순서는 드래그 앤 드롭으로 변경할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 수정 다이얼로그 */}
|
||||
<RankDialog
|
||||
isOpen={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
mode={dialogMode}
|
||||
rank={selectedRank}
|
||||
onSubmit={handleDialogSubmit}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>직급 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{rankToDelete?.name}" 직급을 삭제하시겠습니까?
|
||||
<br />
|
||||
<span className="text-destructive">
|
||||
이 직급을 사용 중인 사원이 있으면 해당 사원의 직급이 초기화됩니다.
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
18
src/components/settings/RankManagement/types.ts
Normal file
18
src/components/settings/RankManagement/types.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 직급 타입 정의
|
||||
*/
|
||||
export interface Rank {
|
||||
id: number;
|
||||
name: string;
|
||||
order: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface RankDialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
mode: 'add' | 'edit';
|
||||
rank?: Rank;
|
||||
onSubmit: (name: string) => void;
|
||||
}
|
||||
84
src/components/settings/TitleManagement/TitleDialog.tsx
Normal file
84
src/components/settings/TitleManagement/TitleDialog.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import type { TitleDialogProps } from './types';
|
||||
|
||||
/**
|
||||
* 직책 추가/수정 다이얼로그
|
||||
*/
|
||||
export function TitleDialog({
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
mode,
|
||||
title,
|
||||
onSubmit
|
||||
}: TitleDialogProps) {
|
||||
const [name, setName] = useState('');
|
||||
|
||||
// 다이얼로그 열릴 때 초기값 설정
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
if (mode === 'edit' && title) {
|
||||
setName(title.name);
|
||||
} else {
|
||||
setName('');
|
||||
}
|
||||
}
|
||||
}, [isOpen, mode, title]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) {
|
||||
onSubmit(name.trim());
|
||||
setName('');
|
||||
}
|
||||
};
|
||||
|
||||
const dialogTitle = mode === 'add' ? '직책 추가' : '직책 수정';
|
||||
const submitText = mode === 'add' ? '등록' : '수정';
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dialogTitle}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="space-y-4 py-4">
|
||||
{/* 직책명 입력 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="title-name">직책명</Label>
|
||||
<Input
|
||||
id="title-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="직책명을 입력하세요"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" disabled={!name.trim()}>
|
||||
{submitText}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
270
src/components/settings/TitleManagement/index.tsx
Normal file
270
src/components/settings/TitleManagement/index.tsx
Normal file
@@ -0,0 +1,270 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { Briefcase, Plus, GripVertical, Pencil, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { TitleDialog } from './TitleDialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import type { Title } from './types';
|
||||
|
||||
/**
|
||||
* 기본 직책 데이터 (PDF 52페이지 기준)
|
||||
*/
|
||||
const defaultTitles: Title[] = [
|
||||
{ id: 1, name: '없음(기본)', order: 1 },
|
||||
{ id: 2, name: '팀장', order: 2 },
|
||||
{ id: 3, name: '파트장', order: 3 },
|
||||
{ id: 4, name: '실장', order: 4 },
|
||||
{ id: 5, name: '부서장', order: 5 },
|
||||
{ id: 6, name: '본부장', order: 6 },
|
||||
{ id: 7, name: '센터장', order: 7 },
|
||||
{ id: 8, name: '매니저', order: 8 },
|
||||
{ id: 9, name: '리더', order: 9 },
|
||||
];
|
||||
|
||||
export function TitleManagement() {
|
||||
// 직책 데이터
|
||||
const [titles, setTitles] = useState<Title[]>(defaultTitles);
|
||||
|
||||
// 입력 필드
|
||||
const [newTitleName, setNewTitleName] = useState('');
|
||||
|
||||
// 다이얼로그 상태
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [dialogMode, setDialogMode] = useState<'add' | 'edit'>('add');
|
||||
const [selectedTitle, setSelectedTitle] = useState<Title | undefined>();
|
||||
|
||||
// 삭제 확인 다이얼로그
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [titleToDelete, setTitleToDelete] = useState<Title | null>(null);
|
||||
|
||||
// 드래그 상태
|
||||
const [draggedItem, setDraggedItem] = useState<number | null>(null);
|
||||
|
||||
// 직책 추가 (입력 필드에서 직접)
|
||||
const handleQuickAdd = () => {
|
||||
if (!newTitleName.trim()) return;
|
||||
|
||||
const newId = Math.max(...titles.map(t => t.id), 0) + 1;
|
||||
const newOrder = Math.max(...titles.map(t => t.order), 0) + 1;
|
||||
|
||||
setTitles(prev => [...prev, {
|
||||
id: newId,
|
||||
name: newTitleName.trim(),
|
||||
order: newOrder,
|
||||
}]);
|
||||
setNewTitleName('');
|
||||
};
|
||||
|
||||
// 직책 수정 다이얼로그 열기
|
||||
const handleEdit = (title: Title) => {
|
||||
setSelectedTitle(title);
|
||||
setDialogMode('edit');
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
// 직책 삭제 확인
|
||||
const handleDelete = (title: Title) => {
|
||||
setTitleToDelete(title);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// 삭제 실행
|
||||
const confirmDelete = () => {
|
||||
if (titleToDelete) {
|
||||
setTitles(prev => prev.filter(t => t.id !== titleToDelete.id));
|
||||
}
|
||||
setDeleteDialogOpen(false);
|
||||
setTitleToDelete(null);
|
||||
};
|
||||
|
||||
// 다이얼로그 제출
|
||||
const handleDialogSubmit = (name: string) => {
|
||||
if (dialogMode === 'edit' && selectedTitle) {
|
||||
setTitles(prev => prev.map(t =>
|
||||
t.id === selectedTitle.id ? { ...t, name } : t
|
||||
));
|
||||
}
|
||||
setDialogOpen(false);
|
||||
};
|
||||
|
||||
// 드래그 시작
|
||||
const handleDragStart = (e: React.DragEvent, index: number) => {
|
||||
setDraggedItem(index);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
};
|
||||
|
||||
// 드래그 종료
|
||||
const handleDragEnd = () => {
|
||||
setDraggedItem(null);
|
||||
};
|
||||
|
||||
// 드래그 오버
|
||||
const handleDragOver = (e: React.DragEvent, index: number) => {
|
||||
e.preventDefault();
|
||||
if (draggedItem === null || draggedItem === index) return;
|
||||
|
||||
const newTitles = [...titles];
|
||||
const draggedTitle = newTitles[draggedItem];
|
||||
newTitles.splice(draggedItem, 1);
|
||||
newTitles.splice(index, 0, draggedTitle);
|
||||
|
||||
// 순서 업데이트
|
||||
const reorderedTitles = newTitles.map((title, idx) => ({
|
||||
...title,
|
||||
order: idx + 1
|
||||
}));
|
||||
|
||||
setTitles(reorderedTitles);
|
||||
setDraggedItem(index);
|
||||
};
|
||||
|
||||
// 키보드로 추가 (한글 IME 조합 중에는 무시)
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
|
||||
handleQuickAdd();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
<PageHeader
|
||||
title="직책관리"
|
||||
description="사원의 직책을 관리합니다. 드래그하여 순서를 변경할 수 있습니다."
|
||||
icon={Briefcase}
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* 직책 추가 입력 영역 */}
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newTitleName}
|
||||
onChange={(e) => setNewTitleName(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="직책명을 입력하세요"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={handleQuickAdd} disabled={!newTitleName.trim()}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
추가
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 직책 목록 */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="divide-y">
|
||||
{titles.map((title, index) => (
|
||||
<div
|
||||
key={title.id}
|
||||
draggable
|
||||
onDragStart={(e) => handleDragStart(e, index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragOver={(e) => handleDragOver(e, index)}
|
||||
className={`flex items-center gap-3 px-4 py-3 hover:bg-muted/50 transition-colors cursor-move ${
|
||||
draggedItem === index ? 'opacity-50 bg-muted' : ''
|
||||
}`}
|
||||
>
|
||||
{/* 드래그 핸들 */}
|
||||
<GripVertical className="h-5 w-5 text-muted-foreground flex-shrink-0" />
|
||||
|
||||
{/* 순서 번호 */}
|
||||
<span className="text-sm text-muted-foreground w-8">
|
||||
{index + 1}
|
||||
</span>
|
||||
|
||||
{/* 직책명 */}
|
||||
<span className="flex-1 font-medium">{title.name}</span>
|
||||
|
||||
{/* 액션 버튼 */}
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(title)}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
<span className="sr-only">수정</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(title)}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<span className="sr-only">삭제</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{titles.length === 0 && (
|
||||
<div className="px-4 py-8 text-center text-muted-foreground">
|
||||
등록된 직책이 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 안내 문구 */}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
※ 직책 순서는 드래그 앤 드롭으로 변경할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 수정 다이얼로그 */}
|
||||
<TitleDialog
|
||||
isOpen={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
mode={dialogMode}
|
||||
title={selectedTitle}
|
||||
onSubmit={handleDialogSubmit}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>직책 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{titleToDelete?.name}" 직책을 삭제하시겠습니까?
|
||||
<br />
|
||||
<span className="text-destructive">
|
||||
이 직책을 사용 중인 사원이 있으면 해당 사원의 직책이 초기화됩니다.
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
18
src/components/settings/TitleManagement/types.ts
Normal file
18
src/components/settings/TitleManagement/types.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 직책 타입 정의
|
||||
*/
|
||||
export interface Title {
|
||||
id: number;
|
||||
name: string;
|
||||
order: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface TitleDialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
mode: 'add' | 'edit';
|
||||
title?: Title;
|
||||
onSubmit: (name: string) => void;
|
||||
}
|
||||
286
src/components/settings/WorkScheduleManagement/index.tsx
Normal file
286
src/components/settings/WorkScheduleManagement/index.tsx
Normal file
@@ -0,0 +1,286 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { Clock, Save } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { TimePicker } from '@/components/ui/time-picker';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { toast } from 'sonner';
|
||||
import type {
|
||||
WorkScheduleSettings,
|
||||
EmploymentType,
|
||||
DayOfWeek,
|
||||
} from './types';
|
||||
import {
|
||||
DEFAULT_WORK_SCHEDULE,
|
||||
EMPLOYMENT_TYPE_LABELS,
|
||||
DAY_OF_WEEK_LABELS,
|
||||
} from './types';
|
||||
|
||||
// 고용 형태별 기본 설정
|
||||
const EMPLOYMENT_TYPE_DEFAULTS: Record<EmploymentType, Partial<WorkScheduleSettings>> = {
|
||||
regular: {
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
},
|
||||
contract: {
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
},
|
||||
dispatch: {
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
},
|
||||
outsourcing: {
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
},
|
||||
partTime: {
|
||||
workDays: ['mon', 'tue', 'wed'],
|
||||
workStartTime: '10:00',
|
||||
workEndTime: '15:00',
|
||||
weeklyWorkHours: 15,
|
||||
weeklyOvertimeHours: 0,
|
||||
},
|
||||
};
|
||||
|
||||
export function WorkScheduleManagement() {
|
||||
// 현재 선택된 고용 형태
|
||||
const [selectedEmploymentType, setSelectedEmploymentType] = useState<EmploymentType>('regular');
|
||||
|
||||
// 근무 설정
|
||||
const [settings, setSettings] = useState<WorkScheduleSettings>(DEFAULT_WORK_SCHEDULE);
|
||||
|
||||
// 고용 형태 변경 시 기본값 로드
|
||||
useEffect(() => {
|
||||
const defaults = EMPLOYMENT_TYPE_DEFAULTS[selectedEmploymentType];
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
employmentType: selectedEmploymentType,
|
||||
...defaults,
|
||||
}));
|
||||
}, [selectedEmploymentType]);
|
||||
|
||||
// 근무일 토글
|
||||
const toggleWorkDay = (day: DayOfWeek) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
workDays: prev.workDays.includes(day)
|
||||
? prev.workDays.filter(d => d !== day)
|
||||
: [...prev.workDays, day],
|
||||
}));
|
||||
};
|
||||
|
||||
// 저장
|
||||
const handleSave = () => {
|
||||
// 실제로는 API 호출
|
||||
console.log('저장할 설정:', settings);
|
||||
toast.success(`${EMPLOYMENT_TYPE_LABELS[selectedEmploymentType]} 근무 설정이 저장되었습니다.`);
|
||||
};
|
||||
|
||||
const ALL_DAYS: DayOfWeek[] = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
<PageHeader
|
||||
title="근무관리"
|
||||
description="고용 형태별 근무 시간을 설정합니다."
|
||||
icon={Clock}
|
||||
/>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* 고용 형태 선택 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">고용 형태 선택</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="employment-type">고용 형태</Label>
|
||||
<Select
|
||||
value={selectedEmploymentType}
|
||||
onValueChange={(value: EmploymentType) => setSelectedEmploymentType(value)}
|
||||
>
|
||||
<SelectTrigger className="w-64">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.entries(EMPLOYMENT_TYPE_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 주간 근무일 설정 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">주간 근무일</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{ALL_DAYS.map((day) => (
|
||||
<label
|
||||
key={day}
|
||||
className="flex items-center gap-2 cursor-pointer"
|
||||
>
|
||||
<Checkbox
|
||||
checked={settings.workDays.includes(day)}
|
||||
onCheckedChange={() => toggleWorkDay(day)}
|
||||
/>
|
||||
<span className="text-sm font-medium">
|
||||
{DAY_OF_WEEK_LABELS[day]}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 1일 기준 근로시간 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">1일 기준 근로시간</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label>출근 시간</Label>
|
||||
<TimePicker
|
||||
value={settings.workStartTime}
|
||||
onChange={(value) => setSettings(prev => ({ ...prev, workStartTime: value }))}
|
||||
className="w-40"
|
||||
minuteStep={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>퇴근 시간</Label>
|
||||
<TimePicker
|
||||
value={settings.workEndTime}
|
||||
onChange={(value) => setSettings(prev => ({ ...prev, workEndTime: value }))}
|
||||
className="w-40"
|
||||
minuteStep={1}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 주당 근로시간 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">주당 근로시간</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="weekly-hours">주당 기준 근로시간</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="weekly-hours"
|
||||
type="number"
|
||||
min={0}
|
||||
max={52}
|
||||
value={settings.weeklyWorkHours}
|
||||
onChange={(e) =>
|
||||
setSettings(prev => ({ ...prev, weeklyWorkHours: parseInt(e.target.value) || 0 }))
|
||||
}
|
||||
className="w-24"
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">시간</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="overtime-hours">주당 연장 근로시간</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="overtime-hours"
|
||||
type="number"
|
||||
min={0}
|
||||
max={52}
|
||||
value={settings.weeklyOvertimeHours}
|
||||
onChange={(e) =>
|
||||
setSettings(prev => ({ ...prev, weeklyOvertimeHours: parseInt(e.target.value) || 0 }))
|
||||
}
|
||||
className="w-24"
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">시간</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 1일 기준 휴게시간 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">1일 기준 휴게시간</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label>휴게 시작</Label>
|
||||
<TimePicker
|
||||
value={settings.breakStartTime}
|
||||
onChange={(value) => setSettings(prev => ({ ...prev, breakStartTime: value }))}
|
||||
className="w-40"
|
||||
minuteStep={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>휴게 종료</Label>
|
||||
<TimePicker
|
||||
value={settings.breakEndTime}
|
||||
onChange={(value) => setSettings(prev => ({ ...prev, breakEndTime: value }))}
|
||||
className="w-40"
|
||||
minuteStep={1}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 저장 버튼 */}
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSave} size="lg">
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 안내 문구 */}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
※ 근무 설정은 고용 형태별로 저장됩니다. 설정 변경 후 반드시 저장 버튼을 클릭하세요.
|
||||
</p>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
51
src/components/settings/WorkScheduleManagement/types.ts
Normal file
51
src/components/settings/WorkScheduleManagement/types.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 근무관리 타입 정의 (PDF 56페이지 기준)
|
||||
*/
|
||||
|
||||
// 고용 형태
|
||||
export type EmploymentType = 'regular' | 'contract' | 'dispatch' | 'outsourcing' | 'partTime';
|
||||
|
||||
export const EMPLOYMENT_TYPE_LABELS: Record<EmploymentType, string> = {
|
||||
regular: '정규직',
|
||||
contract: '계약직',
|
||||
dispatch: '파견직',
|
||||
outsourcing: '용역직',
|
||||
partTime: '시간제 근로자',
|
||||
};
|
||||
|
||||
// 요일
|
||||
export type DayOfWeek = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
|
||||
|
||||
export const DAY_OF_WEEK_LABELS: Record<DayOfWeek, string> = {
|
||||
mon: '월',
|
||||
tue: '화',
|
||||
wed: '수',
|
||||
thu: '목',
|
||||
fri: '금',
|
||||
sat: '토',
|
||||
sun: '일',
|
||||
};
|
||||
|
||||
// 근무 설정
|
||||
export interface WorkScheduleSettings {
|
||||
employmentType: EmploymentType;
|
||||
workDays: DayOfWeek[]; // 주간 근무일
|
||||
workStartTime: string; // 출근 시간 (HH:mm)
|
||||
workEndTime: string; // 퇴근 시간 (HH:mm)
|
||||
weeklyWorkHours: number; // 주당 기준 근로시간
|
||||
weeklyOvertimeHours: number; // 주당 연장 근로시간
|
||||
breakStartTime: string; // 휴게 시작 시간 (HH:mm)
|
||||
breakEndTime: string; // 휴게 종료 시간 (HH:mm)
|
||||
}
|
||||
|
||||
// 기본 설정값
|
||||
export const DEFAULT_WORK_SCHEDULE: WorkScheduleSettings = {
|
||||
employmentType: 'regular',
|
||||
workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
workStartTime: '09:00',
|
||||
workEndTime: '18:00',
|
||||
weeklyWorkHours: 40,
|
||||
weeklyOvertimeHours: 12,
|
||||
breakStartTime: '12:00',
|
||||
breakEndTime: '13:00',
|
||||
};
|
||||
@@ -181,7 +181,7 @@ export function IntegratedListTemplateV2<T = any>({
|
||||
};
|
||||
|
||||
return (
|
||||
<PageLayout devMetadata={devMetadata}>
|
||||
<PageLayout>
|
||||
{/* 페이지 헤더 */}
|
||||
<PageHeader
|
||||
title={title}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ReactNode } from "react";
|
||||
import { ReactNode, ComponentType } from "react";
|
||||
import { LucideIcon } from "lucide-react";
|
||||
import { PageLayout } from "@/components/organisms/PageLayout";
|
||||
import { PageHeader } from "@/components/organisms/PageHeader";
|
||||
@@ -10,7 +10,7 @@ import { DataTable, Column } from "@/components/organisms/DataTable";
|
||||
import { EmptyState } from "@/components/organisms/EmptyState";
|
||||
import { MobileCard } from "@/components/organisms/MobileCard";
|
||||
|
||||
interface ListPageTemplateProps<T> {
|
||||
interface ListPageTemplateProps<T extends object> {
|
||||
// Header
|
||||
title: string;
|
||||
description?: string;
|
||||
@@ -50,7 +50,7 @@ interface ListPageTemplateProps<T> {
|
||||
icon?: ReactNode;
|
||||
badge?: { label: string; variant?: "default" | "secondary" | "destructive" | "outline" };
|
||||
fields: Array<{ label: string; value: string; badge?: boolean; badgeVariant?: string }>;
|
||||
actions?: Array<{ label: string; onClick: () => void; icon?: ReactNode; variant?: "default" | "outline" | "destructive" }>;
|
||||
actions?: Array<{ label: string; onClick: () => void; icon?: LucideIcon | ComponentType<any>; variant?: "default" | "outline" | "destructive" }>;
|
||||
};
|
||||
|
||||
// Empty State
|
||||
@@ -67,7 +67,7 @@ interface ListPageTemplateProps<T> {
|
||||
};
|
||||
}
|
||||
|
||||
export function ListPageTemplate<T>({
|
||||
export function ListPageTemplate<T extends object>({
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
|
||||
@@ -64,11 +64,10 @@ export function ResponsiveFormTemplate({
|
||||
<PageLayout maxWidth={maxWidth} versionInfo={versionInfo}>
|
||||
{/* 헤더 */}
|
||||
<PageHeader
|
||||
title={title}
|
||||
title={isEditMode ? `${title} 수정` : title}
|
||||
description={description}
|
||||
icon={icon}
|
||||
rightActions={headerActions}
|
||||
isEditMode={isEditMode}
|
||||
actions={headerActions}
|
||||
/>
|
||||
|
||||
{/* 메인 컨텐츠 */}
|
||||
|
||||
52
src/components/ui/scroll-area.tsx
Normal file
52
src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-bar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none select-none transition-colors",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
);
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
@@ -13,8 +13,8 @@ import { cn } from "@/lib/utils";
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
// modal={false}로 설정하여 aria-hidden 충돌 방지
|
||||
return <SelectPrimitive.Root data-slot="select" modal={false} {...props} />;
|
||||
// aria-hidden 충돌 방지를 위해 props만 전달
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
|
||||
@@ -6,11 +6,14 @@ import { XIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
// modal={false}: aria-hidden이 sibling 요소에 설정되지 않도록 함
|
||||
// 사이드바 용도로는 modal 모드가 필요하지 않음 (focus trap 불필요)
|
||||
// 이렇게 하면 Select, Dialog 등 다른 Radix 컴포넌트와 충돌 방지
|
||||
return <SheetPrimitive.Root data-slot="sheet" modal={false} {...props} />;
|
||||
function Sheet({
|
||||
modal = true, // 기본값을 true로 변경 (딤 처리 및 포커스 트랩 활성화)
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Root> & { modal?: boolean }) {
|
||||
// modal={true}: 딤 처리, 포커스 트랩, ESC 키로 닫기 등 모달 동작 활성화
|
||||
// modal={false}: aria-hidden이 sibling 요소에 설정되지 않음, 다른 Radix 컴포넌트와 충돌 방지
|
||||
// 모바일 사이드바에서는 modal={true}가 필요 (딤 클릭으로 닫기 기능)
|
||||
return <SheetPrimitive.Root data-slot="sheet" modal={modal} {...props} />;
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
|
||||
190
src/components/ui/time-picker.tsx
Normal file
190
src/components/ui/time-picker.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { Clock } from "lucide-react";
|
||||
import { cn } from "./utils";
|
||||
import { Button } from "./button";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "./popover";
|
||||
import { ScrollArea } from "./scroll-area";
|
||||
|
||||
interface TimePickerProps {
|
||||
value?: string; // "HH:mm" format
|
||||
onChange?: (value: string) => void;
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
/** 분 단위 간격 (기본값: 5) */
|
||||
minuteStep?: number;
|
||||
}
|
||||
|
||||
function TimePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "시간 선택",
|
||||
disabled = false,
|
||||
className,
|
||||
minuteStep = 5,
|
||||
}: TimePickerProps) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
// 현재 선택된 시/분 파싱
|
||||
const [selectedHour, selectedMinute] = React.useMemo(() => {
|
||||
if (!value) return [null, null];
|
||||
const [h, m] = value.split(":").map(Number);
|
||||
return [h, m];
|
||||
}, [value]);
|
||||
|
||||
// 시간 배열 생성 (0-23)
|
||||
const hours = Array.from({ length: 24 }, (_, i) => i);
|
||||
|
||||
// 분 배열 생성 (minuteStep 간격)
|
||||
const minutes = Array.from(
|
||||
{ length: Math.ceil(60 / minuteStep) },
|
||||
(_, i) => i * minuteStep
|
||||
);
|
||||
|
||||
// 시간 선택 핸들러
|
||||
const handleHourSelect = (hour: number) => {
|
||||
const minute = selectedMinute ?? 0;
|
||||
const newValue = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
|
||||
onChange?.(newValue);
|
||||
};
|
||||
|
||||
// 분 선택 핸들러
|
||||
const handleMinuteSelect = (minute: number) => {
|
||||
const hour = selectedHour ?? 0;
|
||||
const newValue = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
|
||||
onChange?.(newValue);
|
||||
};
|
||||
|
||||
// 표시할 시간 텍스트
|
||||
const displayValue = value || placeholder;
|
||||
|
||||
// 스크롤 영역 ref
|
||||
const hourScrollRef = React.useRef<HTMLDivElement>(null);
|
||||
const minuteScrollRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
// 팝오버 열릴 때 선택된 시간으로 스크롤
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setTimeout(() => {
|
||||
if (selectedHour !== null && hourScrollRef.current) {
|
||||
const hourElement = hourScrollRef.current.querySelector(
|
||||
`[data-hour="${selectedHour}"]`
|
||||
);
|
||||
hourElement?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
if (selectedMinute !== null && minuteScrollRef.current) {
|
||||
const minuteElement = minuteScrollRef.current.querySelector(
|
||||
`[data-minute="${selectedMinute}"]`
|
||||
);
|
||||
minuteElement?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
}, [open, selectedHour, selectedMinute]);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"w-full justify-start text-left font-normal",
|
||||
!value && "text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Clock className="mr-2 h-4 w-4" />
|
||||
{displayValue}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<div className="p-3">
|
||||
{/* 헤더 */}
|
||||
<div className="text-center mb-3">
|
||||
<span className="text-lg font-bold">시간 선택</span>
|
||||
</div>
|
||||
|
||||
{/* 시간/분 선택 영역 */}
|
||||
<div className="flex gap-2">
|
||||
{/* 시간 선택 */}
|
||||
<div className="flex flex-col">
|
||||
<span className="text-xs text-muted-foreground text-center mb-1 font-semibold">
|
||||
시
|
||||
</span>
|
||||
<ScrollArea className="h-[200px] w-[70px] rounded-md border">
|
||||
<div className="p-1" ref={hourScrollRef}>
|
||||
{hours.map((hour) => (
|
||||
<button
|
||||
key={hour}
|
||||
data-hour={hour}
|
||||
onClick={() => handleHourSelect(hour)}
|
||||
className={cn(
|
||||
"w-full px-3 py-2 text-sm rounded-md transition-colors",
|
||||
"hover:bg-primary/10",
|
||||
selectedHour === hour
|
||||
? "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground"
|
||||
: "text-foreground"
|
||||
)}
|
||||
>
|
||||
{hour.toString().padStart(2, "0")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* 구분자 */}
|
||||
<div className="flex items-center justify-center pt-5">
|
||||
<span className="text-2xl font-bold text-muted-foreground">:</span>
|
||||
</div>
|
||||
|
||||
{/* 분 선택 */}
|
||||
<div className="flex flex-col">
|
||||
<span className="text-xs text-muted-foreground text-center mb-1 font-semibold">
|
||||
분
|
||||
</span>
|
||||
<ScrollArea className="h-[200px] w-[70px] rounded-md border">
|
||||
<div className="p-1" ref={minuteScrollRef}>
|
||||
{minutes.map((minute) => (
|
||||
<button
|
||||
key={minute}
|
||||
data-minute={minute}
|
||||
onClick={() => handleMinuteSelect(minute)}
|
||||
className={cn(
|
||||
"w-full px-3 py-2 text-sm rounded-md transition-colors",
|
||||
"hover:bg-primary/10",
|
||||
selectedMinute === minute
|
||||
? "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground"
|
||||
: "text-foreground"
|
||||
)}
|
||||
>
|
||||
{minute.toString().padStart(2, "0")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 현재 선택된 시간 표시 */}
|
||||
{value && (
|
||||
<div className="mt-3 pt-3 border-t text-center">
|
||||
<span className="text-sm text-muted-foreground">선택: </span>
|
||||
<span className="text-sm font-semibold">{value}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export { TimePicker };
|
||||
export type { TimePickerProps };
|
||||
Reference in New Issue
Block a user