Merge lhj branch: 운영/작업 지원 위젯 4종 + 하이브리드 서비스 구현

This commit is contained in:
leeheejin
2025-10-14 17:22:52 +09:00
19 changed files with 2926 additions and 1 deletions

View File

@@ -37,6 +37,26 @@ const RiskAlertWidget = dynamic(() => import("@/components/dashboard/widgets/Ris
loading: () => <div className="flex h-full items-center justify-center text-sm text-gray-500"> ...</div>,
});
const TodoWidget = dynamic(() => import("@/components/dashboard/widgets/TodoWidget"), {
ssr: false,
loading: () => <div className="flex h-full items-center justify-center text-sm text-gray-500"> ...</div>,
});
const BookingAlertWidget = dynamic(() => import("@/components/dashboard/widgets/BookingAlertWidget"), {
ssr: false,
loading: () => <div className="flex h-full items-center justify-center text-sm text-gray-500"> ...</div>,
});
const MaintenanceWidget = dynamic(() => import("@/components/dashboard/widgets/MaintenanceWidget"), {
ssr: false,
loading: () => <div className="flex h-full items-center justify-center text-sm text-gray-500"> ...</div>,
});
const DocumentWidget = dynamic(() => import("@/components/dashboard/widgets/DocumentWidget"), {
ssr: false,
loading: () => <div className="flex h-full items-center justify-center text-sm text-gray-500"> ...</div>,
});
// 시계 위젯 임포트
import { ClockWidget } from "./widgets/ClockWidget";
// 달력 위젯 임포트
@@ -463,6 +483,26 @@ export function CanvasElement({
}}
/>
</div>
) : element.type === "widget" && element.subtype === "todo" ? (
// To-Do 위젯 렌더링
<div className="widget-interactive-area h-full w-full">
<TodoWidget />
</div>
) : element.type === "widget" && element.subtype === "booking-alert" ? (
// 예약 요청 알림 위젯 렌더링
<div className="widget-interactive-area h-full w-full">
<BookingAlertWidget />
</div>
) : element.type === "widget" && element.subtype === "maintenance" ? (
// 정비 일정 위젯 렌더링
<div className="widget-interactive-area h-full w-full">
<MaintenanceWidget />
</div>
) : element.type === "widget" && element.subtype === "document" ? (
// 문서 다운로드 위젯 렌더링
<div className="widget-interactive-area h-full w-full">
<DocumentWidget />
</div>
) : (
// 기타 위젯 렌더링
<div

View File

@@ -161,6 +161,46 @@ export function DashboardSidebar() {
/>
</div>
</div>
{/* 운영/작업 지원 섹션 */}
<div className="mb-8">
<h3 className="mb-4 border-b-2 border-green-500 pb-3 text-lg font-semibold text-gray-800">📋 / </h3>
<div className="space-y-3">
<DraggableItem
icon="✅"
title="To-Do / 긴급 지시"
type="widget"
subtype="todo"
onDragStart={handleDragStart}
className="border-l-4 border-blue-600"
/>
<DraggableItem
icon="🔔"
title="예약 요청 알림"
type="widget"
subtype="booking-alert"
onDragStart={handleDragStart}
className="border-l-4 border-rose-600"
/>
<DraggableItem
icon="🔧"
title="정비 일정 관리"
type="widget"
subtype="maintenance"
onDragStart={handleDragStart}
className="border-l-4 border-teal-600"
/>
<DraggableItem
icon="📂"
title="문서 다운로드"
type="widget"
subtype="document"
onDragStart={handleDragStart}
className="border-l-4 border-purple-600"
/>
</div>
</div>
</div>
);
}

View File

