/** * SpinClients.jsx - Słownik Klientów i Operatorów Telekomunikacyjnych (SPiN Enterprise UI) * Komponent dla platformy Multi-Tech Pro Field Service Manager (fsm.multi-tech.pro) * * Zgodny z estetyką NetWorks SPiN Enterprise: * - Srebrzysto-stalowy pasek tytułowy z pigułką SPiN oraz toolbar z przyciskami akcji * - Zwarty, beveled panel formularza z jasnoszarym gradientem (#f8fafc do #edf2f7) * - 3-kolumnowy układ kontrolek input ~26px z szablonami operatorów (Orange, TMPL, Play, Tauron, TELZAS, NetWorks) * - Gęsta siatka danych (SPiN Data Grid) z filtrami pod nagłówkami, sortowaniem i plakietkami operatorów * - Moduł zarządzania dedykowanymi uprawnieniami techników/użytkowników do klientów (Client Permissions) * - Eksport do CSV, powiadomienia Toast, pełna zgodność z React 18 & Babel Standalone */ (function(window) { 'use strict'; const { useState, useEffect, useMemo, useCallback, useRef } = React; // Wzorcowe szablony operatorów i klientów infrastrukturalnych Multi-Tech Pro const OPERATOR_TEMPLATES = [ { name: 'TELZAS Sp. z o.o.', code: 'TEL', nip: '8522384798', contact_person: 'Dział Realizacji Usług RTF', email: 'rtf@telzas.com', phone: '+48 94 345 88 00', notes: 'Umowa ramowa na serwis siłowni DC i wymiany baterii; fakturowanie wg protokołów PZ/ZZ' }, { name: 'Orange Polska S.A.', code: 'OPL', nip: '5260250995', contact_person: 'Koordynator Utrzymania Sieci OPL', email: 'fsm-kontakt@orange.com', phone: '+48 22 527 00 00', notes: 'Dostęp do stacji bazowych RAN/DWDM; rygorystyczne procedury BHP i zgłoszenia wstępu' }, { name: 'T-Mobile Polska S.A.', code: 'TMPL', nip: '5250001087', contact_person: 'Dyspozytor Techniczny RAN', email: 'utrzymanie@t-mobile.pl', phone: '+48 22 413 60 00', notes: 'Zlecenia prewencyjne zasilania i kompensacja mocy biernej KMBP; protokoły pomiarowe' }, { name: 'P4 Sp. z o.o. (Play)', code: 'P4', nip: '9512120077', contact_person: 'Koordynator Regionu P4', email: 'serwis-sieci@play.pl', phone: '+48 22 334 40 00', notes: 'Modernizacja systemów zasilania gwarantowanego 48V, audyty As-Built' }, { name: 'Tauron Dystrybucja S.A.', code: 'TKN', nip: '6110202860', contact_person: 'Wydział Pomiarów i Kompensacji', email: 'dystrybucja@tauron.pl', phone: '+48 32 303 03 03', notes: 'Odbiory kompensatorów tg phi i certyfikowane pomiary miernikiem UNI-T UT267B' }, { name: 'NetWorks! Sp. z o.o.', code: 'NW!', nip: '5252516480', contact_person: 'Centrum Zarządzania Siecią NetWorks!', email: 'noc@networks.pl', phone: '+48 22 555 55 55', notes: 'Współdzielona infrastruktura RAN Orange & T-Mobile; nadzór nad stacjami wieżowymi' }, { name: 'Polkomtel Sp. z o.o. (Plus)', code: 'PLUS', nip: '5271037727', contact_person: 'Nadzór Techniczny Plus', email: 'kontakt@plus.pl', phone: '+48 22 426 10 00', notes: 'Utrzymanie zasilania stacji bazowych i kontenerów telekomunikacyjnych' } ]; // Pomocnik stylizujący plakietkę operatora według oficjalnych barw brandowych function getOperatorBadgeStyle(code, name) { const raw = `${code || ''} ${name || ''}`.toUpperCase(); if (raw.includes('OPL') || raw.includes('ORANGE')) { return { bg: 'linear-gradient(135deg, #ff6600 0%, #ea580c 100%)', border: '#c2410c', color: '#ffffff', label: code || 'OPL', brand: 'Orange' }; } if (raw.includes('TMPL') || raw.includes('T-MOBILE') || raw.includes('TMOBILE') || raw.includes('T-MOB')) { return { bg: 'linear-gradient(135deg, #e20074 0%, #be123c 100%)', border: '#9f1239', color: '#ffffff', label: code || 'TMPL', brand: 'T-Mobile' }; } if (raw.includes('P4') || raw.includes('PLAY') || raw.includes('ILIAD')) { return { bg: 'linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%)', border: '#4c1d95', color: '#ffffff', label: code || 'P4', brand: 'Play' }; } if (raw.includes('TKN') || raw.includes('TAURON')) { return { bg: 'linear-gradient(135deg, #0284c7 0%, #0369a1 100%)', border: '#075985', color: '#ffffff', label: code || 'TKN', brand: 'Tauron' }; } if (raw.includes('PLUS') || raw.includes('PLK') || raw.includes('POLKOMTEL')) { return { bg: 'linear-gradient(135deg, #16a34a 0%, #15803d 100%)', border: '#14532d', color: '#ffffff', label: code || 'PLUS', brand: 'Plus' }; } if (raw.includes('TELZAS') || raw.includes('TEL')) { return { bg: 'linear-gradient(135deg, #0d9488 0%, #0f766e 100%)', border: '#115e59', color: '#ffffff', label: code || 'TEL', brand: 'TELZAS' }; } if (raw.includes('NW!') || raw.includes('NETWORKS') || raw.includes('NETWORK')) { return { bg: 'linear-gradient(135deg, #1d4ed8 0%, #1e3a8a 100%)', border: '#172554', color: '#ffffff', label: code || 'NW!', brand: 'NetWorks!' }; } if (raw.includes('PGE')) { return { bg: 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)', border: '#1e40af', color: '#ffffff', label: code || 'PGE', brand: 'PGE' }; } if (raw.includes('ENEA')) { return { bg: 'linear-gradient(135deg, #dc2626 0%, #991b1b 100%)', border: '#7f1d1d', color: '#ffffff', label: code || 'ENEA', brand: 'Enea' }; } if (raw.includes('EMITEL') || raw.includes('EMT')) { return { bg: 'linear-gradient(135deg, #4338ca 0%, #312e81 100%)', border: '#1e1b4b', color: '#ffffff', label: code || 'EMT', brand: 'Emitel' }; } return { bg: 'linear-gradient(135deg, #64748b 0%, #475569 100%)', border: '#334155', color: '#ffffff', label: code || (name ? name.slice(0, 4).toUpperCase() : 'KLIENT'), brand: name || 'Klient' }; } /** * Główny komponent SpinClients */ function SpinClients({ token = null, clients = [], users = [], clientPermissions = [], onSaveClient = null, onDeleteClient = null, onAddPermission = null, onDeletePermission = null, onRefresh = null, showToast = null }) { // Bezpieczne powiadomienia Toast const notify = useCallback((msg, type = 'info') => { if (typeof showToast === 'function') { showToast(msg, type); } else if (typeof window.showToast === 'function') { window.showToast(msg, type); } else { alert(`${type.toUpperCase()}: ${msg}`); } }, [showToast]); // Stan lokalny danych (gdy brak lub uzupełnienie z propsów) const [localClients, setLocalClients] = useState(clients && clients.length > 0 ? clients : []); const [localUsers, setLocalUsers] = useState(users && users.length > 0 ? users : []); const [localPermissions, setLocalPermissions] = useState(clientPermissions && clientPermissions.length > 0 ? clientPermissions : []); const [isLoading, setIsLoading] = useState(false); // Synchronizacja z przekazanymi propsami useEffect(() => { if (clients && clients.length > 0) { setLocalClients(clients); } }, [clients]); useEffect(() => { if (users && users.length > 0) { setLocalUsers(users); } }, [users]); useEffect(() => { if (clientPermissions && clientPermissions.length > 0) { setLocalPermissions(clientPermissions); } }, [clientPermissions]); // Automatyczne załadowanie klientów z API, jeśli lista startowa jest pusta const fetchApiData = useCallback(async () => { setIsLoading(true); try { const fetcher = window.apiFetch || (async (url, opts = {}, tkn = null) => { const sep = url.includes('?') ? '&' : '?'; const finalUrl = tkn ? `${url}${sep}token=${tkn}` : url; const headers = { ...(tkn ? { 'Authorization': `Bearer ${tkn}` } : {}), ...(opts.headers || {}) }; const r = await fetch(finalUrl, { ...opts, headers }); if (!r.ok) { const err = await r.json().catch(() => ({})); throw new Error(err.error || err.message || `Błąd serwera (${r.status})`); } return r.json(); }); const [cData, uData, cpData] = await Promise.all([ fetcher('/api/clients', {}, token).catch(() => null), fetcher('/api/auth/users', {}, token).catch(() => null), fetcher('/api/client-permissions', {}, token).catch(() => null) ]); if (Array.isArray(cData)) { setLocalClients(cData); } if (Array.isArray(uData)) { setLocalUsers(uData); } if (Array.isArray(cpData)) { setLocalPermissions(cpData); } } catch (err) { console.warn('SpinClients: Fetch fallback warning:', err); } finally { setIsLoading(false); } }, [token]); useEffect(() => { if ((!clients || clients.length === 0) && token) { fetchApiData(); } }, [token, clients, fetchApiData]); // Stan formularza klienta const initialFormState = { id: null, name: '', code: '', nip: '', contact_person: '', email: '', phone: '', notes: '' }; const [formVisible, setFormVisible] = useState(false); const [clientForm, setClientForm] = useState(initialFormState); const [isSaving, setIsSaving] = useState(false); // Stan formularza przypisywania uprawnień const [assignUserId, setAssignUserId] = useState(''); const [assignClientName, setAssignClientName] = useState(''); const [isAssigning, setIsAssigning] = useState(false); // Wyszukiwanie globalne i filtry kolumnowe const [globalSearch, setGlobalSearch] = useState(''); const [columnFilters, setColumnFilters] = useState({ name: '', code: '', nip: '', contact_person: '', email: '', phone: '' }); // Sortowanie const [sortConfig, setSortConfig] = useState({ key: 'name', direction: 'asc' }); // Wybrany wiersz klienta (podświetlenie) const [selectedClientId, setSelectedClientId] = useState(null); // Widok modułu uprawnień: 'badges' (pastylki wg użytkowników) vs 'table' (tabela) const [permViewMode, setPermViewMode] = useState('badges'); // Obsługa sortowania kolumn const handleSort = (key) => { setSortConfig(prev => { if (prev.key === key) { return { key, direction: prev.direction === 'asc' ? 'desc' : 'asc' }; } return { key, direction: 'asc' }; }); }; // Wypełnienie szablonem operatora const handleApplyTemplate = (tmpl) => { setClientForm(prev => ({ ...prev, name: tmpl.name, code: tmpl.code, nip: tmpl.nip, contact_person: tmpl.contact_person, email: tmpl.email, phone: tmpl.phone, notes: tmpl.notes })); setFormVisible(true); notify(`📋 Zastosowano wzorzec operatora: ${tmpl.name}`, 'info'); }; // Start edycji klienta const handleEditClient = (client) => { setClientForm({ id: client.id, name: client.name || '', code: client.code || '', nip: client.nip || '', contact_person: client.contact_person || '', email: client.email || '', phone: client.phone || '', notes: client.notes || '' }); setSelectedClientId(client.id); setFormVisible(true); }; // Anulowanie edycji const handleCancelForm = () => { setClientForm(initialFormState); setFormVisible(false); }; // Zapisanie klienta (Create / Update) const handleSaveSubmit = async (e) => { if (e) e.preventDefault(); if (!clientForm.name.trim()) { notify('Nazwa klienta / operatora jest wymagana!', 'warning'); return; } setIsSaving(true); try { if (typeof onSaveClient === 'function') { await onSaveClient(clientForm); } else { // Bezpośrednie wywołanie API jako solidny fallback const fetcher = window.apiFetch || fetch; const res = await (window.apiFetch ? fetcher('/api/clients', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(clientForm) }, token) : fetch('/api/clients' + (token ? `?token=${token}` : ''), { method: 'POST', headers: { 'Content-Type': 'application/json', ...(token ? { 'Authorization': `Bearer ${token}` } : {}) }, body: JSON.stringify(clientForm) }).then(r => r.json()) ); notify(res.message || 'Dane klienta zostały pomyślnie zapisane', 'success'); await fetchApiData(); } setClientForm(initialFormState); setFormVisible(false); if (typeof onRefresh === 'function') onRefresh(); } catch (err) { notify(err.message || 'Błąd podczas zapisywania klienta', 'error'); } finally { setIsSaving(false); } }; // Usunięcie klienta const handleDeleteClick = async (cid, cname) => { if (!window.confirm(`Czy na pewno chcesz bezpowrotnie usunąć klienta "${cname}" ze słownika?`)) { return; } try { if (typeof onDeleteClient === 'function') { await onDeleteClient(cid, cname); } else { const fetcher = window.apiFetch || fetch; const res = await (window.apiFetch ? fetcher(`/api/clients/${cid}`, { method: 'DELETE' }, token) : fetch(`/api/clients/${cid}` + (token ? `?token=${token}` : ''), { method: 'DELETE', headers: token ? { 'Authorization': `Bearer ${token}` } : {} }).then(r => r.json()) ); notify(res.message || `Klient "${cname}" został usunięty`, 'success'); await fetchApiData(); } if (selectedClientId === cid) setSelectedClientId(null); if (typeof onRefresh === 'function') onRefresh(); } catch (err) { notify(err.message || 'Błąd usuwania klienta', 'error'); } }; // Przypisanie uprawnienia do klienta const handleAssignSubmit = async (e) => { if (e) e.preventDefault(); if (!assignUserId) { notify('Wybierz użytkownika / technika z listy', 'warning'); return; } if (!assignClientName) { notify('Wybierz klienta ze słownika', 'warning'); return; } setIsAssigning(true); try { const payload = { user_id: parseInt(assignUserId, 10), client_name: assignClientName }; if (typeof onAddPermission === 'function') { await onAddPermission(payload); } else { const fetcher = window.apiFetch || fetch; const res = await (window.apiFetch ? fetcher('/api/client-permissions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }, token) : fetch('/api/client-permissions' + (token ? `?token=${token}` : ''), { method: 'POST', headers: { 'Content-Type': 'application/json', ...(token ? { 'Authorization': `Bearer ${token}` } : {}) }, body: JSON.stringify(payload) }).then(r => r.json()) ); notify(res.message || 'Uprawnienie zostało pomyślnie przydzielone', 'success'); await fetchApiData(); } setAssignClientName(''); if (typeof onRefresh === 'function') onRefresh(); } catch (err) { notify(err.message || 'Błąd przydzielania uprawnienia', 'error'); } finally { setIsAssigning(false); } }; // Usunięcie uprawnienia klienta const handleDeletePermissionClick = async (cpid, userLabel, clientLabel) => { if (!window.confirm(`Czy na pewno odebrać użytkownikowi dostęp do klienta "${clientLabel || ''}"?`)) { return; } try { if (typeof onDeletePermission === 'function') { await onDeletePermission(cpid); } else { const fetcher = window.apiFetch || fetch; const res = await (window.apiFetch ? fetcher(`/api/client-permissions/${cpid}`, { method: 'DELETE' }, token) : fetch(`/api/client-permissions/${cpid}` + (token ? `?token=${token}` : ''), { method: 'DELETE', headers: token ? { 'Authorization': `Bearer ${token}` } : {} }).then(r => r.json()) ); notify(res.message || 'Dostęp do klienta został odebrany', 'success'); await fetchApiData(); } if (typeof onRefresh === 'function') onRefresh(); } catch (err) { notify(err.message || 'Błąd odbierania uprawnienia', 'error'); } }; // Odświeżenie danych const handleManualRefresh = () => { if (typeof onRefresh === 'function') { onRefresh(); } fetchApiData(); notify('🔄 Odświeżono słownik klientów i uprawnienia', 'info'); }; // Eksport klientów do CSV const handleExportCsv = () => { if (localClients.length === 0) { notify('Brak danych klientów do eksportu', 'warning'); return; } const headers = ['ID', 'Nazwa Klienta', 'Kod', 'NIP', 'Osoba Kontaktowa', 'Email', 'Telefon', 'Notatki']; const rows = localClients.map(c => [ c.id || '', `"${(c.name || '').replace(/"/g, '""')}"`, `"${(c.code || '').replace(/"/g, '""')}"`, `"${(c.nip || '').replace(/"/g, '""')}"`, `"${(c.contact_person || '').replace(/"/g, '""')}"`, `"${(c.email || '').replace(/"/g, '""')}"`, `"${(c.phone || '').replace(/"/g, '""')}"`, `"${(c.notes || '').replace(/"/g, '""')}"` ]); const csvContent = '\uFEFF' + [headers.join(';'), ...rows.map(r => r.join(';'))].join('\r\n'); const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.setAttribute('href', url); link.setAttribute('download', `slownik_klientow_mtp_${new Date().toISOString().slice(0, 10)}.csv`); document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); notify('📥 Pomyślnie wygenerowano i pobrano plik CSV', 'success'); }; // Filtrowanie i sortowanie listy klientów const filteredClients = useMemo(() => { let result = [...localClients]; // Filtr globalny if (globalSearch.trim()) { const q = globalSearch.trim().toLowerCase(); result = result.filter(c => (c.name && c.name.toLowerCase().includes(q)) || (c.code && c.code.toLowerCase().includes(q)) || (c.nip && c.nip.toLowerCase().includes(q)) || (c.contact_person && c.contact_person.toLowerCase().includes(q)) || (c.email && c.email.toLowerCase().includes(q)) || (c.phone && c.phone.toLowerCase().includes(q)) || (c.notes && c.notes.toLowerCase().includes(q)) ); } // Filtry kolumnowe if (columnFilters.name.trim()) { const q = columnFilters.name.trim().toLowerCase(); result = result.filter(c => c.name && c.name.toLowerCase().includes(q)); } if (columnFilters.code.trim()) { const q = columnFilters.code.trim().toLowerCase(); result = result.filter(c => c.code && c.code.toLowerCase().includes(q)); } if (columnFilters.nip.trim()) { const q = columnFilters.nip.trim().toLowerCase(); result = result.filter(c => c.nip && c.nip.toLowerCase().includes(q)); } if (columnFilters.contact_person.trim()) { const q = columnFilters.contact_person.trim().toLowerCase(); result = result.filter(c => c.contact_person && c.contact_person.toLowerCase().includes(q)); } if (columnFilters.email.trim()) { const q = columnFilters.email.trim().toLowerCase(); result = result.filter(c => c.email && c.email.toLowerCase().includes(q)); } if (columnFilters.phone.trim()) { const q = columnFilters.phone.trim().toLowerCase(); result = result.filter(c => c.phone && c.phone.toLowerCase().includes(q)); } // Sortowanie if (sortConfig.key) { result.sort((a, b) => { let aVal = a[sortConfig.key] || ''; let bVal = b[sortConfig.key] || ''; if (typeof aVal === 'string') aVal = aVal.toLowerCase(); if (typeof bVal === 'string') bVal = bVal.toLowerCase(); if (aVal < bVal) return sortConfig.direction === 'asc' ? -1 : 1; if (aVal > bVal) return sortConfig.direction === 'asc' ? 1 : -1; return 0; }); } return result; }, [localClients, globalSearch, columnFilters, sortConfig]); // Grupowanie uprawnień według użytkownika dla widoku pastylek (Badges View) const permissionsByUser = useMemo(() => { const map = {}; localPermissions.forEach(cp => { const key = cp.user_id || cp.username || 'unknown'; if (!map[key]) { map[key] = { userId: cp.user_id, username: cp.username || `Użytkownik #${cp.user_id}`, email: cp.email || '-', items: [] }; } map[key].items.push(cp); }); return Object.values(map); }, [localPermissions]); // Czy aktywne są jakiekolwiek filtry kolumnowe const hasActiveFilters = useMemo(() => { return Object.values(columnFilters).some(v => v.trim() !== '') || globalSearch.trim() !== ''; }, [columnFilters, globalSearch]); const handleClearFilters = () => { setGlobalSearch(''); setColumnFilters({ name: '', code: '', nip: '', contact_person: '', email: '', phone: '' }); }; return (
| # | handleSort('name')} className="spin-clients-header-th" style={{ minWidth: '180px' }}> Nazwa Klienta / Operatora {sortConfig.key === 'name' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : '↕'} | handleSort('code')} className="spin-clients-header-th" style={{ minWidth: '90px' }}> Kod {sortConfig.key === 'code' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : '↕'} | handleSort('nip')} className="spin-clients-header-th" style={{ minWidth: '110px' }}> NIP {sortConfig.key === 'nip' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : '↕'} | handleSort('contact_person')} className="spin-clients-header-th" style={{ minWidth: '160px' }}> Koordynator / Kontakt {sortConfig.key === 'contact_person' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : '↕'} | handleSort('email')} className="spin-clients-header-th" style={{ minWidth: '160px' }}> Adres E-mail {sortConfig.key === 'email' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : '↕'} | handleSort('phone')} className="spin-clients-header-th" style={{ minWidth: '120px' }}> Telefon {sortConfig.key === 'phone' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : '↕'} | Notatki / Umowa | Akcje |
|---|---|---|---|---|---|---|---|---|
| {filteredClients.length} | setColumnFilters({ ...columnFilters, name: e.target.value })} /> | setColumnFilters({ ...columnFilters, code: e.target.value })} /> | setColumnFilters({ ...columnFilters, nip: e.target.value })} /> | setColumnFilters({ ...columnFilters, contact_person: e.target.value })} /> | setColumnFilters({ ...columnFilters, email: e.target.value })} /> | setColumnFilters({ ...columnFilters, phone: e.target.value })} /> | — | {hasActiveFilters && ( )} |
|
🏢
Brak klientów spełniających kryteria filtrowania
{localClients.length === 0 ?
'Słownik jest aktualnie pusty. Użyj przycisku "➕ Nowy Klient" lub kliknij jeden z szablonów powyżej.' :
'Spróbuj zresetować aktywne filtry w nagłówkach kolumn.'
}
{hasActiveFilters && (
)}
|
||||||||
| {idx + 1} | {/* Nazwa Klienta */}{client.name} | {/* Plakietka Kodu Operatora z barwami brandowymi */}{badge.label} | {/* NIP */}{client.nip || '—'} | {/* Koordynator / Kontakt */}{client.contact_person || '—'} | {/* E-mail */}{client.email ? ( e.stopPropagation()} > ✉️ {client.email} ) : ( — )} | {/* Telefon */}{client.phone ? ( e.stopPropagation()} > 📞 {client.phone} ) : ( — )} | {/* Notatki */}{client.notes || '—'} | {/* Akcje */}
|
| # | Użytkownik / Technik | Adres E-mail | Przypisany Klient / Operator | Data Przypisania | Akcje |
|---|---|---|---|---|---|
| Brak zarejestrowanych dedykowanych przypisań uprawnień. | |||||
| {idx + 1} | {cp.username} | {cp.email || '—'} | {cp.client_name} | {cp.created_at ? new Date(cp.created_at).toLocaleDateString('pl-PL') : '—'} | |