diff --git a/server.js b/server.js
index 7332049..3f4cf4c 100644
--- a/server.js
+++ b/server.js
@@ -11,6 +11,7 @@ const { scheduleConfig } = require('./services/pickupScheduler');
const adminConfig = require('./services/adminConfig');
const { readNotificationSettings, writeNotificationSettings } = require('./services/userSettingsStore');
const notificationService = require('./services/notificationService');
+const { readStoreWatch, writeStoreWatch } = require('./services/storeWatchStore');
const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;
const adminEmail = (process.env.ADMIN_EMAIL || '').toLowerCase();
@@ -20,6 +21,8 @@ const app = express();
const port = process.env.PORT || 3000;
const storeRefreshJobs = new Map();
const cachedStoreSnapshots = new Map();
+const regionStoreCache = new Map();
+const REGION_STORE_CACHE_MS = 15 * 60 * 1000;
app.use(cors());
app.use(express.json({ limit: '1mb' }));
@@ -88,6 +91,25 @@ function mergeStoresIntoConfig(config = [], stores = []) {
return { merged: Array.from(map.values()), changed };
}
+function getCachedRegionStores(regionId) {
+ const entry = regionStoreCache.get(String(regionId));
+ if (!entry) {
+ return null;
+ }
+ if (Date.now() - entry.fetchedAt > REGION_STORE_CACHE_MS) {
+ regionStoreCache.delete(String(regionId));
+ return null;
+ }
+ return entry.payload;
+}
+
+function setCachedRegionStores(regionId, payload) {
+ regionStoreCache.set(String(regionId), {
+ fetchedAt: Date.now(),
+ payload
+ });
+}
+
function isStoreCacheFresh(session) {
if (!session?.storesCache?.fetchedAt) {
return false;
@@ -368,6 +390,79 @@ app.get('/api/profile', requireAuth, async (req, res) => {
});
});
+app.get('/api/store-watch/regions', requireAuth, async (req, res) => {
+ try {
+ const details = await foodsharingClient.fetchProfile(req.session.cookieHeader);
+ const regions = Array.isArray(details?.regions)
+ ? details.regions.filter((region) => Number(region?.classification) === 1)
+ : [];
+ res.json({ regions });
+ } catch (error) {
+ console.error('[STORE-WATCH] Regionen konnten nicht geladen werden:', error.message);
+ res.status(500).json({ error: 'Regionen konnten nicht geladen werden' });
+ }
+});
+
+app.get('/api/store-watch/regions/:regionId/stores', requireAuth, async (req, res) => {
+ const { regionId } = req.params;
+ if (!regionId) {
+ return res.status(400).json({ error: 'Region-ID fehlt' });
+ }
+ const forceRefresh = req.query.force === '1';
+ if (!forceRefresh) {
+ const cached = getCachedRegionStores(regionId);
+ if (cached) {
+ return res.json(cached);
+ }
+ }
+ try {
+ const result = await foodsharingClient.fetchRegionStores(regionId, req.session.cookieHeader);
+ const payload = {
+ total: Number(result?.total) || 0,
+ stores: Array.isArray(result?.stores) ? result.stores : []
+ };
+ setCachedRegionStores(regionId, payload);
+ res.json(payload);
+ } catch (error) {
+ console.error(`[STORE-WATCH] Stores für Region ${regionId} konnten nicht geladen werden:`, error.message);
+ res.status(500).json({ error: 'Betriebe konnten nicht geladen werden' });
+ }
+});
+
+app.get('/api/store-watch/subscriptions', requireAuth, (req, res) => {
+ const stores = readStoreWatch(req.session.profile.id);
+ res.json({ stores });
+});
+
+app.post('/api/store-watch/subscriptions', requireAuth, (req, res) => {
+ if (!req.body || !Array.isArray(req.body.stores)) {
+ return res.status(400).json({ error: 'Erwartet eine Liste von Betrieben' });
+ }
+ const previous = readStoreWatch(req.session.profile.id);
+ const previousMap = new Map(previous.map((entry) => [entry.storeId, entry]));
+ const normalized = [];
+ req.body.stores.forEach((store) => {
+ const storeId = store?.storeId || store?.id;
+ const regionId = store?.regionId || store?.region?.id;
+ if (!storeId || !regionId) {
+ return;
+ }
+ const entry = {
+ storeId: String(storeId),
+ storeName: store?.storeName || store?.name || `Store ${storeId}`,
+ regionId: String(regionId),
+ regionName: store?.regionName || store?.region?.name || '',
+ lastTeamSearchStatus: previousMap.get(String(storeId))?.lastTeamSearchStatus ?? null
+ };
+ normalized.push(entry);
+ });
+
+ const persisted = writeStoreWatch(req.session.profile.id, normalized);
+ const config = readConfig(req.session.profile.id);
+ scheduleWithCurrentSettings(req.session.id, config);
+ res.json({ success: true, stores: persisted });
+});
+
app.get('/api/config', requireAuth, (req, res) => {
const config = readConfig(req.session.profile.id);
res.json(config);
diff --git a/services/adminConfig.js b/services/adminConfig.js
index 845f020..5a6a964 100644
--- a/services/adminConfig.js
+++ b/services/adminConfig.js
@@ -10,6 +10,9 @@ const DEFAULT_SETTINGS = {
randomDelayMaxSeconds: 120,
initialDelayMinSeconds: 5,
initialDelayMaxSeconds: 30,
+ storeWatchCron: '*/30 * * * *',
+ storeWatchInitialDelayMinSeconds: 10,
+ storeWatchInitialDelayMaxSeconds: 60,
storePickupCheckDelayMs: 400,
ignoredSlots: [
{
@@ -101,6 +104,15 @@ function readSettings() {
randomDelayMaxSeconds: sanitizeNumber(parsed.randomDelayMaxSeconds, DEFAULT_SETTINGS.randomDelayMaxSeconds),
initialDelayMinSeconds: sanitizeNumber(parsed.initialDelayMinSeconds, DEFAULT_SETTINGS.initialDelayMinSeconds),
initialDelayMaxSeconds: sanitizeNumber(parsed.initialDelayMaxSeconds, DEFAULT_SETTINGS.initialDelayMaxSeconds),
+ storeWatchCron: parsed.storeWatchCron || DEFAULT_SETTINGS.storeWatchCron,
+ storeWatchInitialDelayMinSeconds: sanitizeNumber(
+ parsed.storeWatchInitialDelayMinSeconds,
+ DEFAULT_SETTINGS.storeWatchInitialDelayMinSeconds
+ ),
+ storeWatchInitialDelayMaxSeconds: sanitizeNumber(
+ parsed.storeWatchInitialDelayMaxSeconds,
+ DEFAULT_SETTINGS.storeWatchInitialDelayMaxSeconds
+ ),
storePickupCheckDelayMs: sanitizeNumber(
parsed.storePickupCheckDelayMs,
DEFAULT_SETTINGS.storePickupCheckDelayMs
@@ -122,6 +134,15 @@ function writeSettings(patch = {}) {
randomDelayMaxSeconds: sanitizeNumber(patch.randomDelayMaxSeconds, current.randomDelayMaxSeconds),
initialDelayMinSeconds: sanitizeNumber(patch.initialDelayMinSeconds, current.initialDelayMinSeconds),
initialDelayMaxSeconds: sanitizeNumber(patch.initialDelayMaxSeconds, current.initialDelayMaxSeconds),
+ storeWatchCron: patch.storeWatchCron || current.storeWatchCron,
+ storeWatchInitialDelayMinSeconds: sanitizeNumber(
+ patch.storeWatchInitialDelayMinSeconds,
+ current.storeWatchInitialDelayMinSeconds
+ ),
+ storeWatchInitialDelayMaxSeconds: sanitizeNumber(
+ patch.storeWatchInitialDelayMaxSeconds,
+ current.storeWatchInitialDelayMaxSeconds
+ ),
storePickupCheckDelayMs: sanitizeNumber(
patch.storePickupCheckDelayMs,
current.storePickupCheckDelayMs
diff --git a/services/foodsharingClient.js b/services/foodsharingClient.js
index 22acb69..e146962 100644
--- a/services/foodsharingClient.js
+++ b/services/foodsharingClient.js
@@ -200,6 +200,29 @@ async function fetchPickups(storeId, cookieHeader) {
return response.data?.pickups || [];
}
+async function fetchRegionStores(regionId, cookieHeader) {
+ if (!regionId) {
+ return { total: 0, stores: [] };
+ }
+ const response = await client.get(`/api/region/${regionId}/stores`, {
+ headers: buildHeaders(cookieHeader)
+ });
+ return {
+ total: Number(response.data?.total) || 0,
+ stores: Array.isArray(response.data?.stores) ? response.data.stores : []
+ };
+}
+
+async function fetchStoreDetails(storeId, cookieHeader) {
+ if (!storeId) {
+ return null;
+ }
+ const response = await client.get(`/api/map/stores/${storeId}`, {
+ headers: buildHeaders(cookieHeader)
+ });
+ return response.data || null;
+}
+
async function pickupRuleCheck(storeId, utcDate, profileId, session) {
const response = await client.get(`/api/stores/${storeId}/pickupRuleCheck/${utcDate}/${profileId}`, {
headers: buildHeaders(session.cookieHeader, session.csrfToken)
@@ -223,6 +246,8 @@ module.exports = {
fetchProfile,
fetchStores,
fetchPickups,
+ fetchRegionStores,
+ fetchStoreDetails,
pickupRuleCheck,
bookSlot
};
diff --git a/services/notificationService.js b/services/notificationService.js
index 5b14e3b..729cb28 100644
--- a/services/notificationService.js
+++ b/services/notificationService.js
@@ -99,6 +99,20 @@ async function sendSlotNotification({ profileId, storeName, pickupDate, onlyNoti
});
}
+async function sendStoreWatchNotification({ profileId, storeName, storeId, regionName }) {
+ const storeLink = storeId ? `https://foodsharing.de/store/${storeId}` : null;
+ const title = `Team sucht Verstärkung: ${storeName}`;
+ const regionText = regionName ? ` (${regionName})` : '';
+ const messageBase = `Der Betrieb${regionText} sucht wieder aktiv neue Teammitglieder.`;
+ const message = storeLink ? `${messageBase}\n${storeLink}` : messageBase;
+ await notifyChannels(profileId, {
+ title,
+ message,
+ link: storeLink,
+ priority: 'high'
+ });
+}
+
async function sendTestNotification(profileId, channel) {
const title = 'Pickup Benachrichtigung (Test)';
const message = 'Das ist eine Testnachricht. Bei Fragen wende dich bitte an den Admin.';
@@ -134,5 +148,6 @@ async function sendTestNotification(profileId, channel) {
module.exports = {
sendSlotNotification,
+ sendStoreWatchNotification,
sendTestNotification
};
diff --git a/services/pickupScheduler.js b/services/pickupScheduler.js
index df0e5fa..6d0696b 100644
--- a/services/pickupScheduler.js
+++ b/services/pickupScheduler.js
@@ -4,6 +4,7 @@ const sessionStore = require('./sessionStore');
const { DEFAULT_SETTINGS } = require('./adminConfig');
const notificationService = require('./notificationService');
const { readConfig, writeConfig } = require('./configStore');
+const { readStoreWatch, writeStoreWatch } = require('./storeWatchStore');
const weekdayMap = {
Montag: 'Monday',
@@ -39,6 +40,13 @@ function resolveSettings(settings) {
initialDelayMaxSeconds: Number.isFinite(settings.initialDelayMaxSeconds)
? settings.initialDelayMaxSeconds
: DEFAULT_SETTINGS.initialDelayMaxSeconds,
+ storeWatchCron: settings.storeWatchCron || DEFAULT_SETTINGS.storeWatchCron,
+ storeWatchInitialDelayMinSeconds: Number.isFinite(settings.storeWatchInitialDelayMinSeconds)
+ ? settings.storeWatchInitialDelayMinSeconds
+ : DEFAULT_SETTINGS.storeWatchInitialDelayMinSeconds,
+ storeWatchInitialDelayMaxSeconds: Number.isFinite(settings.storeWatchInitialDelayMaxSeconds)
+ ? settings.storeWatchInitialDelayMaxSeconds
+ : DEFAULT_SETTINGS.storeWatchInitialDelayMaxSeconds,
ignoredSlots: Array.isArray(settings.ignoredSlots) ? settings.ignoredSlots : DEFAULT_SETTINGS.ignoredSlots,
notifications: {
ntfy: {
@@ -287,6 +295,78 @@ async function checkEntry(sessionId, entry, settings) {
}
}
+async function checkWatchedStores(sessionId) {
+ const session = sessionStore.get(sessionId);
+ if (!session?.profile?.id) {
+ return;
+ }
+ const watchers = readStoreWatch(session.profile.id);
+ if (!Array.isArray(watchers) || watchers.length === 0) {
+ return;
+ }
+
+ const ready = await ensureSession(session);
+ if (!ready) {
+ return;
+ }
+
+ let changed = false;
+ for (const watcher of watchers) {
+ try {
+ const details = await foodsharingClient.fetchStoreDetails(watcher.storeId, session.cookieHeader);
+ const status = details?.teamSearchStatus === 1 ? 1 : 0;
+ if (status === 1 && watcher.lastTeamSearchStatus !== 1) {
+ await notificationService.sendStoreWatchNotification({
+ profileId: session.profile.id,
+ storeName: watcher.storeName,
+ storeId: watcher.storeId,
+ regionName: watcher.regionName
+ });
+ }
+ if (watcher.lastTeamSearchStatus !== status) {
+ watcher.lastTeamSearchStatus = status;
+ changed = true;
+ }
+ } catch (error) {
+ console.error(`[WATCH] Prüfung für Store ${watcher.storeId} fehlgeschlagen:`, error.message);
+ }
+ }
+
+ if (changed) {
+ writeStoreWatch(session.profile.id, watchers);
+ }
+}
+
+function scheduleStoreWatchers(sessionId, settings) {
+ const session = sessionStore.get(sessionId);
+ if (!session?.profile?.id) {
+ return false;
+ }
+ const watchers = readStoreWatch(session.profile.id);
+ if (!Array.isArray(watchers) || watchers.length === 0) {
+ return false;
+ }
+ const cronExpression = settings.storeWatchCron || DEFAULT_SETTINGS.storeWatchCron;
+ const job = cron.schedule(
+ cronExpression,
+ () => {
+ checkWatchedStores(sessionId).catch((error) => {
+ console.error('[WATCH] Regelmäßige Prüfung fehlgeschlagen:', error.message);
+ });
+ },
+ { timezone: 'Europe/Berlin' }
+ );
+ sessionStore.attachJob(sessionId, job);
+ setTimeout(
+ () => checkWatchedStores(sessionId),
+ randomDelayMs(settings.storeWatchInitialDelayMinSeconds, settings.storeWatchInitialDelayMaxSeconds)
+ );
+ console.log(
+ `[WATCH] Überwache ${watchers.length} Betriebe für Session ${sessionId} (Cron: ${cronExpression}).`
+ );
+ return true;
+}
+
function scheduleEntry(sessionId, entry, settings) {
const cronExpression = settings.scheduleCron || DEFAULT_SETTINGS.scheduleCron;
const job = cron.schedule(
@@ -312,9 +392,17 @@ function scheduleEntry(sessionId, entry, settings) {
function scheduleConfig(sessionId, config, settings) {
const resolvedSettings = resolveSettings(settings);
sessionStore.clearJobs(sessionId);
- const activeEntries = config.filter((entry) => entry.active);
+ const watchScheduled = scheduleStoreWatchers(sessionId, resolvedSettings);
+ const entries = Array.isArray(config) ? config : [];
+ const activeEntries = entries.filter((entry) => entry.active);
if (activeEntries.length === 0) {
- console.log(`[INFO] Keine aktiven Einträge für Session ${sessionId} – Scheduler ruht.`);
+ if (watchScheduled) {
+ console.log(
+ `[INFO] Keine aktiven Pickup-Einträge für Session ${sessionId} – Store-Watch bleibt aktiv.`
+ );
+ } else {
+ console.log(`[INFO] Keine aktiven Einträge für Session ${sessionId} – Scheduler ruht.`);
+ }
return;
}
activeEntries.forEach((entry) => scheduleEntry(sessionId, entry, resolvedSettings));
diff --git a/services/storeWatchStore.js b/services/storeWatchStore.js
new file mode 100644
index 0000000..86f4fe2
--- /dev/null
+++ b/services/storeWatchStore.js
@@ -0,0 +1,84 @@
+const fs = require('fs');
+const path = require('path');
+
+const STORE_WATCH_DIR = path.join(__dirname, '..', 'config');
+
+function ensureDir() {
+ if (!fs.existsSync(STORE_WATCH_DIR)) {
+ fs.mkdirSync(STORE_WATCH_DIR, { recursive: true });
+ }
+}
+
+function getStoreWatchPath(profileId = 'shared') {
+ return path.join(STORE_WATCH_DIR, `${profileId}-store-watch.json`);
+}
+
+function sanitizeEntry(entry) {
+ if (!entry || !entry.storeId) {
+ return null;
+ }
+ const normalized = {
+ storeId: String(entry.storeId),
+ storeName: entry.storeName ? String(entry.storeName).trim() : `Store ${entry.storeId}`,
+ regionId: entry.regionId ? String(entry.regionId) : '',
+ regionName: entry.regionName ? String(entry.regionName).trim() : '',
+ lastTeamSearchStatus:
+ entry.lastTeamSearchStatus === 1
+ ? 1
+ : entry.lastTeamSearchStatus === 0
+ ? 0
+ : null
+ };
+ if (!normalized.regionId) {
+ return null;
+ }
+ return normalized;
+}
+
+function readStoreWatch(profileId) {
+ ensureDir();
+ const filePath = getStoreWatchPath(profileId);
+ if (!fs.existsSync(filePath)) {
+ fs.writeFileSync(filePath, JSON.stringify([], null, 2));
+ return [];
+ }
+ try {
+ const raw = fs.readFileSync(filePath, 'utf8');
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) {
+ return [];
+ }
+ const unique = new Map();
+ parsed.forEach((entry) => {
+ const sanitized = sanitizeEntry(entry);
+ if (sanitized) {
+ unique.set(sanitized.storeId, sanitized);
+ }
+ });
+ return Array.from(unique.values());
+ } catch (error) {
+ console.error(`[STORE-WATCH] Konnte Datei ${filePath} nicht lesen:`, error.message);
+ return [];
+ }
+}
+
+function writeStoreWatch(profileId, entries = []) {
+ const sanitized = [];
+ const seen = new Set();
+ entries.forEach((entry) => {
+ const normalized = sanitizeEntry(entry);
+ if (normalized && !seen.has(normalized.storeId)) {
+ sanitized.push(normalized);
+ seen.add(normalized.storeId);
+ }
+ });
+ ensureDir();
+ const filePath = getStoreWatchPath(profileId);
+ fs.writeFileSync(filePath, JSON.stringify(sanitized, null, 2));
+ return sanitized;
+}
+
+module.exports = {
+ readStoreWatch,
+ writeStoreWatch
+};
diff --git a/src/App.js b/src/App.js
index 261ac05..a66f424 100644
--- a/src/App.js
+++ b/src/App.js
@@ -21,6 +21,7 @@ import DirtyNavigationDialog from './components/DirtyNavigationDialog';
import ConfirmationDialog from './components/ConfirmationDialog';
import StoreSyncOverlay from './components/StoreSyncOverlay';
import RangePickerModal from './components/RangePickerModal';
+import StoreWatchPage from './components/StoreWatchPage';
function App() {
const [credentials, setCredentials] = useState({ email: '', password: '' });
@@ -695,6 +696,7 @@ function App() {
+ Legt fest, wie häufig der Team-Status der überwachten Betriebe geprüft wird. +
++ Wird genutzt, um die ersten Prüfungen leicht zu verteilen. +
+Keine Session aktiv.
++ Wähle Betriebe aus, die bei offenem Team-Status automatisch gemeldet werden sollen. +
++ Es werden nur Regionen angezeigt, in denen du Mitglied mit Klassifikation 1 bist. +
+Lade Betriebe...
} + {!storesLoading && (!selectedRegionId || eligibleStores.length === 0) && ( ++ {selectedRegionId + ? 'Keine geeigneten Betriebe (Status "aktiv") in dieser Region.' + : 'Bitte zuerst eine Region auswählen.'} +
+ )} + {!storesLoading && eligibleStores.length > 0 && ( +| Betrieb | +Ort | +Kooperation | +Überwachen | +
|---|---|---|---|
|
+ {store.name} +#{store.id} + |
+
+ {store.city || 'unbekannt'} +{store.street || ''} + |
+ + Seit {store.createdAt ? new Date(store.createdAt).toLocaleDateString('de-DE') : 'n/a'} + | ++ handleToggleStore(store, event.target.checked)} + /> + | +
Lade aktuelle Auswahl...
} + {!subscriptionsLoading && watchList.length === 0 && ( +Noch keine Betriebe ausgewählt.
+ )} + {watchList.length > 0 && ( +{entry.storeName}
++ #{entry.storeId} — {entry.regionName || 'Region unbekannt'} +
++ Letzter Status:{' '} + {entry.lastTeamSearchStatus === 1 + ? 'Suchend' + : entry.lastTeamSearchStatus === 0 + ? 'Nicht suchend' + : 'Unbekannt'} +
++ Es gibt ungespeicherte Änderungen. Bitte "Speichern" klicken. +
+ )} +