/** * ============================================================================== * Multi-Tech Pro FSM - NetWorks SPiN Edit Project & Order Correction Modal * Plik: SpinEditOrderModal.jsx * Lokalizacja: /public/js/SpinEditOrderModal.jsx * Moduł: Szczegóły & Korekta Zlecenia (SPiN Master Order Details & Correction) * Rola: Subagent 3 - SPiN Edit Project & Order Correction Modal Specialist * Wersja: 2.1.0 (Production Enterprise NetWorks SPiN Release) * ============================================================================== * Zastępuje stary, ciemnogranatowy blok '#0f172a' nowoczesnym, eleganckim, * beveled jasnoszarym interfejsem operatorskim NetWorks SPiN zgodnym ze stylem telco. */ (function(window) { const { useState, useEffect, useMemo, useCallback, useRef } = React; // Bezpieczny klient API z obsługą tokenu autoryzacyjnego const fetchApi = window.apiFetch || (async (url, options = {}, token = null) => { const sep = url.includes('?') ? '&' : '?'; const fullUrl = token ? `${url}${sep}token=${token}` : url; const defaultHeaders = token ? { 'Authorization': `Bearer ${token}` } : {}; const res = await fetch(fullUrl, { ...options, headers: { ...defaultHeaders, ...(options.headers || {}) } }); if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || `Błąd serwera (${res.status})`); } return res.json(); }); // Pomocnik formatowania daty w języku polskim function formatDatePl(dateStr) { if (!dateStr) return 'Brak'; try { const d = new Date(dateStr); if (isNaN(d.getTime())) return dateStr; return d.toLocaleString('pl-PL', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); } catch (e) { return dateStr; } } // Identyfikacja kolorystyczna operatorów telco function getClientBadgeStyle(clientName) { const c = (clientName || '').toUpperCase(); if (c.includes('ORANGE')) return { bg: '#ff7900', text: '#ffffff', border: '#e66d00', icon: '🍊' }; if (c.includes('T-MOBILE') || c.includes('TMOBILE')) return { bg: '#e20074', text: '#ffffff', border: '#b8005f', icon: '📱' }; if (c.includes('PLAY') || c.includes('P4')) return { bg: '#5c068c', text: '#ffffff', border: '#420366', icon: '🟣' }; if (c.includes('PLUS') || c.includes('POLKOMTEL')) return { bg: '#008b3e', text: '#ffffff', border: '#006c30', icon: '🟢' }; if (c.includes('NETWORKS')) return { bg: '#002d62', text: '#ffffff', border: '#001e42', icon: '📡' }; if (c.includes('TELZAS')) return { bg: '#0284c7', text: '#ffffff', border: '#0369a1', icon: '⚡' }; if (c.includes('EMITEL')) return { bg: '#004b97', text: '#ffffff', border: '#00356b', icon: '🗼' }; if (c.includes('DELTA')) return { bg: '#059669', text: '#ffffff', border: '#047857', icon: '🔋' }; if (c.includes('ELTEK')) return { bg: '#d97706', text: '#ffffff', border: '#b45309', icon: '🔌' }; if (c.includes('TAURON')) return { bg: '#008542', text: '#ffffff', border: '#006633', icon: '⚡' }; return { bg: '#015ea4', text: '#ffffff', border: '#004880', icon: '🏢' }; } // Predefiniowana lista typów prac technicznych const STANDARD_PROJECT_TYPES = [ 'Wymiana baterii 48V (Zasilanie DC)', 'Kompensacja mocy biernej KMBP', 'Modernizacja siłowni DC', 'Przegląd okresowy SLA', 'Montaż i konfiguracja prostowników', 'Awaria zasilania DC (Interwencja pilna)', 'Audyt techniczny i inwentaryzacja', 'Pomiary odbiorcze i tangens phi', 'Instalacja aparatury klimatyzacji HVAC', 'Inne prace instalacyjno-serwisowe' ]; // Domyślna lista operatorów / klientów słownikowych const DEFAULT_CLIENTS_LIST = [ { id: 'c-1', name: 'TELZAS', code: 'TEL' }, { id: 'c-2', name: 'Orange Polska', code: 'OPL' }, { id: 'c-3', name: 'T-Mobile Polska', code: 'TMP' }, { id: 'c-4', name: 'Play (P4)', code: 'P4' }, { id: 'c-5', name: 'Plus (Polkomtel)', code: 'PLS' }, { id: 'c-6', name: 'NetWorks!', code: 'NW!' }, { id: 'c-7', name: 'Emitel', code: 'EMT' }, { id: 'c-8', name: 'Delta Electronics', code: 'DEL' }, { id: 'c-9', name: 'Eltek', code: 'ELT' }, { id: 'c-10', name: 'Tauron Dystrybucja', code: 'TAU' } ]; /** * Główny komponent okna modalnego szczegółów i korekty zlecenia w stylu NetWorks SPiN */ function SpinEditOrderModal({ token, project, getProjectStatusBadge, onClose, onUpdated, onDeleted, showToast }) { if (!project) return null; // Bezpieczny system powiadomień Toast const notify = useCallback((message, type = 'info') => { if (typeof showToast === 'function') { showToast(message, type); } else if (typeof window.showToast === 'function') { window.showToast(message, type); } else { alert(message); } }, [showToast]); // ─── STANY FORMULARZA ──────────────────────────────────────────────────────── const [name, setName] = useState(project.name || project.title || ''); const [clientName, setClientName] = useState(project.client_name || project.target_client || 'TELZAS'); const [customClient, setCustomClient] = useState(''); const [objectNumber, setObjectNumber] = useState(project.object_number || ''); const [location, setLocation] = useState(project.location || ''); const [latitude, setLatitude] = useState(project.latitude !== undefined && project.latitude !== null ? project.latitude : ''); const [longitude, setLongitude] = useState(project.longitude !== undefined && project.longitude !== null ? project.longitude : ''); const [status, setStatus] = useState(project.status || 'DRAFT'); const [priority, setPriority] = useState(project.priority || 'NORMAL'); const [projectType, setProjectType] = useState(project.project_type || project.order_template || 'Wymiana baterii 48V (Zasilanie DC)'); const [plannedCompletionDate, setPlannedCompletionDate] = useState(project.planned_completion_date || ''); const [completionDate, setCompletionDate] = useState(project.completion_date || ''); const [remarks, setRemarks] = useState(project.remarks || ''); const [description, setDescription] = useState(project.description || ''); // Przypisani pracownicy const [workers, setWorkers] = useState([]); const [selectedWorkers, setSelectedWorkers] = useState(() => { try { const arr = JSON.parse(project.assigned_workers_json || '[]'); return Array.isArray(arr) ? arr : []; } catch (e) { return []; } }); // Słowniki i ładowanie const [clients, setClients] = useState(DEFAULT_CLIENTS_LIST); const [loadingLookup, setLoadingLookup] = useState(false); const [loadingGps, setLoadingGps] = useState(false); const [saving, setSaving] = useState(false); // Klawisz Escape do zamykania useEffect(() => { const handleKeyDown = (e) => { if (e.key === 'Escape') { onClose(); } }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); }, [onClose]); // Pobieranie listy użytkowników (monterzy / admini) useEffect(() => { fetchApi('/api/auth/users', {}, token) .then(usrs => { if (Array.isArray(usrs)) { setWorkers(usrs.filter(u => u.role === 'WORKER' || u.role === 'ADMIN')); } }) .catch(err => console.warn('Błąd pobierania listy pracowników:', err)); }, [token]); // Pobieranie słownika klientów useEffect(() => { fetchApi('/api/clients', {}, token) .then(cls => { if (Array.isArray(cls) && cls.length > 0) { setClients(cls); } }) .catch(err => console.warn('Błąd pobierania słownika klientów:', err)); }, [token]); // Sprawdzanie czy pracownik jest wybrany const isWorkerSelected = (w) => { if (!w) return false; return selectedWorkers.includes(w.id) || selectedWorkers.includes(String(w.id)) || selectedWorkers.includes(w.username); }; // Przełączanie przypisania pracownika (toggle) const toggleWorker = (w) => { if (isWorkerSelected(w)) { setSelectedWorkers(selectedWorkers.filter(idOrName => idOrName !== w.id && idOrName !== String(w.id) && idOrName !== w.username )); } else { setSelectedWorkers([...selectedWorkers, w.username]); } }; // Obsługa dropdownu przypisywania pracownika const handleSelectDropdown = (e) => { const val = e.target.value; if (!val) return; const targetWorker = workers.find(w => w.username === val || String(w.id) === val); if (targetWorker && !isWorkerSelected(targetWorker)) { setSelectedWorkers([...selectedWorkers, targetWorker.username]); } e.target.value = ''; }; // Pobieranie danych i współrzędnych GPS z BTSearch const handleFetchBtSearch = async () => { const code = (objectNumber || '').trim(); if (!code) { notify('Wpisz numer/kod obiektu (np. 51482), aby pobrać dane!', 'warning'); return; } setLoadingLookup(true); try { const data = await fetchApi(`/api/btsearch/lookup?code=${encodeURIComponent(code)}`, {}, token); if (data.address) setLocation(data.address); if (data.gps_coordinates) { const parts = data.gps_coordinates.split(',').map(s => s.trim()); if (parts.length === 2 && !isNaN(parseFloat(parts[0])) && !isNaN(parseFloat(parts[1]))) { setLatitude(parseFloat(parts[0])); setLongitude(parseFloat(parts[1])); } } notify(`Pobrano adres i współrzędne z BTSearch dla stacji ${code}!`, 'success'); } catch (err) { notify(err.message || 'Nie znaleziono danych w BTSearch dla podanego kodu', 'error'); } finally { setLoadingLookup(false); } }; // Pobieranie współrzędnych GPS z urządzenia const handleGetBrowserGps = () => { if (!navigator.geolocation) { notify('Geolokalizacja nie jest obsługiwana przez Twoją przeglądarkę', 'warning'); return; } setLoadingGps(true); navigator.geolocation.getCurrentPosition( (pos) => { const lat = parseFloat(pos.coords.latitude.toFixed(6)); const lng = parseFloat(pos.coords.longitude.toFixed(6)); setLatitude(lat); setLongitude(lng); setLoadingGps(false); notify(`📍 Pobrano aktualną pozycję GPS: ${lat}, ${lng}`, 'success'); }, (err) => { setLoadingGps(false); notify(`Błąd geolokalizacji: ${err.message}`, 'error'); }, { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 } ); }; // Kopiowanie pełnych danych zlecenia do schowka const handleCopyOrderData = () => { const activeClient = clientName === 'INNY' ? (customClient || 'Inny') : clientName; const lines = [ `==================================================`, `Multi-Tech Pro FSM - NetWorks SPiN Karta Zlecenia`, `==================================================`, `ID Zlecenia: #${project.id || '-'}`, `Kod Systemowy: ${project.code || '-'}`, `Nazwa Zlecenia: ${name || project.name || '-'}`, `Klient / Operator: ${activeClient}`, `Numer / Kod Obiektu: ${objectNumber || project.object_number || 'Brak'}`, `Status Zlecenia: ${status}`, `Priorytet: ${priority}`, `Kategoria / Typ: ${projectType}`, `--------------------------------------------------`, `Lokalizacja Obiektu: ${location || 'Nie podano adresu'}`, `Koordynaty GPS: ${latitude && longitude ? `${latitude}, ${longitude}` : 'Brak współrzędnych'}`, `Data utworzenia: ${formatDatePl(project.created_at)}`, `Termin planowany: ${plannedCompletionDate || 'Nie określono'}`, `Data zakończenia: ${completionDate || 'W toku'}`, `--------------------------------------------------`, `Rejestr Czasu Pracy:`, ` - Rozpoczęto: ${project.work_started_at || 'Brak startu'}`, ` - Zakończono: ${project.work_ended_at || 'Brak zakończenia'}`, `Przypisani Technicy: ${selectedWorkers.length > 0 ? selectedWorkers.join(', ') : 'Brak przypisanych osób'}`, `--------------------------------------------------`, `Zakres Prac:`, description || project.description || 'Brak szczegółowego opisu zlecenia.', `Uwagi Dyspozytora:`, remarks || project.remarks || 'Brak uwag.', `==================================================` ]; const fullText = lines.join('\n'); if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(fullText) .then(() => notify('📋 Skopiowano kompletne dane zlecenia do schowka!', 'success')) .catch(() => notify('Nie udało się skopiować danych', 'error')); } else { notify('Schowek jest niedostępny w tej przeglądarce', 'warning'); } }; // Zapisywanie zmian (Submit formularza) const handleSubmit = async (e) => { if (e) e.preventDefault(); setSaving(true); try { const latVal = latitude !== '' && !isNaN(parseFloat(latitude)) ? parseFloat(latitude) : null; const lngVal = longitude !== '' && !isNaN(parseFloat(longitude)) ? parseFloat(longitude) : null; const finalClient = clientName === 'INNY' ? (customClient.trim() || 'INNY') : clientName; const payload = { name: name.trim() || project.name, client_name: finalClient, object_number: objectNumber.trim(), location: location.trim(), latitude: latVal, longitude: lngVal, status, priority, project_type: projectType, completion_date: completionDate, planned_completion_date: plannedCompletionDate, remarks: remarks.trim(), description: description.trim(), assigned_workers: selectedWorkers }; const res = await fetchApi(`/api/projects/${project.id}/update`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }, token); notify(res.message || 'Zlecenie zaktualizowane pomyślnie!', 'success'); if (onUpdated) onUpdated(); if (onClose) onClose(); } catch (err) { notify(err.message || 'Wystąpił błąd podczas zapisywania zlecenia', 'error'); } finally { setSaving(false); } }; // Obsługa bezpowrotnego usunięcia zlecenia z bazy FSM const handleDeleteOrder = async () => { if (!project || !project.id) return; const projCode = project.code || project.order_id || ('#' + project.id); const projName = project.name || project.title || ''; const objCode = project.station_code || project.object_number || ''; const confirmed = window.confirm( '⚠️ CZY NA PEWNO CHCESZ USUNĄĆ TO ZLECENIE?\n\n' + 'Nr zlecenia: ' + projCode + '\n' + 'Nazwa: ' + projName + '\n' + 'Obiekt / Stacja: ' + objCode + '\n\n' + 'UWAGA: Spowoduje to bezpowrotne usunięcie zlecenia z bazy FSM wraz ze wszystkimi przypisanymi etapami i zdjęciami dokumentacji!' ); if (!confirmed) return; setSaving(true); try { await fetchApi('/api/projects/' + project.id, { method: 'DELETE' }, token); notify('✅ Zlecenie ' + projCode + ' zostało pomyślnie usunięte.', 'success'); if (typeof onDeleted === 'function') { onDeleted(project.id); } else if (typeof onUpdated === 'function') { onUpdated(); if (typeof onClose === 'function') onClose(); } else if (typeof onClose === 'function') { onClose(); } } catch (err) { console.error('Błąd usuwania zlecenia:', err); notify('Błąd podczas usuwania zlecenia: ' + err.message, 'error'); } finally { setSaving(false); } }; // Pomocnik renderowania oficjalnej plakietki SPiN const renderOfficialSpinStatusBadge = (st) => { const s = (st || '').toUpperCase(); if (s === 'IN_PROGRESS' || s === 'ON_SITE' || s === 'IN_TRANSIT') { return ( {s === 'IN_PROGRESS' ? 'W REALIZACJI' : (s === 'ON_SITE' ? 'NA OBIEKCIE' : 'W TRASIE')} ); } if (s === 'DRAFT' || s === 'NEW' || s === 'NOWE') { return ( NOWE / PROJEKT ); } if (s === 'COMPLETED' || s === 'CONFIRMED' || s === 'ZAKOŃCZONE') { return ( ZAKOŃCZONE ); } if (s === 'PAUSED') { return ( ⏸️ PAUZA ); } return ( DO ODBIORU / WYKONANIA ); }; // Pomocnik renderowania priorytetu const renderPriorityPill = (prio) => { const p = (prio || 'NORMAL').toUpperCase(); if (p === 'URGENT' || p === 'AWARYJNY' || p === 'CRITICAL') { return ( 🚨 PILNY ! ); } if (p === 'HIGH' || p === 'WYSOKI') { return ( ⚡ WYSOKI ); } return ( NORMALNY ); }; const clientBadgeStyle = getClientBadgeStyle(project.client_name || project.target_client); const hasWorkStarted = Boolean(project.work_started_at); const hasWorkEnded = Boolean(project.work_ended_at); return (
{ if (e.target === e.currentTarget) onClose(); }} >
{/* ============================================================================== 1. BELKA TYTUŁOWA OKNA (SPiN Window Chrome) ============================================================================== */}
✏️ SZCZEGÓŁY & KOREKTA ZLECENIA: {project.name || project.title || project.code || 'Brak nazwy'} ID: #{project.id || '-'}
{/* ============================================================================== TREŚĆ OKNA (Scrollable Body) ============================================================================== */}
{/* ============================================================================== 2. KARTA IDENTYFIKACJI ZLECENIA (SPiN Master Card) Zastępuje stary ciemnogranatowy blok jasnym, beveled panelem telco! ============================================================================== */}
📋 KARTA IDENTYFIKACJI ZLECENIA (SPiN MASTER RECORD)
PLATFORMA TELCO: fsm.multi-tech.pro
{/* Siatka metryczna w 3 kolumnach */}
{/* 1. Klient / Operator */}
Klient / Operator:
{clientBadgeStyle.icon} {project.client_name || project.target_client || 'Brak'}
{/* 2. Kod Zlecenia */}
Kod Zlecenia:
{project.code || '-'}
{/* 3. Numer / Kod Obiektu */}
Numer / Kod Obiektu:
🏢 {project.object_number || 'Brak (nieokreślony)'}
{/* 4. Status Zlecenia */}
Status Zlecenia:
{getProjectStatusBadge ? getProjectStatusBadge(project) : renderOfficialSpinStatusBadge(project.status)}
{/* 5. Typ / Szablon Prac */}
Typ / Kategoria Prac: {project.project_type || project.order_template || 'Standardowy'}
{/* 6. Priorytet Zlecenia */}
Priorytet:
{renderPriorityPill(project.priority)}
{/* 7. Data Zgłoszenia */}
Data Zgłoszenia / Utworzenia: 📅 {formatDatePl(project.created_at)}
{/* 8. Adres & GPS */}
Lokalizacja & Koordynaty GPS:
📍 {project.location || 'Nie podano adresu'} {project.latitude && project.longitude && ( 🌐 {project.latitude}, {project.longitude} )}
{/* ============================================================================== 3. REJESTR CZASU PRACY & OPIS ZAKRESU PRAC ============================================================================== */}
⏱️ REJESTR CZASU PRACY:
{/* Rozpoczęto z diodą LED */}
Rozpoczęto: {project.work_started_at || 'Brak startu'}
{/* Zakończono z diodą LED */}
Zakończono: {project.work_ended_at || 'W realizacji (brak daty)'}
Status telemetryczny: {hasWorkEnded ? '🏁 PRACA ZAKOŃCZONA' : (hasWorkStarted ? '⚡ TRWAJĄ PRACE NA OBIEKCIE' : '⏳ OCZEKUJE NA MONTAŻ')}
{/* Podgląd opisu i zakresu prac */}
📝 ZAKRES PRAC & NOTATKI TECHNICZNE OBIEKTU:
{project.description || project.remarks || 'Brak szczegółowego opisu zlecenia w bazie danych.'}
{/* ============================================================================== 4. FORMULARZ KOREKTY PARAMETRÓW ZLECENIA (NetWorks SPiN Form Grid) ============================================================================== */}
{/* ──────────────────────────────────────────────────────────── SEKCJA 1: PODSTAWOWE PARAMETRY & STATUS ──────────────────────────────────────────────────────────── */}
🛠️ 1. PARAMETRY ZLECENIA & STATUS OPERACYJNY
{/* Nazwa zlecenia */}
setName(e.target.value)} placeholder="np. Wymiana baterii 48V w szafie zasilania awaryjnego" required style={{ height: '26px' }} />
{/* Klient / Operator ze słownika */}
{clientName === 'INNY' && ( setCustomClient(e.target.value)} placeholder="Wpisz nazwę nowego klienta..." style={{ marginTop: '4px', height: '24px' }} /> )}
{/* Kategoria / Typ Prac */}
{/* Status Zlecenia z natychmiastowym podglądem plakietki! */}
{renderOfficialSpinStatusBadge(status)}
{/* Priorytet Zlecenia */}
{renderPriorityPill(priority)}
{/* ──────────────────────────────────────────────────────────── SEKCJA 2: PASZPORTYZACJA OBIEKTU, ADRES & GPS (BTSearch) ──────────────────────────────────────────────────────────── */}
📍 2. OBIEKT TELCO, ADRES & KOORDYNATY GPS (BTSEARCH)
{/* Numer obiektu i przyciski szybkiego pobierania */}
setObjectNumber(e.target.value)} placeholder="Wpisz kod stacji bazowej..." style={{ height: '26px' }} />
{/* Pełny adres obiektu */}
setLocation(e.target.value)} placeholder="np. Kraków, ul. Drukarska 8, 30-348 Kraków" style={{ height: '26px' }} />
{/* Szerokość i długość geograficzna */}
setLatitude(e.target.value)} placeholder="np. 50.064650" style={{ height: '26px' }} />
setLongitude(e.target.value)} placeholder="np. 19.944980" style={{ height: '26px' }} />
{/* ──────────────────────────────────────────────────────────── SEKCJA 3: HARMONOGRAM & PRZYPISANI SERWISANCI ──────────────────────────────────────────────────────────── */}
📅 3. HARMONOGRAM PRAC & PRZYPISANA EKIPA SERWISOWA
{/* Terminy planowane i wykonane */}
setPlannedCompletionDate(e.target.value)} style={{ height: '26px' }} />
setCompletionDate(e.target.value)} style={{ height: '26px' }} />
{/* Przypisani monterzy / technicy */}
{selectedWorkers.length === 0 && ( ⚠️ Brak przypisanej ekipy do zlecenia! )}
{/* Dropdown do wyboru */} {/* Wizualne kafelki / chipsy w stylu SPiN */}
{workers.map(w => { const isSel = isWorkerSelected(w); return ( ); })}
{/* ──────────────────────────────────────────────────────────── SEKCJA 4: OPIS, ZAKRES PRAC & NOTATKI DYSPOZYTORSKIE ──────────────────────────────────────────────────────────── */}
📝 4. ZAKRES PRAC & NOTATKI DYSPOZYTORSKIE
{/* Opis / Zakres Prac */}