@@ -20,7 +20,11 @@ export type ElementSubtype =
| "vehicle-map"
| "delivery-status"
| "risk-alert"
| "driver-management"; // 위젯 타입
| "driver-management"
| "todo"
| "booking-alert"
| "maintenance"
| "document"; // 위젯 타입
export interface Position {
x: number;

View File

@@ -0,0 +1,308 @@
"use client";
import React, { useState, useEffect } from "react";
import { Check, X, Phone, MapPin, Package, Clock, AlertCircle } from "lucide-react";
interface BookingRequest {
id: string;
customerName: string;
customerPhone: string;
pickupLocation: string;
dropoffLocation: string;
scheduledTime: string;
vehicleType: "truck" | "van" | "car";
cargoType?: string;
weight?: number;
status: "pending" | "accepted" | "rejected" | "completed";
priority: "normal" | "urgent";
createdAt: string;
estimatedCost?: number;
}
export default function BookingAlertWidget() {
const [bookings, setBookings] = useState<BookingRequest[]>([]);
const [newCount, setNewCount] = useState(0);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<"all" | "pending" | "accepted">("pending");
const [showNotification, setShowNotification] = useState(false);
useEffect(() => {
fetchBookings();
const interval = setInterval(fetchBookings, 10000); // 10초마다 갱신
return () => clearInterval(interval);
}, [filter]);
const fetchBookings = async () => {
try {
const token = localStorage.getItem("authToken");
const filterParam = filter !== "all" ? `?status=${filter}` : "";
const response = await fetch(`http://localhost:9771/api/bookings${filterParam}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const result = await response.json();
const newBookings = result.data || [];
// 신규 예약이 있으면 알림 표시
if (result.newCount > 0 && newBookings.length > bookings.length) {
setShowNotification(true);
setTimeout(() => setShowNotification(false), 5000);
}
setBookings(newBookings);
setNewCount(result.newCount);
}
} catch (error) {
// console.error("예약 로딩 오류:", error);
} finally {
setLoading(false);
}
};
const handleAccept = async (id: string) => {
if (!confirm("이 예약을 수락하시겠습니까?")) return;
try {
const token = localStorage.getItem("authToken");
const response = await fetch(`http://localhost:9771/api/bookings/${id}/accept`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
fetchBookings();
}
} catch (error) {
// console.error("예약 수락 오류:", error);
}
};
const handleReject = async (id: string) => {
const reason = prompt("거절 사유를 입력하세요:");
if (!reason) return;
try {
const token = localStorage.getItem("authToken");
const response = await fetch(`http://localhost:9771/api/bookings/${id}/reject`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ reason }),
});
if (response.ok) {
fetchBookings();
}
} catch (error) {
// console.error("예약 거절 오류:", error);
}
};
const getVehicleIcon = (type: string) => {
switch (type) {
case "truck":
return "🚚";
case "van":
return "🚐";
case "car":
return "🚗";
default:
return "🚗";
}
};
const getTimeStatus = (scheduledTime: string) => {
const now = new Date();
const scheduled = new Date(scheduledTime);
const diff = scheduled.getTime() - now.getTime();
const hours = Math.floor(diff / (1000 * 60 * 60));
if (hours < 0) return { text: "⏰ 시간 초과", color: "text-red-600" };
if (hours < 2) return { text: `⏱️ ${hours}시간 후`, color: "text-red-600" };
if (hours < 4) return { text: `⏱️ ${hours}시간 후`, color: "text-orange-600" };
return { text: `📅 ${hours}시간 후`, color: "text-gray-600" };
};
const isNew = (createdAt: string) => {
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
return new Date(createdAt) > fiveMinutesAgo;
};
if (loading) {
return (
<div className="flex h-full items-center justify-center">
<div className="text-gray-500"> ...</div>
</div>
);
}
return (
<div className="flex h-full flex-col bg-gradient-to-br from-slate-50 to-rose-50">
{/* 신규 알림 배너 */}
{showNotification && newCount > 0 && (
<div className="animate-pulse border-b border-rose-300 bg-rose-100 px-4 py-2 text-center">
<span className="font-bold text-rose-700">🔔 {newCount} !</span>
</div>
)}
{/* 헤더 */}
<div className="border-b border-gray-200 bg-white px-4 py-3">
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<h3 className="text-lg font-bold text-gray-800">🔔 </h3>
{newCount > 0 && (
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-red-500 text-xs font-bold text-white">
{newCount}
</span>
)}
</div>
<button
onClick={fetchBookings}
className="rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90"
>
🔄
</button>
</div>
{/* 필터 */}
<div className="flex gap-2">
{(["pending", "accepted", "all"] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
filter === f ? "bg-primary text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"
}`}
>
{f === "pending" ? "대기중" : f === "accepted" ? "수락됨" : "전체"}
</button>
))}
</div>
</div>
{/* 예약 리스트 */}
<div className="flex-1 overflow-y-auto p-4">
{bookings.length === 0 ? (
<div className="flex h-full items-center justify-center text-gray-400">
<div className="text-center">
<div className="mb-2 text-4xl">📭</div>
<div> </div>
</div>
</div>
) : (
<div className="space-y-3">
{bookings.map((booking) => (
<div
key={booking.id}
className={`group relative rounded-lg border-2 bg-white p-4 shadow-sm transition-all hover:shadow-md ${
booking.priority === "urgent" ? "border-red-400" : "border-gray-200"
} ${booking.status !== "pending" ? "opacity-60" : ""}`}
>
{/* NEW 뱃지 */}
{isNew(booking.createdAt) && booking.status === "pending" && (
<div className="absolute -right-2 -top-2 animate-bounce">
<span className="flex h-12 w-12 items-center justify-center rounded-full bg-red-500 text-xs font-bold text-white shadow-lg">
🆕
</span>
</div>
)}
{/* 우선순위 표시 */}
{booking.priority === "urgent" && (
<div className="mb-2 flex items-center gap-1 text-sm font-bold text-red-600">
<AlertCircle className="h-4 w-4" />
</div>
)}
{/* 고객 정보 */}
<div className="mb-3 flex items-start justify-between">
<div className="flex-1">
<div className="mb-1 flex items-center gap-2">
<span className="text-2xl">{getVehicleIcon(booking.vehicleType)}</span>
<div>
<div className="font-bold text-gray-800">{booking.customerName}</div>
<div className="flex items-center gap-1 text-xs text-gray-600">
<Phone className="h-3 w-3" />
{booking.customerPhone}
</div>
</div>
</div>
</div>
{booking.status === "pending" && (
<div className="flex gap-1">
<button
onClick={() => handleAccept(booking.id)}
className="flex items-center gap-1 rounded bg-green-500 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-green-600"
>
<Check className="h-4 w-4" />
</button>
<button
onClick={() => handleReject(booking.id)}
className="flex items-center gap-1 rounded bg-red-500 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-red-600"
>
<X className="h-4 w-4" />
</button>
</div>
)}
{booking.status === "accepted" && (
<span className="rounded bg-green-100 px-2 py-1 text-xs font-medium text-green-700">
</span>
)}
</div>
{/* 경로 정보 */}
<div className="mb-3 space-y-2 border-t border-gray-100 pt-3">
<div className="flex items-start gap-2 text-sm">
<MapPin className="mt-0.5 h-4 w-4 flex-shrink-0 text-blue-600" />
<div className="flex-1">
<div className="font-medium text-gray-700"></div>
<div className="text-gray-600">{booking.pickupLocation}</div>
</div>
</div>
<div className="flex items-start gap-2 text-sm">
<MapPin className="mt-0.5 h-4 w-4 flex-shrink-0 text-rose-600" />
<div className="flex-1">
<div className="font-medium text-gray-700"></div>
<div className="text-gray-600">{booking.dropoffLocation}</div>
</div>
</div>
</div>
{/* 상세 정보 */}
<div className="grid grid-cols-2 gap-2 text-xs">
<div className="flex items-center gap-1">
<Package className="h-3 w-3 text-gray-500" />
<span className="text-gray-600">
{booking.cargoType} ({booking.weight}kg)
</span>
</div>
<div className={`flex items-center gap-1 ${getTimeStatus(booking.scheduledTime).color}`}>
<Clock className="h-3 w-3" />
<span className="font-medium">{getTimeStatus(booking.scheduledTime).text}</span>
</div>
{booking.estimatedCost && (
<div className="col-span-2 font-bold text-primary">
: {booking.estimatedCost.toLocaleString()}
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,242 @@
"use client";
import React, { useState } from "react";
import { FileText, Download, Calendar, Folder, Search } from "lucide-react";
interface Document {
id: string;
name: string;
category: "계약서" | "보험" | "세금계산서" | "기타";
size: string;
uploadDate: string;
url: string;
description?: string;
}
// 목 데이터
const mockDocuments: Document[] = [
{
id: "1",
name: "2025년 1월 세금계산서.pdf",
category: "세금계산서",
size: "1.2 MB",
uploadDate: "2025-01-05",
url: "/documents/tax-invoice-202501.pdf",
description: "1월 매출 세금계산서",
},
{
id: "2",
name: "차량보험증권_서울12가3456.pdf",
category: "보험",
size: "856 KB",
uploadDate: "2024-12-20",
url: "/documents/insurance-vehicle-1.pdf",
description: "1톤 트럭 종합보험",
},
{
id: "3",
name: "운송계약서_ABC물류.pdf",
category: "계약서",
size: "2.4 MB",
uploadDate: "2024-12-15",
url: "/documents/contract-abc-logistics.pdf",
description: "ABC물류 연간 운송 계약",
},
{
id: "4",
name: "2024년 12월 세금계산서.pdf",
category: "세금계산서",
size: "1.1 MB",
uploadDate: "2024-12-05",
url: "/documents/tax-invoice-202412.pdf",
},
{
id: "5",
name: "화물배상책임보험증권.pdf",
category: "보험",
size: "720 KB",
uploadDate: "2024-11-30",
url: "/documents/cargo-insurance.pdf",
description: "화물 배상책임보험",
},
{
id: "6",
name: "차고지 임대계약서.pdf",
category: "계약서",
size: "1.8 MB",
uploadDate: "2024-11-15",
url: "/documents/garage-lease-contract.pdf",
},
];
export default function DocumentWidget() {
const [documents] = useState<Document[]>(mockDocuments);
const [filter, setFilter] = useState<"all" | Document["category"]>("all");
const [searchTerm, setSearchTerm] = useState("");
const filteredDocuments = documents.filter((doc) => {
const matchesFilter = filter === "all" || doc.category === filter;
const matchesSearch =
searchTerm === "" ||
doc.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
doc.description?.toLowerCase().includes(searchTerm.toLowerCase());
return matchesFilter && matchesSearch;
});
const getCategoryIcon = (category: Document["category"]) => {
switch (category) {
case "계약서":
return "📄";
case "보험":
return "🛡️";
case "세금계산서":
return "💰";
case "기타":
return "📁";
}
};
const getCategoryColor = (category: Document["category"]) => {
switch (category) {
case "계약서":
return "bg-blue-100 text-blue-700";
case "보험":
return "bg-green-100 text-green-700";
case "세금계산서":
return "bg-amber-100 text-amber-700";
case "기타":
return "bg-gray-100 text-gray-700";
}
};
const handleDownload = (doc: Document) => {
// 실제로는 백엔드 API 호출
alert(`다운로드: ${doc.name}\n(실제 구현 시 파일 다운로드 처리)`);
};
const stats = {
total: documents.length,
contract: documents.filter((d) => d.category === "계약서").length,
insurance: documents.filter((d) => d.category === "보험").length,
tax: documents.filter((d) => d.category === "세금계산서").length,
};
return (
<div className="flex h-full flex-col bg-gradient-to-br from-slate-50 to-blue-50">
{/* 헤더 */}
<div className="border-b border-gray-200 bg-white px-4 py-3">
<div className="mb-3 flex items-center justify-between">
<h3 className="text-lg font-bold text-gray-800">📂 </h3>
<button className="rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90">
+
</button>
</div>
{/* 통계 */}
<div className="mb-3 grid grid-cols-4 gap-2 text-xs">
<div className="rounded bg-gray-50 px-2 py-1.5 text-center">
<div className="font-bold text-gray-700">{stats.total}</div>
<div className="text-gray-600"></div>
</div>
<div className="rounded bg-blue-50 px-2 py-1.5 text-center">
<div className="font-bold text-blue-700">{stats.contract}</div>
<div className="text-blue-600"></div>
</div>
<div className="rounded bg-green-50 px-2 py-1.5 text-center">
<div className="font-bold text-green-700">{stats.insurance}</div>
<div className="text-green-600"></div>
</div>
<div className="rounded bg-amber-50 px-2 py-1.5 text-center">
<div className="font-bold text-amber-700">{stats.tax}</div>
<div className="text-amber-600"></div>
</div>
</div>
{/* 검색 */}
<div className="mb-3 relative">
<Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
<input
type="text"
placeholder="문서명 검색..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full rounded border border-gray-300 py-2 pl-10 pr-3 text-sm focus:border-primary focus:outline-none"
/>
</div>
{/* 필터 */}
<div className="flex gap-2">
{(["all", "계약서", "보험", "세금계산서", "기타"] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
filter === f ? "bg-primary text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"
}`}
>
{f === "all" ? "전체" : f}
</button>
))}
</div>
</div>
{/* 문서 리스트 */}
<div className="flex-1 overflow-y-auto p-4">
{filteredDocuments.length === 0 ? (
<div className="flex h-full items-center justify-center text-gray-400">
<div className="text-center">
<div className="mb-2 text-4xl">📭</div>
<div> </div>
</div>
</div>
) : (
<div className="space-y-2">
{filteredDocuments.map((doc) => (
<div
key={doc.id}
className="group flex items-center gap-3 rounded-lg border border-gray-200 bg-white p-3 shadow-sm transition-all hover:border-primary hover:shadow-md"
>
{/* 아이콘 */}
<div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-lg bg-gray-50 text-2xl">
{getCategoryIcon(doc.category)}
</div>
{/* 정보 */}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="truncate font-medium text-gray-800">{doc.name}</div>
{doc.description && (
<div className="mt-0.5 truncate text-xs text-gray-600">{doc.description}</div>
)}
<div className="mt-1 flex items-center gap-3 text-xs text-gray-500">
<span className={`rounded px-2 py-0.5 ${getCategoryColor(doc.category)}`}>
{doc.category}
</span>
<span className="flex items-center gap-1">
<Calendar className="h-3 w-3" />
{new Date(doc.uploadDate).toLocaleDateString()}
</span>
<span>{doc.size}</span>
</div>
</div>
</div>
</div>
{/* 다운로드 버튼 */}
<button
onClick={() => handleDownload(doc)}
className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-primary text-white transition-colors hover:bg-primary/90"
title="다운로드"
>
<Download className="h-4 w-4" />
</button>
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,244 @@
"use client";
import React, { useState } from "react";
import { Calendar, Wrench, Truck, Check, Clock, AlertTriangle } from "lucide-react";
interface MaintenanceSchedule {
id: string;
vehicleNumber: string;
vehicleType: string;
maintenanceType: "정기점검" | "수리" | "타이어교체" | "오일교환" | "기타";
scheduledDate: string;
status: "scheduled" | "in_progress" | "completed" | "overdue";
notes?: string;
estimatedCost?: number;
}
// 목 데이터
const mockSchedules: MaintenanceSchedule[] = [
{
id: "1",
vehicleNumber: "서울12가3456",
vehicleType: "1톤 트럭",
maintenanceType: "정기점검",
scheduledDate: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(),
status: "scheduled",
notes: "6개월 정기점검",
estimatedCost: 300000,
},
{
id: "2",
vehicleNumber: "경기34나5678",
vehicleType: "2.5톤 트럭",
maintenanceType: "오일교환",
scheduledDate: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000).toISOString(),
status: "scheduled",
estimatedCost: 150000,
},
{
id: "3",
vehicleNumber: "인천56다7890",
vehicleType: "라보",
maintenanceType: "타이어교체",
scheduledDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
status: "overdue",
notes: "긴급",
estimatedCost: 400000,
},
{
id: "4",
vehicleNumber: "부산78라1234",
vehicleType: "1톤 트럭",
maintenanceType: "수리",
scheduledDate: new Date().toISOString(),
status: "in_progress",
notes: "엔진 점검 중",
estimatedCost: 800000,
},
];
export default function MaintenanceWidget() {
const [schedules] = useState<MaintenanceSchedule[]>(mockSchedules);
const [filter, setFilter] = useState<"all" | MaintenanceSchedule["status"]>("all");
const [selectedDate, setSelectedDate] = useState<Date>(new Date());
const filteredSchedules = schedules.filter(
(s) => filter === "all" || s.status === filter
);
const getStatusBadge = (status: MaintenanceSchedule["status"]) => {
switch (status) {
case "scheduled":
return <span className="rounded bg-blue-100 px-2 py-1 text-xs font-medium text-blue-700"></span>;
case "in_progress":
return <span className="rounded bg-amber-100 px-2 py-1 text-xs font-medium text-amber-700"></span>;
case "completed":
return <span className="rounded bg-green-100 px-2 py-1 text-xs font-medium text-green-700"></span>;
case "overdue":
return <span className="rounded bg-red-100 px-2 py-1 text-xs font-medium text-red-700"></span>;
}
};
const getMaintenanceIcon = (type: MaintenanceSchedule["maintenanceType"]) => {
switch (type) {
case "정기점검":
return "🔍";
case "수리":
return "🔧";
case "타이어교체":
return "⚙️";
case "오일교환":
return "🛢️";
default:
return "🔧";
}
};
const getDaysUntil = (date: string) => {
const now = new Date();
const scheduled = new Date(date);
const diff = scheduled.getTime() - now.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days < 0) return `${Math.abs(days)}일 지연`;
if (days === 0) return "오늘";
if (days === 1) return "내일";
return `${days}일 후`;
};
const stats = {
total: schedules.length,
scheduled: schedules.filter((s) => s.status === "scheduled").length,
inProgress: schedules.filter((s) => s.status === "in_progress").length,
overdue: schedules.filter((s) => s.status === "overdue").length,
};
return (
<div className="flex h-full flex-col bg-gradient-to-br from-slate-50 to-teal-50">
{/* 헤더 */}
<div className="border-b border-gray-200 bg-white px-4 py-3">
<div className="mb-3 flex items-center justify-between">
<h3 className="text-lg font-bold text-gray-800">🔧 </h3>
<button className="rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90">
+
</button>
</div>
{/* 통계 */}
<div className="mb-3 grid grid-cols-4 gap-2 text-xs">
<div className="rounded bg-blue-50 px-2 py-1.5 text-center">
<div className="font-bold text-blue-700">{stats.scheduled}</div>
<div className="text-blue-600"></div>
</div>
<div className="rounded bg-amber-50 px-2 py-1.5 text-center">
<div className="font-bold text-amber-700">{stats.inProgress}</div>
<div className="text-amber-600"></div>
</div>
<div className="rounded bg-red-50 px-2 py-1.5 text-center">
<div className="font-bold text-red-700">{stats.overdue}</div>
<div className="text-red-600"></div>
</div>
<div className="rounded bg-gray-50 px-2 py-1.5 text-center">
<div className="font-bold text-gray-700">{stats.total}</div>
<div className="text-gray-600"></div>
</div>
</div>
{/* 필터 */}
<div className="flex gap-2">
{(["all", "scheduled", "in_progress", "overdue"] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
filter === f ? "bg-primary text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"
}`}
>
{f === "all" ? "전체" : f === "scheduled" ? "예정" : f === "in_progress" ? "진행중" : "지연"}
</button>
))}
</div>
</div>
{/* 일정 리스트 */}
<div className="flex-1 overflow-y-auto p-4">
{filteredSchedules.length === 0 ? (
<div className="flex h-full items-center justify-center text-gray-400">
<div className="text-center">
<div className="mb-2 text-4xl">📅</div>
<div> </div>
</div>
</div>
) : (
<div className="space-y-3">
{filteredSchedules.map((schedule) => (
<div
key={schedule.id}
className={`group rounded-lg border-2 bg-white p-4 shadow-sm transition-all hover:shadow-md ${
schedule.status === "overdue" ? "border-red-300" : "border-gray-200"
}`}
>
<div className="mb-2 flex items-start justify-between">
<div className="flex items-center gap-2">
<span className="text-2xl">{getMaintenanceIcon(schedule.maintenanceType)}</span>
<div>
<div className="font-bold text-gray-800">{schedule.vehicleNumber}</div>
<div className="text-xs text-gray-600">{schedule.vehicleType}</div>
</div>
</div>
{getStatusBadge(schedule.status)}
</div>
<div className="mb-3 rounded bg-gray-50 p-2">
<div className="text-sm font-medium text-gray-700">{schedule.maintenanceType}</div>
{schedule.notes && <div className="mt-1 text-xs text-gray-600">{schedule.notes}</div>}
</div>
<div className="grid grid-cols-2 gap-2 text-xs">
<div className="flex items-center gap-1 text-gray-600">
<Calendar className="h-3 w-3" />
{new Date(schedule.scheduledDate).toLocaleDateString()}
</div>
<div
className={`flex items-center gap-1 font-medium ${
schedule.status === "overdue" ? "text-red-600" : "text-blue-600"
}`}
>
<Clock className="h-3 w-3" />
{getDaysUntil(schedule.scheduledDate)}
</div>
{schedule.estimatedCost && (
<div className="col-span-2 font-bold text-primary">
: {schedule.estimatedCost.toLocaleString()}
</div>
)}
</div>
{/* 액션 버튼 */}
{schedule.status === "scheduled" && (
<div className="mt-3 flex gap-2">
<button className="flex-1 rounded bg-blue-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-600">
</button>
<button className="flex-1 rounded bg-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-300">
</button>
</div>
)}
{schedule.status === "in_progress" && (
<div className="mt-3">
<button className="w-full rounded bg-green-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-green-600">
<Check className="mr-1 inline h-3 w-3" />
</button>
</div>
)}
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,405 @@
"use client";
import React, { useState, useEffect } from "react";
import { Plus, Check, X, Clock, AlertCircle, GripVertical, ChevronDown } from "lucide-react";
interface TodoItem {
id: string;
title: string;
description?: string;
priority: "urgent" | "high" | "normal" | "low";
status: "pending" | "in_progress" | "completed";
assignedTo?: string;
dueDate?: string;
createdAt: string;
updatedAt: string;
completedAt?: string;
isUrgent: boolean;
order: number;
}
interface TodoStats {
total: number;
pending: number;
inProgress: number;
completed: number;
urgent: number;
overdue: number;
}
export default function TodoWidget() {
const [todos, setTodos] = useState<TodoItem[]>([]);
const [stats, setStats] = useState<TodoStats | null>(null);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<"all" | "pending" | "in_progress" | "completed">("all");
const [showAddForm, setShowAddForm] = useState(false);
const [newTodo, setNewTodo] = useState({
title: "",
description: "",
priority: "normal" as TodoItem["priority"],
isUrgent: false,
dueDate: "",
assignedTo: "",
});
useEffect(() => {
fetchTodos();
const interval = setInterval(fetchTodos, 30000); // 30초마다 갱신
return () => clearInterval(interval);
}, [filter]);
const fetchTodos = async () => {
try {
const token = localStorage.getItem("authToken");
const filterParam = filter !== "all" ? `?status=${filter}` : "";
const response = await fetch(`http://localhost:9771/api/todos${filterParam}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const result = await response.json();
setTodos(result.data || []);
setStats(result.stats);
}
} catch (error) {
// console.error("To-Do 로딩 오류:", error);
} finally {
setLoading(false);
}
};
const handleAddTodo = async () => {
if (!newTodo.title.trim()) return;
try {
const token = localStorage.getItem("authToken");
const response = await fetch("http://localhost:9771/api/todos", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(newTodo),
});
if (response.ok) {
setNewTodo({
title: "",
description: "",
priority: "normal",
isUrgent: false,
dueDate: "",
assignedTo: "",
});
setShowAddForm(false);
fetchTodos();
}
} catch (error) {
// console.error("To-Do 추가 오류:", error);
}
};
const handleUpdateStatus = async (id: string, status: TodoItem["status"]) => {
try {
const token = localStorage.getItem("authToken");
const response = await fetch(`http://localhost:9771/api/todos/${id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ status }),
});
if (response.ok) {
fetchTodos();
}
} catch (error) {
// console.error("상태 업데이트 오류:", error);
}
};
const handleDelete = async (id: string) => {
if (!confirm("이 To-Do를 삭제하시겠습니까?")) return;
try {
const token = localStorage.getItem("authToken");
const response = await fetch(`http://localhost:9771/api/todos/${id}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
fetchTodos();
}
} catch (error) {
// console.error("To-Do 삭제 오류:", error);
}
};
const getPriorityColor = (priority: TodoItem["priority"]) => {
switch (priority) {
case "urgent":
return "bg-red-100 text-red-700 border-red-300";
case "high":
return "bg-orange-100 text-orange-700 border-orange-300";
case "normal":
return "bg-blue-100 text-blue-700 border-blue-300";
case "low":
return "bg-gray-100 text-gray-700 border-gray-300";
}
};
const getPriorityIcon = (priority: TodoItem["priority"]) => {
switch (priority) {
case "urgent":
return "🔴";
case "high":
return "🟠";
case "normal":
return "🟡";
case "low":
return "🟢";
}
};
const getTimeRemaining = (dueDate: string) => {
const now = new Date();
const due = new Date(dueDate);
const diff = due.getTime() - now.getTime();
const hours = Math.floor(diff / (1000 * 60 * 60));
const days = Math.floor(hours / 24);
if (diff < 0) return "⏰ 기한 초과";
if (days > 0) return `📅 ${days}일 남음`;
if (hours > 0) return `⏱️ ${hours}시간 남음`;
return "⚠️ 오늘 마감";
};
if (loading) {
return (
<div className="flex h-full items-center justify-center">
<div className="text-gray-500"> ...</div>
</div>
);
}
return (
<div className="flex h-full flex-col bg-gradient-to-br from-slate-50 to-blue-50">
{/* 헤더 */}
<div className="border-b border-gray-200 bg-white px-4 py-3">
<div className="mb-3 flex items-center justify-between">
<h3 className="text-lg font-bold text-gray-800"> To-Do / </h3>
<button
onClick={() => setShowAddForm(!showAddForm)}
className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90"
>
<Plus className="h-4 w-4" />
</button>
</div>
{/* 통계 */}
{stats && (
<div className="grid grid-cols-4 gap-2 text-xs">
<div className="rounded bg-blue-50 px-2 py-1.5 text-center">
<div className="font-bold text-blue-700">{stats.pending}</div>
<div className="text-blue-600"></div>
</div>
<div className="rounded bg-amber-50 px-2 py-1.5 text-center">
<div className="font-bold text-amber-700">{stats.inProgress}</div>
<div className="text-amber-600"></div>
</div>
<div className="rounded bg-red-50 px-2 py-1.5 text-center">
<div className="font-bold text-red-700">{stats.urgent}</div>
<div className="text-red-600"></div>
</div>
<div className="rounded bg-rose-50 px-2 py-1.5 text-center">
<div className="font-bold text-rose-700">{stats.overdue}</div>
<div className="text-rose-600"></div>
</div>
</div>
)}
{/* 필터 */}
<div className="mt-3 flex gap-2">
{(["all", "pending", "in_progress", "completed"] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
filter === f
? "bg-primary text-white"
: "bg-gray-100 text-gray-600 hover:bg-gray-200"
}`}
>
{f === "all" ? "전체" : f === "pending" ? "대기" : f === "in_progress" ? "진행중" : "완료"}
</button>
))}
</div>
</div>
{/* 추가 폼 */}
{showAddForm && (
<div className="border-b border-gray-200 bg-white p-4">
<div className="space-y-2">
<input
type="text"
placeholder="할 일 제목*"
value={newTodo.title}
onChange={(e) => setNewTodo({ ...newTodo, title: e.target.value })}
className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
/>
<textarea
placeholder="상세 설명 (선택)"
value={newTodo.description}
onChange={(e) => setNewTodo({ ...newTodo, description: e.target.value })}
className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
rows={2}
/>
<div className="grid grid-cols-2 gap-2">
<select
value={newTodo.priority}
onChange={(e) => setNewTodo({ ...newTodo, priority: e.target.value as TodoItem["priority"] })}
className="rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
>
<option value="low">🟢 </option>
<option value="normal">🟡 </option>
<option value="high">🟠 </option>
<option value="urgent">🔴 </option>
</select>
<input
type="datetime-local"
value={newTodo.dueDate}
onChange={(e) => setNewTodo({ ...newTodo, dueDate: e.target.value })}
className="rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
/>
</div>
<div className="flex items-center gap-2">
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={newTodo.isUrgent}
onChange={(e) => setNewTodo({ ...newTodo, isUrgent: e.target.checked })}
className="h-4 w-4 rounded border-gray-300"
/>
<span className="text-red-600 font-medium"> </span>
</label>
</div>
<div className="flex gap-2">
<button
onClick={handleAddTodo}
className="flex-1 rounded bg-primary px-4 py-2 text-sm text-white hover:bg-primary/90"
>
</button>
<button
onClick={() => setShowAddForm(false)}
className="rounded bg-gray-200 px-4 py-2 text-sm text-gray-700 hover:bg-gray-300"
>
</button>
</div>
</div>
</div>
)}
{/* To-Do 리스트 */}
<div className="flex-1 overflow-y-auto p-4">
{todos.length === 0 ? (
<div className="flex h-full items-center justify-center text-gray-400">
<div className="text-center">
<div className="mb-2 text-4xl">📝</div>
<div> </div>
</div>
</div>
) : (
<div className="space-y-2">
{todos.map((todo) => (
<div
key={todo.id}
className={`group relative rounded-lg border-2 bg-white p-3 shadow-sm transition-all hover:shadow-md ${
todo.isUrgent ? "border-red-400" : "border-gray-200"
} ${todo.status === "completed" ? "opacity-60" : ""}`}
>
<div className="flex items-start gap-3">
{/* 우선순위 아이콘 */}
<div className="mt-1 text-lg">{getPriorityIcon(todo.priority)}</div>
{/* 내용 */}
<div className="flex-1">
<div className="flex items-start justify-between gap-2">
<div className="flex-1">
<div className={`font-medium ${todo.status === "completed" ? "line-through" : ""}`}>
{todo.isUrgent && <span className="mr-1 text-red-600"></span>}
{todo.title}
</div>
{todo.description && (
<div className="mt-1 text-xs text-gray-600">{todo.description}</div>
)}
{todo.dueDate && (
<div className="mt-1 text-xs text-gray-500">{getTimeRemaining(todo.dueDate)}</div>
)}
</div>
{/* 액션 버튼 */}
<div className="flex gap-1">
{todo.status !== "completed" && (
<button
onClick={() => handleUpdateStatus(todo.id, "completed")}
className="rounded p-1 text-green-600 hover:bg-green-50"
title="완료"
>
<Check className="h-4 w-4" />
</button>
)}
<button
onClick={() => handleDelete(todo.id)}
className="rounded p-1 text-red-600 hover:bg-red-50"
title="삭제"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
{/* 상태 변경 */}
{todo.status !== "completed" && (
<div className="mt-2 flex gap-1">
<button
onClick={() => handleUpdateStatus(todo.id, "pending")}
className={`rounded px-2 py-1 text-xs ${
todo.status === "pending"
? "bg-blue-100 text-blue-700"
: "bg-gray-100 text-gray-600 hover:bg-gray-200"
}`}
>
</button>
<button
onClick={() => handleUpdateStatus(todo.id, "in_progress")}
className={`rounded px-2 py-1 text-xs ${
todo.status === "in_progress"
? "bg-amber-100 text-amber-700"
: "bg-gray-100 text-gray-600 hover:bg-gray-200"
}`}
>
</button>
</div>
)}
</div>
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}