refactoring
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -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));
|
||||
|
||||
84
services/storeWatchStore.js
Normal file
84
services/storeWatchStore.js
Normal file
@@ -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
|
||||
};
|
||||
Reference in New Issue
Block a user