refactoring

This commit is contained in:
2025-11-10 16:44:54 +01:00
parent c2710f0a67
commit 89e7f77a4e
11 changed files with 807 additions and 10 deletions

View File

@@ -0,0 +1,414 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
const StoreWatchPage = ({ authorizedFetch }) => {
const [regions, setRegions] = useState([]);
const [selectedRegionId, setSelectedRegionId] = useState('');
const [storesByRegion, setStoresByRegion] = useState({});
const [watchList, setWatchList] = useState([]);
const [regionLoading, setRegionLoading] = useState(false);
const [storesLoading, setStoresLoading] = useState(false);
const [subscriptionsLoading, setSubscriptionsLoading] = useState(false);
const [status, setStatus] = useState('');
const [error, setError] = useState('');
const [dirty, setDirty] = useState(false);
const [saving, setSaving] = useState(false);
const watchedIds = useMemo(
() => new Set(watchList.map((entry) => String(entry.storeId))),
[watchList]
);
const selectedRegion = useMemo(
() => regions.find((region) => String(region.id) === String(selectedRegionId)) || null,
[regions, selectedRegionId]
);
const currentStores = useMemo(() => {
const regionEntry = storesByRegion[String(selectedRegionId)];
if (!regionEntry || !Array.isArray(regionEntry.stores)) {
return [];
}
return regionEntry.stores;
}, [storesByRegion, selectedRegionId]);
const eligibleStores = useMemo(
() => currentStores.filter((store) => Number(store.cooperationStatus) === 5),
[currentStores]
);
const loadRegions = useCallback(async () => {
if (!authorizedFetch) {
return;
}
setRegionLoading(true);
setError('');
try {
const response = await authorizedFetch('/api/store-watch/regions');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const normalized = Array.isArray(data.regions) ? data.regions : [];
setRegions(normalized);
if (!selectedRegionId && normalized.length > 0) {
setSelectedRegionId(String(normalized[0].id));
}
} catch (err) {
setError(`Regionen konnten nicht geladen werden: ${err.message}`);
} finally {
setRegionLoading(false);
}
}, [authorizedFetch, selectedRegionId]);
const loadSubscriptions = useCallback(async () => {
if (!authorizedFetch) {
return;
}
setSubscriptionsLoading(true);
setError('');
try {
const response = await authorizedFetch('/api/store-watch/subscriptions');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const normalized = Array.isArray(data.stores) ? data.stores : [];
setWatchList(normalized);
setDirty(false);
} catch (err) {
setError(`Überwachte Betriebe konnten nicht geladen werden: ${err.message}`);
} finally {
setSubscriptionsLoading(false);
}
}, [authorizedFetch]);
const fetchStoresForRegion = useCallback(
async (regionId, { force } = {}) => {
if (!authorizedFetch || !regionId) {
return;
}
if (!force && storesByRegion[String(regionId)]) {
return;
}
setStoresLoading(true);
setError('');
try {
const endpoint = force
? `/api/store-watch/regions/${regionId}/stores?force=1`
: `/api/store-watch/regions/${regionId}/stores`;
const response = await authorizedFetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
setStoresByRegion((prev) => ({
...prev,
[String(regionId)]: {
total: Number(data.total) || 0,
stores: Array.isArray(data.stores) ? data.stores : [],
fetchedAt: Date.now()
}
}));
} catch (err) {
setError(`Betriebe konnten nicht geladen werden: ${err.message}`);
} finally {
setStoresLoading(false);
}
},
[authorizedFetch, storesByRegion]
);
useEffect(() => {
loadRegions();
loadSubscriptions();
}, [loadRegions, loadSubscriptions]);
useEffect(() => {
if (selectedRegionId) {
fetchStoresForRegion(selectedRegionId);
}
}, [selectedRegionId, fetchStoresForRegion]);
const handleToggleStore = useCallback(
(store, checked) => {
setWatchList((prev) => {
const storeId = String(store.id || store.storeId);
const existing = prev.find((entry) => entry.storeId === storeId);
if (checked) {
if (existing) {
return prev;
}
setDirty(true);
const regionName =
store.region?.name || selectedRegion?.name || existing?.regionName || '';
return [
...prev,
{
storeId,
storeName: store.name || store.storeName || `Store ${storeId}`,
regionId: String(store.region?.id || selectedRegionId || existing?.regionId || ''),
regionName,
lastTeamSearchStatus: existing?.lastTeamSearchStatus ?? null
}
];
}
if (!existing) {
return prev;
}
setDirty(true);
return prev.filter((entry) => entry.storeId !== storeId);
});
},
[selectedRegion, selectedRegionId]
);
const handleRemoveWatch = useCallback((storeId) => {
setWatchList((prev) => {
const next = prev.filter((entry) => entry.storeId !== storeId);
if (next.length !== prev.length) {
setDirty(true);
}
return next;
});
}, []);
const handleSave = useCallback(async () => {
if (!authorizedFetch || saving || !dirty) {
return;
}
setSaving(true);
setStatus('');
setError('');
try {
const response = await authorizedFetch('/api/store-watch/subscriptions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ stores: watchList })
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
setWatchList(Array.isArray(data.stores) ? data.stores : []);
setDirty(false);
setStatus('Überwachung gespeichert.');
setTimeout(() => setStatus(''), 4000);
} catch (err) {
setError(`Speichern fehlgeschlagen: ${err.message}`);
} finally {
setSaving(false);
}
}, [authorizedFetch, dirty, saving, watchList]);
const handleReset = useCallback(() => {
loadSubscriptions();
}, [loadSubscriptions]);
if (!authorizedFetch) {
return (
<div className="p-4 max-w-4xl mx-auto">
<p className="text-red-600">Keine Session aktiv.</p>
</div>
);
}
return (
<div className="p-4 max-w-5xl mx-auto bg-white shadow rounded-lg mt-4">
<div className="flex flex-col gap-2 mb-4">
<h1 className="text-2xl font-bold text-blue-900">Betriebs-Monitoring</h1>
<p className="text-gray-600 text-sm">
Wähle Betriebe aus, die bei offenem Team-Status automatisch gemeldet werden sollen.
</p>
</div>
{(error || status) && (
<div className="mb-4 space-y-2">
{error && (
<div className="bg-red-100 border border-red-300 text-red-700 px-4 py-2 rounded">{error}</div>
)}
{status && (
<div className="bg-green-100 border border-green-300 text-green-700 px-4 py-2 rounded">
{status}
</div>
)}
</div>
)}
<div className="mb-6 border border-gray-200 rounded-lg p-4 bg-gray-50">
<div className="flex flex-col md:flex-row md:items-end gap-3">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700 mb-1" htmlFor="region-select">
Region
</label>
<select
id="region-select"
value={selectedRegionId}
onChange={(event) => setSelectedRegionId(event.target.value)}
className="border rounded-md p-2 w-full"
disabled={regionLoading}
>
<option value="">Region auswählen</option>
{regions.map((region) => (
<option key={region.id} value={region.id}>
{region.name}
</option>
))}
</select>
</div>
<div className="flex gap-2">
<button
type="button"
onClick={() => loadRegions()}
className="px-4 py-2 border rounded-md text-sm bg-white hover:bg-gray-100"
disabled={regionLoading}
>
Regionen neu laden
</button>
<button
type="button"
onClick={() => fetchStoresForRegion(selectedRegionId, { force: true })}
className="px-4 py-2 border rounded-md text-sm bg-white hover:bg-gray-100"
disabled={!selectedRegionId || storesLoading}
>
Betriebe aktualisieren
</button>
</div>
</div>
<p className="text-xs text-gray-500 mt-2">
Es werden nur Regionen angezeigt, in denen du Mitglied mit Klassifikation 1 bist.
</p>
</div>
<div className="mb-6">
<div className="flex items-center justify-between mb-2">
<h2 className="text-lg font-semibold text-gray-800">Betriebe in der Region</h2>
{storesByRegion[String(selectedRegionId)]?.fetchedAt && (
<span className="text-xs text-gray-500">
Aktualisiert:{' '}
{new Date(storesByRegion[String(selectedRegionId)].fetchedAt).toLocaleTimeString('de-DE')}
</span>
)}
</div>
{storesLoading && <p className="text-sm text-gray-600">Lade Betriebe...</p>}
{!storesLoading && (!selectedRegionId || eligibleStores.length === 0) && (
<p className="text-sm text-gray-500">
{selectedRegionId
? 'Keine geeigneten Betriebe (Status "aktiv") in dieser Region.'
: 'Bitte zuerst eine Region auswählen.'}
</p>
)}
{!storesLoading && eligibleStores.length > 0 && (
<div className="overflow-x-auto border border-gray-200 rounded-lg">
<table className="min-w-full divide-y divide-gray-200 text-sm">
<thead className="bg-gray-100">
<tr>
<th className="px-4 py-2 text-left">Betrieb</th>
<th className="px-4 py-2 text-left">Ort</th>
<th className="px-4 py-2 text-left">Kooperation</th>
<th className="px-4 py-2 text-center">Überwachen</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{eligibleStores.map((store) => {
const checked = watchedIds.has(String(store.id));
return (
<tr key={store.id} className="bg-white">
<td className="px-4 py-2">
<p className="font-medium text-gray-900">{store.name}</p>
<p className="text-xs text-gray-500">#{store.id}</p>
</td>
<td className="px-4 py-2">
<p className="text-gray-800 text-sm">{store.city || 'unbekannt'}</p>
<p className="text-xs text-gray-500">{store.street || ''}</p>
</td>
<td className="px-4 py-2 text-sm text-gray-600">
Seit {store.createdAt ? new Date(store.createdAt).toLocaleDateString('de-DE') : 'n/a'}
</td>
<td className="px-4 py-2 text-center">
<input
type="checkbox"
className="h-5 w-5"
checked={checked}
onChange={(event) => handleToggleStore(store, event.target.checked)}
/>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
<div className="mb-6">
<div className="flex items-center justify-between mb-3">
<h2 className="text-lg font-semibold text-gray-800">
Überwachte Betriebe ({watchList.length})
</h2>
<div className="flex gap-2">
<button
type="button"
className="px-4 py-2 border rounded-md text-sm bg-white hover:bg-gray-100"
onClick={handleReset}
disabled={subscriptionsLoading}
>
Änderungen verwerfen
</button>
<button
type="button"
className="px-4 py-2 rounded-md text-sm text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-60"
onClick={handleSave}
disabled={!dirty || saving}
>
{saving ? 'Speichere...' : 'Speichern'}
</button>
</div>
</div>
{subscriptionsLoading && <p className="text-sm text-gray-600">Lade aktuelle Auswahl...</p>}
{!subscriptionsLoading && watchList.length === 0 && (
<p className="text-sm text-gray-500">Noch keine Betriebe ausgewählt.</p>
)}
{watchList.length > 0 && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{watchList.map((entry) => (
<div key={entry.storeId} className="border border-gray-200 rounded-lg p-3 bg-gray-50">
<div className="flex justify-between items-start">
<div>
<p className="font-semibold text-gray-900">{entry.storeName}</p>
<p className="text-xs text-gray-500">
#{entry.storeId} {entry.regionName || 'Region unbekannt'}
</p>
</div>
<button
type="button"
className="text-xs text-red-600 hover:underline"
onClick={() => handleRemoveWatch(entry.storeId)}
>
Entfernen
</button>
</div>
<p className="text-xs text-gray-600 mt-2">
Letzter Status:{' '}
{entry.lastTeamSearchStatus === 1
? 'Suchend'
: entry.lastTeamSearchStatus === 0
? 'Nicht suchend'
: 'Unbekannt'}
</p>
</div>
))}
</div>
)}
</div>
{dirty && (
<p className="text-xs text-amber-600">
Es gibt ungespeicherte Änderungen. Bitte "Speichern" klicken.
</p>
)}
</div>
);
};
export default StoreWatchPage;