Initial commit - ERP System

This commit is contained in:
root
2026-05-20 18:58:23 +00:00
commit e174936997
2697 changed files with 1628427 additions and 0 deletions
+329
View File
@@ -0,0 +1,329 @@
// /opt/erp-system/app/tickets/[id]/page.tsx
'use client';
import { useState, useEffect, useRef } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useSession } from "next-auth/react";
import { Send, CheckCircle, Clock, ArrowLeft, StickyNote, Activity, User as UserIcon, Paperclip, FileText, Download, AlertTriangle } from 'lucide-react';
import { useToast } from '../../components/ToastProvider';
import { getStatusBadge, getPriorityBadge } from '../../components/AppShell';
export default function TicketDetailPage() {
const params = useParams();
const router = useRouter();
const { data: session } = useSession();
const ticketId = params.id;
const { toast } = useToast();
const [ticket, setTicket] = useState<any>(null);
const [users, setUsers] = useState<any[]>([]);
const [attachments, setAttachments] = useState<any[]>([]);
const [error, setError] = useState(false);
const [messageInput, setMessageInput] = useState('');
const [uploading, setUploading] = useState(false);
const [showModal, setShowModal] = useState(false);
const [modalMode, setModalMode] = useState<'addTime' | 'close' | 'addNote'>('addTime');
const [modalData, setModalData] = useState({ durationMins: 15, description: '', content: '' });
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (ticketId) {
fetchTicket();
fetchAttachments();
if ((session?.user as any)?.userType === 'TEAM') {
fetchUsers();
}
}
}, [ticketId, session]);
const fetchTicket = async () => {
try {
const res = await fetch(`/api/tickets/${ticketId}`);
if (res.ok) setTicket(await res.json());
else setError(true);
} catch (err) {
setError(true);
}
};
const fetchUsers = async () => {
const res = await fetch('/api/users');
if (res.ok) setUsers(await res.json());
};
const fetchAttachments = async () => {
const res = await fetch(`/api/tickets/${ticketId}/attachments`);
if (res.ok) setAttachments(await res.json());
};
const handleSendMessage = async (e: React.FormEvent) => {
e.preventDefault();
if (!messageInput.trim()) return;
await fetch(`/api/tickets/${ticketId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'addMessage', content: messageInput })
});
setMessageInput('');
fetchTicket();
};
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploading(true);
const formData = new FormData();
formData.append('file', file);
const res = await fetch(`/api/tickets/${ticketId}/attachments`, {
method: 'POST',
body: formData
});
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = '';
if (res.ok) {
fetchAttachments();
fetchTicket();
} else {
toast('Fehler beim Hochladen der Datei.', 'error');
}
};
const handleAssign = async (userId: string) => {
await fetch(`/api/tickets/${ticketId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'assign', userId })
});
fetchTicket();
};
const handleChangePriority = async (priority: string) => {
await fetch(`/api/tickets/${ticketId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'changePriority', priority })
});
fetchTicket();
};
const handleModalSubmit = async (e: React.FormEvent) => {
e.preventDefault();
let payload = {};
if (modalMode === 'addNote') {
payload = { action: 'addNote', content: modalData.content };
} else {
const action = modalMode === 'close' ? 'closeTicket' : 'addTimeEntry';
payload = { action, durationMins: modalData.durationMins, description: modalData.description };
}
const res = await fetch(`/api/tickets/${ticketId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (res.ok) {
setShowModal(false);
setModalData({ durationMins: 15, description: '', content: '' });
fetchTicket();
}
};
const openModal = (mode: 'addTime' | 'close' | 'addNote') => {
setModalMode(mode);
setShowModal(true);
};
const formatBytes = (bytes: number) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
if (error) return <div className="p-8 text-red-600 font-medium">Fehler: Ticket konnte nicht geladen werden.</div>;
if (!ticket) return <div className="p-8 text-slate-500 font-medium animate-pulse">Lade Ticketdaten...</div>;
const isClosed = ticket.status === 'RESOLVED' || ticket.status === 'CLOSED';
const userType = (session?.user as any)?.userType;
const timelineItems = [
...(ticket.timeEntries || []).map((entry: any) => ({ ...entry, type: 'time' })),
...(ticket.notes || []).map((note: any) => ({ ...note, type: 'note' }))
].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
return (
<div className="max-w-7xl mx-auto space-y-6 relative pb-12 animate-fade-in-up">
<div className="flex items-center gap-4">
<button onClick={() => router.push('/')} className="p-2 hover:bg-slate-200 rounded-lg text-slate-600 transition">
<ArrowLeft className="w-5 h-5" />
</button>
<div>
<h1 className="text-2xl font-bold text-slate-900 mb-1">#{ticket.id}: {ticket.title}</h1>
<div className="flex items-center gap-3 mt-2">
{getStatusBadge(ticket.status)}
{getPriorityBadge(ticket.priority)}
</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-4">
<div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100">
<h3 className="font-semibold text-slate-800 mb-2">Beschreibung</h3>
<p className="text-slate-600 whitespace-pre-wrap">{ticket.description}</p>
</div>
<div className="bg-white rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 flex flex-col h-[500px]">
<div className="p-4 border-b border-slate-200 font-semibold text-slate-800">Nachrichtenverlauf</div>
<div className="flex-1 p-4 overflow-y-auto space-y-4 bg-slate-50">
{ticket.messages.length === 0 ? (
<p className="text-center text-slate-400 mt-4">Noch keine Nachrichten.</p>
) : (
ticket.messages.map((msg: any) => (
<div key={msg.id} className={`flex ${msg.isFromCustomer ? 'justify-end' : 'justify-start'}`}>
<div className={`max-w-[75%] p-3 rounded-lg ${msg.isFromCustomer ? 'bg-indigo-600 text-white shadow-sm' : 'bg-white border border-slate-200 text-slate-800'}`}>
<p className="text-sm whitespace-pre-wrap">{msg.content}</p>
<span className={`text-[10px] mt-1 block ${msg.isFromCustomer ? 'text-indigo-200' : 'text-slate-400'}`}>
{new Date(msg.createdAt).toLocaleString('de-DE')}
</span>
</div>
</div>
))
)}
</div>
{!isClosed && (
<div className="p-4 border-t border-slate-200 bg-white">
<form onSubmit={handleSendMessage} className="flex gap-2">
<input type="text" value={messageInput} onChange={(e) => setMessageInput(e.target.value)} placeholder="Antwort schreiben..." className="flex-1 border border-slate-300 p-2.5 rounded-xl focus-ring outline-none transition-all" />
<input type="file" className="hidden" ref={fileInputRef} onChange={handleFileUpload} />
<button type="button" onClick={() => fileInputRef.current?.click()} disabled={uploading} className="bg-slate-100 text-slate-600 p-2.5 rounded-lg hover:bg-slate-200 transition">
<Paperclip className="w-5 h-5" />
</button>
<button type="submit" className="bg-indigo-600 text-white p-2.5 rounded-lg hover:bg-indigo-700 transition">
<Send className="w-5 h-5" />
</button>
</form>
</div>
)}
</div>
</div>
<div className="space-y-6">
<div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100">
<h3 className="font-semibold text-slate-800 mb-4 flex items-center gap-2">
<Paperclip className="w-5 h-5 text-slate-500" /> Anhänge ({attachments.length})
</h3>
{attachments.length > 0 ? (
<div className="space-y-2">
{attachments.map(att => (
<div key={att.id} className="flex items-center justify-between p-2 hover:bg-slate-50 rounded-lg border border-slate-200 group">
<div className="flex items-center gap-2 overflow-hidden">
<FileText className="w-4 h-4 text-slate-400 flex-shrink-0" />
<div className="truncate">
<p className="text-sm font-medium text-slate-700 truncate">{att.fileName}</p>
<p className="text-[10px] text-slate-400">{formatBytes(att.fileSize)}</p>
</div>
</div>
<a href={`/api/tickets/${ticketId}/attachments?download=${att.id}`} download className="p-1.5 text-slate-500 hover:text-indigo-600 transition">
<Download className="w-4 h-4" />
</a>
</div>
))}
</div>
) : (
<p className="text-sm text-slate-500">Keine Dateien vorhanden.</p>
)}
</div>
{userType === 'TEAM' && (
<>
<div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 space-y-4">
<div>
<h3 className="font-semibold text-slate-800 mb-2 flex items-center gap-2">
<UserIcon className="w-4 h-4 text-slate-400" /> Bearbeiter
</h3>
<select className="w-full border border-slate-300 p-2 rounded-lg text-sm bg-white" value={ticket.assignedToId || ''} onChange={(e) => handleAssign(e.target.value)} disabled={isClosed}>
<option value="">Nicht zugewiesen</option>
{users.map(u => <option key={u.id} value={u.id}>{u.firstName} {u.lastName}</option>)}
</select>
</div>
<div>
<h3 className="font-semibold text-slate-800 mb-2 flex items-center gap-2">
<AlertTriangle className="w-4 h-4 text-slate-400" /> Priorität
</h3>
<select className="w-full border border-slate-300 p-2 rounded-lg text-sm bg-white" value={ticket.priority} onChange={(e) => handleChangePriority(e.target.value)} disabled={isClosed}>
<option value="LOW">Niedrig</option>
<option value="MEDIUM">Mittel</option>
<option value="HIGH">Hoch</option>
<option value="CRITICAL">Kritisch</option>
</select>
</div>
</div>
{!isClosed && (
<div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100">
<h3 className="font-semibold text-slate-800 mb-4">Aktionen</h3>
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<button onClick={() => openModal('addTime')} className="bg-indigo-50 text-indigo-700 border border-indigo-200 px-4 py-2.5 rounded-lg text-sm font-medium"><Clock className="w-4 h-4" /> Zeit buchen</button>
<button onClick={() => openModal('addNote')} className="bg-slate-50 text-slate-700 border border-slate-200 px-4 py-2.5 rounded-lg text-sm font-medium"><StickyNote className="w-4 h-4" /> Int. Notiz</button>
</div>
<button onClick={() => openModal('close')} className="w-full bg-emerald-600 text-white px-4 py-2.5 rounded-lg text-sm font-medium shadow-sm"><CheckCircle className="w-4 h-4" /> Ticket abschließen</button>
</div>
</div>
)}
<div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100">
<h3 className="font-semibold text-slate-800 mb-4 flex items-center gap-2"><Activity className="w-5 h-5 text-slate-500" /> Interne Chronik</h3>
<div className="space-y-6">
{timelineItems.map((item: any) => (
<div key={`${item.type}-${item.id}`} className={`border-l-2 pl-4 relative ${item.type === 'time' ? 'border-amber-400' : 'border-indigo-400'}`}>
<p className="font-semibold text-slate-800 text-sm">{item.type === 'time' ? `Zeit: ${item.durationMins} Min.` : 'Interne Notiz'}</p>
<p className="text-sm text-slate-600 mt-1">{item.type === 'time' ? item.description : item.content}</p>
<div className="text-[10px] text-slate-400 mt-1">{new Date(item.createdAt).toLocaleString('de-DE')} {item.user?.firstName}</div>
</div>
))}
</div>
</div>
</>
)}
</div>
</div>
{showModal && (
<div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center z-50 backdrop-blur-sm p-4">
<div className="bg-white p-8 rounded-2xl shadow-xl max-w-md w-full">
<h2 className="text-xl font-bold text-slate-900 mb-2">{modalMode === 'addNote' ? 'Interne Notiz' : 'Zeit erfassen'}</h2>
<form onSubmit={handleModalSubmit} className="space-y-4 mt-6">
{modalMode !== 'addNote' && (
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Dauer (Min.) *</label>
<input type="number" step="15" required value={modalData.durationMins} onChange={(e) => setModalData({...modalData, durationMins: parseInt(e.target.value)})} className="w-full border border-slate-300 p-2.5 rounded-xl focus-ring outline-none transition-all" />
</div>
)}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Inhalt *</label>
{/* HIER WAR DER FEHLER: setModalData statt setFormData */}
<textarea required value={modalMode === 'addNote' ? modalData.content : modalData.description} onChange={(e) => setModalData(modalMode === 'addNote' ? {...modalData, content: e.target.value} : {...modalData, description: e.target.value})} className="w-full border border-slate-300 p-2.5 rounded-xl focus-ring outline-none h-24 resize-none transition-all" />
</div>
<div className="flex justify-end gap-3 mt-6">
<button type="button" onClick={() => setShowModal(false)} className="px-4 py-2.5 text-slate-600">Abbrechen</button>
<button type="submit" className="bg-indigo-600 text-white px-6 py-2.5 rounded-lg">Speichern</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}
+191
View File
@@ -0,0 +1,191 @@
// /opt/erp-system/app/tickets/page.tsx
'use client';
import { useState, useEffect } from 'react';
import { useSession } from "next-auth/react";
import { Ticket as TicketIcon, Plus, X } from 'lucide-react';
import { getStatusBadge, getPriorityBadge } from '../components/AppShell';
import { useToast } from '../components/ToastProvider';
export default function TicketsPage() {
const { data: session } = useSession();
const [tickets, setTickets] = useState<any[]>([]);
const [customers, setCustomers] = useState<any[]>([]);
const [filter, setFilter] = useState<'ALL' | 'MINE' | 'OPEN'>('ALL');
// States für das Formular
const [showForm, setShowForm] = useState(false);
const [formData, setFormData] = useState({ title: '', description: '', customerId: '', priority: 'MEDIUM' });
const { toast } = useToast();
useEffect(() => {
fetchTickets();
fetchCustomers();
}, []);
const fetchTickets = async () => {
const res = await fetch('/api/tickets');
if (res.ok) setTickets(await res.json());
};
const fetchCustomers = async () => {
const res = await fetch('/api/customers');
if (res.ok) {
const data = await res.json();
setCustomers(data);
if (data.length > 0) {
setFormData(prev => ({ ...prev, customerId: data[0].id.toString() }));
}
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const res = await fetch('/api/tickets', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
if (res.ok) {
setShowForm(false);
setFormData({ title: '', description: '', customerId: customers[0]?.id.toString() || '', priority: 'MEDIUM' });
fetchTickets();
toast('Ticket erfolgreich erstellt', 'success');
} else {
toast('Fehler beim Erstellen des Tickets', 'error');
}
};
// getStatusBadge is imported from AppShell
// Filter-Logik
const filteredTickets = tickets.filter(t => {
if (filter === 'OPEN') return t.status === 'OPEN' || t.status === 'IN_PROGRESS';
if (filter === 'MINE') return t.assignedToId === parseInt((session?.user as any)?.id);
return true;
});
return (
<div className="max-w-7xl mx-auto space-y-6 animate-fade-in-up">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
<TicketIcon className="w-6 h-6 text-indigo-600" /> Ticketsystem
</h1>
<button onClick={() => setShowForm(!showForm)} className="bg-indigo-600 text-white px-4 py-2 rounded-lg font-medium shadow-sm flex items-center gap-2 hover:bg-indigo-700 transition">
{showForm ? <X className="w-4 h-4" /> : <Plus className="w-4 h-4" />} {showForm ? 'Abbrechen' : 'Neues Ticket'}
</button>
</div>
{/* Neues Ticket Formular */}
{showForm && (
<div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 animate-in fade-in slide-in-from-top-4">
<h2 className="text-lg font-semibold text-slate-800 mb-4">Neues Ticket erfassen</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="md:col-span-2">
<label className="block text-sm font-medium text-slate-700 mb-1">Betreff *</label>
<input type="text" required className="w-full border border-slate-300 p-2.5 rounded-xl focus-ring outline-none transition-all" value={formData.title} onChange={e => setFormData({...formData, title: e.target.value})} placeholder="Kurze Beschreibung des Problems..." />
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-slate-700 mb-1">Kunde *</label>
<select required className="w-full border border-slate-300 p-2.5 rounded-xl focus-ring outline-none bg-white transition-all" value={formData.customerId} onChange={e => setFormData({...formData, customerId: e.target.value})}>
{customers.map(c => (
<option key={c.id} value={c.id}>{c.companyName || `${c.firstName} ${c.lastName}`}</option>
))}
</select>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-slate-700 mb-1">Priorität *</label>
<select required className="w-full border border-slate-300 p-2.5 rounded-xl focus-ring outline-none bg-white transition-all" value={formData.priority} onChange={e => setFormData({...formData, priority: e.target.value})}>
<option value="LOW">Niedrig</option>
<option value="MEDIUM">Mittel</option>
<option value="HIGH">Hoch</option>
<option value="CRITICAL">Kritisch</option>
</select>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-slate-700 mb-1">Details *</label>
<textarea required className="w-full border border-slate-300 p-2.5 rounded-xl focus-ring outline-none h-32 resize-none transition-all" value={formData.description} onChange={e => setFormData({...formData, description: e.target.value})} placeholder="Ausführliche Problembeschreibung..." />
</div>
</div>
<div className="flex justify-end pt-2">
<button type="submit" className="bg-slate-900 text-white px-6 py-2.5 rounded-lg hover:bg-slate-800 transition font-medium">Ticket erstellen</button>
</div>
</form>
</div>
)}
{/* Filter Tabs */}
<div className="flex border-b border-slate-200 gap-6">
{[
{ id: 'ALL', label: 'Alle Tickets' },
{ id: 'MINE', label: 'Meine Tickets' },
{ id: 'OPEN', label: 'Nur Offene' }
].map(tab => (
<button
key={tab.id}
onClick={() => setFilter(tab.id as any)}
className={`pb-3 text-sm font-medium transition-colors relative ${filter === tab.id ? 'text-indigo-600' : 'text-slate-500 hover:text-slate-700'}`}
>
{tab.label}
{filter === tab.id && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600 animate-in fade-in duration-300"></div>}
</button>
))}
</div>
{/* Datentabelle */}
<div className="bg-white rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 overflow-hidden">
<table className="w-full text-left text-sm">
<thead className="bg-slate-50 text-slate-600 font-medium border-b border-slate-200">
<tr>
<th className="py-4 px-6">ID</th>
<th className="py-4 px-6">Titel & Kunde</th>
<th className="py-4 px-6">Bearbeiter</th>
<th className="py-4 px-6">Status & Prio</th>
<th className="py-4 px-6 text-right">Aktion</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{filteredTickets.map(t => (
<tr key={t.id} className="hover:bg-slate-50/80 transition-colors border-b border-slate-50 last:border-0 group">
<td className="py-4 px-6 font-mono text-slate-400">#{t.id.toString().padStart(5, '0')}</td>
<td className="py-4 px-6">
<div className="flex flex-col">
<span className="font-semibold text-slate-900">{t.title}</span>
<span className="text-slate-500 text-xs">{t.customer.companyName || `${t.customer.firstName} ${t.customer.lastName}`}</span>
</div>
</td>
<td className="py-4 px-6">
{t.assignedTo ? (
<span className="flex items-center gap-1.5 text-slate-700">
<div className="w-6 h-6 rounded-full bg-indigo-100 flex items-center justify-center text-[10px] font-bold text-indigo-700 border border-indigo-200">
{t.assignedTo.firstName[0]}
</div>
{t.assignedTo.firstName} {t.assignedTo.lastName}
</span>
) : <span className="text-slate-400 italic text-xs">Unzugewiesen</span>}
</td>
<td className="py-4 px-6">
<div className="flex flex-col gap-2 items-start">
{getStatusBadge(t.status)}
{getPriorityBadge(t.priority)}
</div>
</td>
<td className="py-4 px-6 text-right">
<a href={`/tickets/${t.id}`} className="text-indigo-600 font-medium hover:text-indigo-800">Akte öffnen</a>
</td>
</tr>
))}
{filteredTickets.length === 0 && (
<tr>
<td colSpan={5} className="py-8 text-center text-slate-500">Keine Tickets in dieser Ansicht gefunden.</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}