Files
panel/src/app/contacts/page.js

616 lines
21 KiB
JavaScript

"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/Card";
import Button from "@/components/ui/Button";
import Badge from "@/components/ui/Badge";
import ContactForm from "@/components/ContactForm";
export default function ContactsPage() {
const router = useRouter();
const { data: session, status } = useSession();
const [contacts, setContacts] = useState([]);
const [filteredContacts, setFilteredContacts] = useState([]);
const [loading, setLoading] = useState(true);
const [showForm, setShowForm] = useState(false);
const [editingContact, setEditingContact] = useState(null);
const [searchTerm, setSearchTerm] = useState("");
const [typeFilter, setTypeFilter] = useState("all");
const [stats, setStats] = useState(null);
const [selectedContact, setSelectedContact] = useState(null);
const [contactProjects, setContactProjects] = useState([]);
const [loadingProjects, setLoadingProjects] = useState(false);
// Redirect if not authenticated
useEffect(() => {
if (status === "unauthenticated") {
router.push("/auth/signin");
}
}, [status, router]);
// Fetch contacts
useEffect(() => {
fetchContacts();
fetchStats();
}, []);
// Filter contacts
useEffect(() => {
let filtered = contacts;
// Filter by search term
if (searchTerm) {
const search = searchTerm.toLowerCase();
filtered = filtered.filter(
(contact) =>
contact.name?.toLowerCase().includes(search) ||
contact.phone?.toLowerCase().includes(search) ||
contact.email?.toLowerCase().includes(search) ||
contact.company?.toLowerCase().includes(search)
);
}
// Filter by type
if (typeFilter !== "all") {
filtered = filtered.filter(
(contact) => contact.contact_type === typeFilter
);
}
setFilteredContacts(filtered);
}, [contacts, searchTerm, typeFilter]);
async function fetchContacts() {
try {
const response = await fetch("/api/contacts?is_active=true");
if (response.ok) {
const data = await response.json();
console.log('Fetched contacts:', data);
setContacts(data);
} else {
console.error('Failed to fetch contacts, status:', response.status);
}
} catch (error) {
console.error("Error fetching contacts:", error);
} finally {
setLoading(false);
}
}
async function fetchStats() {
try {
const response = await fetch("/api/contacts?stats=true");
if (response.ok) {
const data = await response.json();
setStats(data);
}
} catch (error) {
console.error("Error fetching stats:", error);
}
}
async function handleDelete(contactId) {
if (!confirm("Czy na pewno chcesz usunąć ten kontakt?")) return;
try {
const response = await fetch(`/api/contacts/${contactId}`, {
method: "DELETE",
});
if (response.ok) {
fetchContacts();
fetchStats();
}
} catch (error) {
console.error("Error deleting contact:", error);
alert("Nie udało się usunąć kontaktu");
}
}
function handleEdit(contact) {
setEditingContact(contact);
setShowForm(true);
}
async function handleViewDetails(contact) {
setSelectedContact(contact);
setLoadingProjects(true);
try {
// Fetch projects linked to this contact
const response = await fetch(`/api/contacts/${contact.contact_id}/projects`);
if (response.ok) {
const data = await response.json();
setContactProjects(data.projects || []);
}
} catch (error) {
console.error("Error fetching contact projects:", error);
setContactProjects([]);
} finally {
setLoadingProjects(false);
}
}
function closeDetails() {
setSelectedContact(null);
setContactProjects([]);
}
function handleFormSave(contact) {
setShowForm(false);
setEditingContact(null);
fetchContacts();
fetchStats();
}
function handleFormCancel() {
setShowForm(false);
setEditingContact(null);
}
const getContactTypeBadge = (type) => {
const types = {
project: { label: "Projekt", variant: "primary" },
contractor: { label: "Wykonawca", variant: "warning" },
office: { label: "Urząd", variant: "info" },
supplier: { label: "Dostawca", variant: "success" },
other: { label: "Inny", variant: "secondary" },
};
return types[type] || types.other;
};
if (status === "loading" || loading) {
return (
<div className="flex justify-center items-center min-h-screen">
<div className="text-gray-600">Ładowanie...</div>
</div>
);
}
if (showForm) {
return (
<div className="container mx-auto px-4 py-8">
<ContactForm
initialData={editingContact}
onSave={handleFormSave}
onCancel={handleFormCancel}
/>
</div>
);
}
return (
<div className="container mx-auto px-4 py-8">
{/* Header */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Kontakty</h1>
<p className="text-gray-600 mt-1">
Zarządzaj kontaktami do projektów i współpracy
</p>
</div>
<Button onClick={() => setShowForm(true)}>
<svg
className="w-5 h-5 mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 4v16m8-8H4"
/>
</svg>
Dodaj kontakt
</Button>
</div>
{/* Stats */}
{stats && (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-gray-900">
{stats.total_contacts}
</div>
<div className="text-sm text-gray-600">Wszystkie</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-blue-600">
{stats.project_contacts}
</div>
<div className="text-sm text-gray-600">Projekty</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-orange-600">
{stats.contractor_contacts}
</div>
<div className="text-sm text-gray-600">Wykonawcy</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-purple-600">
{stats.office_contacts}
</div>
<div className="text-sm text-gray-600">Urzędy</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-green-600">
{stats.supplier_contacts}
</div>
<div className="text-sm text-gray-600">Dostawcy</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-gray-600">
{stats.other_contacts}
</div>
<div className="text-sm text-gray-600">Inne</div>
</CardContent>
</Card>
</div>
)}
{/* Filters */}
<Card className="mb-6">
<CardContent className="p-4">
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1">
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Szukaj po nazwie, telefonie, email lub firmie..."
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="all">Wszystkie typy</option>
<option value="project">Projekty</option>
<option value="contractor">Wykonawcy</option>
<option value="office">Urzędy</option>
<option value="supplier">Dostawcy</option>
<option value="other">Inne</option>
</select>
</div>
</CardContent>
</Card>
{/* Contacts List */}
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Kontakt
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Firma / Stanowisko
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Telefon
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Email
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Akcje
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{filteredContacts.length === 0 ? (
<tr>
<td colSpan="5" className="px-4 py-12 text-center text-gray-500">
{searchTerm || typeFilter !== "all"
? "Nie znaleziono kontaktów"
: "Brak kontaktów. Dodaj pierwszy kontakt."}
</td>
</tr>
) : (
filteredContacts.map((contact) => {
const typeBadge = getContactTypeBadge(contact.contact_type);
return (
<tr key={contact.contact_id} className="hover:bg-gray-50 transition-colors">
<td className="px-4 py-3">
<div className="flex items-center gap-2 cursor-pointer" onClick={() => handleViewDetails(contact)}>
<div>
<div className="flex items-center gap-2">
<h3 className="font-semibold text-gray-900 text-sm hover:text-blue-600 transition-colors">
{contact.name}
</h3>
<Badge variant={typeBadge.variant} size="sm" className="text-xs">
{typeBadge.label}
</Badge>
</div>
{contact.project_count > 0 && (
<span className="inline-flex items-center gap-1 text-xs text-gray-500 mt-1">
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
</svg>
{contact.project_count} {contact.project_count === 1 ? "projekt" : "projektów"}
</span>
)}
</div>
</div>
</td>
<td className="px-4 py-3">
<div className="text-sm text-gray-600">
{contact.company && (
<div className="flex items-center gap-1">
<span>{contact.company}</span>
{contact.position && <span className="text-gray-500 ml-1"> {contact.position}</span>}
</div>
)}
{!contact.company && contact.position && (
<div>{contact.position}</div>
)}
</div>
</td>
<td className="px-4 py-3">
{contact.phone && (
<div className="space-y-1">
{(() => {
// Handle multiple phones (could be comma-separated or JSON)
let phones = [];
try {
// Try to parse as JSON array first
const parsed = JSON.parse(contact.phone);
phones = Array.isArray(parsed) ? parsed : [contact.phone];
} catch {
// Fall back to comma-separated string
phones = contact.phone.split(',').map(p => p.trim()).filter(p => p);
}
const primaryPhone = phones[0];
const additionalPhones = phones.slice(1);
return (
<>
<a
href={`tel:${primaryPhone}`}
className="flex items-center gap-1 text-sm text-blue-600 hover:underline"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
</svg>
{primaryPhone}
</a>
{additionalPhones.length > 0 && (
<div className="text-xs text-gray-500 pl-5">
{additionalPhones.length === 1 ? (
<a
href={`tel:${additionalPhones[0]}`}
className="text-blue-600 hover:underline"
>
{additionalPhones[0]}
</a>
) : (
<span>+{additionalPhones.length} więcej</span>
)}
</div>
)}
</>
);
})()}
</div>
)}
</td>
<td className="px-4 py-3">
{contact.email && (
<a
href={`mailto:${contact.email}`}
className="flex items-center gap-1 text-sm text-blue-600 hover:underline"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
<span className="truncate max-w-[200px]">{contact.email}</span>
</a>
)}
</td>
<td className="px-4 py-3 text-right">
<div className="flex justify-end gap-1">
<Button
size="sm"
variant="secondary"
onClick={(e) => {
e.stopPropagation();
handleEdit(contact);
}}
className="px-2 py-1"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</Button>
<Button
size="sm"
variant="danger"
onClick={(e) => {
e.stopPropagation();
handleDelete(contact.contact_id);
}}
className="px-2 py-1"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</Button>
</div>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
{/* Contact Details Modal */}
{selectedContact && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50" onClick={closeDetails}>
<Card className="max-w-2xl w-full max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
<CardHeader className="border-b">
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-2xl">{selectedContact.name}</CardTitle>
<div className="mt-2">
<Badge variant={getContactTypeBadge(selectedContact.contact_type).variant}>
{getContactTypeBadge(selectedContact.contact_type).label}
</Badge>
</div>
</div>
<Button variant="ghost" size="sm" onClick={closeDetails}>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</Button>
</div>
</CardHeader>
<CardContent className="p-6 space-y-6">
{/* Contact Information */}
<div>
<h3 className="font-semibold text-gray-900 mb-3">Informacje kontaktowe</h3>
<div className="space-y-2">
{selectedContact.phone && (() => {
let phones = [];
try {
const parsed = JSON.parse(selectedContact.phone);
phones = Array.isArray(parsed) ? parsed : [selectedContact.phone];
} catch {
phones = selectedContact.phone.split(',').map(p => p.trim()).filter(p => p);
}
return phones.map((phone, index) => (
<div key={index} className="flex items-center gap-3">
<svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
</svg>
<a href={`tel:${phone}`} className="text-blue-600 hover:underline">
{phone}
</a>
{index === 0 && phones.length > 1 && (
<span className="text-xs text-gray-500">(główny)</span>
)}
</div>
));
})()}
{selectedContact.email && (
<div className="flex items-center gap-3">
<svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
<a href={`mailto:${selectedContact.email}`} className="text-blue-600 hover:underline">
{selectedContact.email}
</a>
</div>
)}
{selectedContact.company && (
<div className="flex items-center gap-3">
<span className="text-xl">🏢</span>
<span className="text-gray-700">
{selectedContact.company}
{selectedContact.position && `${selectedContact.position}`}
</span>
</div>
)}
{!selectedContact.company && selectedContact.position && (
<div className="flex items-center gap-3">
<span className="text-xl">💼</span>
<span className="text-gray-700">{selectedContact.position}</span>
</div>
)}
</div>
</div>
{/* Notes */}
{selectedContact.notes && (
<div>
<h3 className="font-semibold text-gray-900 mb-2">Notatki</h3>
<p className="text-gray-600 text-sm whitespace-pre-wrap bg-gray-50 p-3 rounded">
{selectedContact.notes}
</p>
</div>
)}
{/* Linked Projects */}
<div>
<h3 className="font-semibold text-gray-900 mb-3">
Powiązane projekty ({contactProjects.length})
</h3>
{loadingProjects ? (
<div className="text-center py-4 text-gray-500">Ładowanie projektów...</div>
) : contactProjects.length === 0 ? (
<p className="text-gray-500 text-sm">Brak powiązanych projektów</p>
) : (
<div className="space-y-2">
{contactProjects.map((project) => (
<div
key={project.project_id}
className="flex items-center justify-between p-3 bg-gray-50 hover:bg-gray-100 rounded cursor-pointer transition-colors"
onClick={() => router.push(`/projects/${project.project_id}`)}
>
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="font-medium text-gray-900">{project.project_name}</span>
{project.is_primary && (
<Badge variant="primary" size="sm">Główny kontakt</Badge>
)}
</div>
{project.relationship_type && (
<span className="text-xs text-gray-500">{project.relationship_type}</span>
)}
</div>
<svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</div>
))}
</div>
)}
</div>
{/* Action Buttons */}
<div className="flex gap-3 pt-4 border-t">
<Button
variant="secondary"
onClick={() => {
closeDetails();
handleEdit(selectedContact);
}}
className="flex-1"
>
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
Edytuj kontakt
</Button>
<Button variant="ghost" onClick={closeDetails}>
Zamknij
</Button>
</div>
</CardContent>
</Card>
</div>
)}
</div>
);
}