Journal für abholungen

This commit is contained in:
2026-01-04 01:37:36 +01:00
parent 1c12bf6bd1
commit 8b0326bac9
8 changed files with 1501 additions and 3 deletions

View File

@@ -5,8 +5,9 @@ const { DEFAULT_SETTINGS } = require('./adminConfig');
const notificationService = require('./notificationService');
const { readConfig, writeConfig } = require('./configStore');
const { readStoreWatch, writeStoreWatch } = require('./storeWatchStore');
const { readJournal, writeJournal } = require('./journalStore');
const { setStoreStatus, persistStoreStatusCache } = require('./storeStatusCache');
const { sendDormantPickupWarning } = require('./notificationService');
const { sendDormantPickupWarning, sendJournalReminderNotification } = require('./notificationService');
const { ensureSession, withSessionRetry } = require('./sessionRefresh');
function wait(ms) {
@@ -32,6 +33,48 @@ function randomDelayMs(minSeconds = 10, maxSeconds = 120) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function startOfDay(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}
function isSameDay(a, b) {
return (
a &&
b &&
a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate()
);
}
function addMonths(date, months) {
const copy = new Date(date.getTime());
copy.setMonth(copy.getMonth() + months);
return copy;
}
function getIntervalMonths(interval) {
if (interval === 'monthly') {
return 1;
}
if (interval === 'quarterly') {
return 3;
}
return 12;
}
function getNextOccurrence(baseDate, intervalMonths, todayStart) {
if (!baseDate || Number.isNaN(baseDate.getTime())) {
return null;
}
let candidate = startOfDay(baseDate);
const guardYear = todayStart.getFullYear() + 200;
while (candidate < todayStart && candidate.getFullYear() < guardYear) {
candidate = startOfDay(addMonths(candidate, intervalMonths));
}
return candidate;
}
function resolveSettings(settings) {
if (!settings) {
return { ...DEFAULT_SETTINGS };
@@ -555,6 +598,7 @@ function scheduleConfig(sessionId, config, settings) {
sessionStore.clearJobs(sessionId);
scheduleDormantMembershipCheck(sessionId);
const watchScheduled = scheduleStoreWatchers(sessionId, resolvedSettings);
scheduleJournalReminders(sessionId);
const entries = Array.isArray(config) ? config : [];
const activeEntries = entries.filter((entry) => entry.active);
if (activeEntries.length === 0) {
@@ -770,6 +814,78 @@ async function runDormantMembershipCheck(sessionId, options = {}) {
await checkDormantMembers(sessionId, options);
}
async function checkJournalReminders(sessionId) {
const session = sessionStore.get(sessionId);
if (!session?.profile?.id) {
return;
}
const profileId = session.profile.id;
const entries = readJournal(profileId);
if (!Array.isArray(entries) || entries.length === 0) {
return;
}
const todayStart = startOfDay(new Date());
const todayLabel = todayStart.toISOString().slice(0, 10);
let updated = false;
for (const entry of entries) {
if (!entry?.reminder?.enabled || !entry.pickupDate) {
continue;
}
const intervalMonths = getIntervalMonths(entry.reminder.interval);
const baseDate = new Date(`${entry.pickupDate}T00:00:00`);
const occurrence = getNextOccurrence(baseDate, intervalMonths, todayStart);
if (!occurrence) {
continue;
}
const daysBefore = Number.isFinite(entry.reminder.daysBefore)
? Math.max(0, entry.reminder.daysBefore)
: 42;
const reminderDate = new Date(occurrence.getTime());
reminderDate.setDate(reminderDate.getDate() - daysBefore);
if (!isSameDay(reminderDate, todayStart)) {
continue;
}
if (entry.lastReminderAt === todayLabel) {
continue;
}
await sendJournalReminderNotification({
profileId,
storeName: entry.storeName || `Store ${entry.storeId || ''}`,
pickupDate: occurrence,
reminderDate,
note: entry.note || ''
});
entry.lastReminderAt = todayLabel;
entry.updatedAt = new Date().toISOString();
updated = true;
}
if (updated) {
writeJournal(profileId, entries);
}
}
function scheduleJournalReminders(sessionId) {
const cronExpression = '0 8 * * *';
const job = cron.schedule(
cronExpression,
() => {
checkJournalReminders(sessionId).catch((error) => {
console.error('[JOURNAL] Erinnerung fehlgeschlagen:', error.message);
});
},
{ timezone: 'Europe/Berlin' }
);
sessionStore.attachJob(sessionId, job);
setTimeout(() => {
checkJournalReminders(sessionId).catch((error) => {
console.error('[JOURNAL] Initiale Erinnerung fehlgeschlagen:', error.message);
});
}, randomDelayMs(30, 120));
}
module.exports = {
scheduleConfig,
runStoreWatchCheck,