Journal für abholungen
This commit is contained in:
83
services/journalStore.js
Normal file
83
services/journalStore.js
Normal file
@@ -0,0 +1,83 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const CONFIG_DIR = path.join(__dirname, '..', 'config');
|
||||
const IMAGE_ROOT = path.join(CONFIG_DIR, 'journal-images');
|
||||
|
||||
function ensureDir(dirPath) {
|
||||
if (!fs.existsSync(dirPath)) {
|
||||
fs.mkdirSync(dirPath, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
function ensureBaseDirs() {
|
||||
ensureDir(CONFIG_DIR);
|
||||
ensureDir(IMAGE_ROOT);
|
||||
}
|
||||
|
||||
function getJournalPath(profileId = 'shared') {
|
||||
return path.join(CONFIG_DIR, `${profileId}-pickup-journal.json`);
|
||||
}
|
||||
|
||||
function getProfileImageDir(profileId = 'shared') {
|
||||
return path.join(IMAGE_ROOT, String(profileId));
|
||||
}
|
||||
|
||||
function hydrateJournalFile(profileId) {
|
||||
ensureBaseDirs();
|
||||
const filePath = getJournalPath(profileId);
|
||||
if (!fs.existsSync(filePath)) {
|
||||
fs.writeFileSync(filePath, JSON.stringify([], null, 2));
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function readJournal(profileId) {
|
||||
const filePath = hydrateJournalFile(profileId);
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch (error) {
|
||||
console.error(`[JOURNAL] Konnte Journal für ${profileId} nicht lesen:`, error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeJournal(profileId, entries = []) {
|
||||
const filePath = hydrateJournalFile(profileId);
|
||||
fs.writeFileSync(filePath, JSON.stringify(entries, null, 2));
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function saveJournalImage(profileId, { id, filename, buffer }) {
|
||||
ensureBaseDirs();
|
||||
const profileDir = getProfileImageDir(profileId);
|
||||
ensureDir(profileDir);
|
||||
const safeName = filename.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
||||
const filePath = path.join(profileDir, safeName);
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
return {
|
||||
id,
|
||||
filename: safeName,
|
||||
filePath
|
||||
};
|
||||
}
|
||||
|
||||
function deleteJournalImage(profileId, filename) {
|
||||
if (!filename) {
|
||||
return;
|
||||
}
|
||||
const filePath = path.join(getProfileImageDir(profileId), filename);
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
readJournal,
|
||||
writeJournal,
|
||||
saveJournalImage,
|
||||
deleteJournalImage,
|
||||
getProfileImageDir
|
||||
};
|
||||
@@ -21,6 +21,22 @@ function formatDateLabel(dateInput) {
|
||||
}
|
||||
}
|
||||
|
||||
function formatDateOnly(dateInput) {
|
||||
try {
|
||||
const date = new Date(dateInput);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return 'unbekanntes Datum';
|
||||
}
|
||||
return date.toLocaleDateString('de-DE', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric'
|
||||
});
|
||||
} catch (_error) {
|
||||
return 'unbekanntes Datum';
|
||||
}
|
||||
}
|
||||
|
||||
async function sendNtfyNotification(adminNtfy, userNtfy, payload) {
|
||||
if (!adminNtfy?.enabled || !userNtfy?.enabled || !userNtfy.topic) {
|
||||
return;
|
||||
@@ -230,6 +246,34 @@ async function sendDormantPickupWarning({ profileId, storeName, storeId, reasonL
|
||||
});
|
||||
}
|
||||
|
||||
async function sendJournalReminderNotification({
|
||||
profileId,
|
||||
storeName,
|
||||
pickupDate,
|
||||
reminderDate,
|
||||
note
|
||||
}) {
|
||||
if (!profileId) {
|
||||
return;
|
||||
}
|
||||
const adminSettings = adminConfig.readSettings();
|
||||
const userSettings = readNotificationSettings(profileId);
|
||||
const title = `Erinnerung: Abholung bei ${storeName}`;
|
||||
const reminderLabel = formatDateOnly(reminderDate);
|
||||
const pickupLabel = formatDateOnly(pickupDate);
|
||||
const noteLine = note ? `Notiz: ${note}` : null;
|
||||
const messageLines = [
|
||||
`Geplante Abholung: ${pickupLabel}`,
|
||||
`Erinnerungstermin: ${reminderLabel}`,
|
||||
noteLine
|
||||
].filter(Boolean);
|
||||
await sendTelegramNotification(adminSettings.notifications?.telegram, userSettings.notifications?.telegram, {
|
||||
title,
|
||||
message: messageLines.join('\n'),
|
||||
priority: 'default'
|
||||
});
|
||||
}
|
||||
|
||||
async function sendAdminBookingErrorNotification({ profileId, profileEmail, storeName, storeId, pickupDate, error }) {
|
||||
const dateLabel = formatDateLabel(pickupDate);
|
||||
const storeLabel = storeName || storeId || 'Unbekannter Store';
|
||||
@@ -257,5 +301,6 @@ module.exports = {
|
||||
sendTestNotification,
|
||||
sendDesiredWindowMissedNotification,
|
||||
sendDormantPickupWarning,
|
||||
sendJournalReminderNotification,
|
||||
sendAdminBookingErrorNotification
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user