const { formatDate } = require('../core/utils.js'); module.exports = { timeout: 10000, immediate: true, name: 'Receipt Day Announcements', data: { channelId: process.env.NODE_ENV === 'development' ? '1468186493251227658' : '1462060674766344370', targetHour: 0, targetMinute: 1 }, async tick(client, timer) { //format date because isostring is utc duh try { const today = new Date(); const lastMonday = new Date(today); lastMonday.setDate(today.getDate() - ((today.getDay() === 0) ? 6 : today.getDay() - 1)); const startDate = formatDate(lastMonday); const nextSunday = new Date(lastMonday); nextSunday.setDate(lastMonday.getDate() + 6); const endDate = formatDate(nextSunday); // 0 1 2 3 4 5 6 // S M T W T F S let db = await client.localDB; const channel = await client.channels.fetch(timer.data.channelId); const config = await (await db.prepare(`SELECT weekly_budget, last_date_msg_receipts FROM bot_config`).get()); const existingBudget = db.prepare(`SELECT id FROM weekly_budgets WHERE start_date = ?`).get(startDate); if (!existingBudget) { await channel.send(`Format date last monday ${lastMonday} as startDate Format date next sunday ${nextSunday} as endDate`); await channel.send(`\`\`\`SELECT id FROM weekly_budgets WHERE start_date = ${startDate}\`\`\` ${JSON.stringify(existingBudget)}`); console.log(`No budget found for week starting ${startDate}.`); const response = await fetch(`https://api.frankfurter.dev/v1/latest?amount=1&from=EUR&to=SEK`); if (!response.ok) await channel.send(`Failed to fetch exchange rate:\n${response.statusText}`); const data = await response.json(); //await channel.send(`Fetched new exchange rate:\n${JSON.stringify(data)}`); await channel.send(`Reset weekly budget to ${config.weekly_budget}€ / ${config.weekly_budget*data.rates.SEK} kr`); db.prepare(` INSERT INTO weekly_budgets (start_date, end_date, budget_amount, exchange_rate) VALUES (?, ?, ?, ?) `).run(startDate, endDate, config.weekly_budget, data.rates.SEK); await channel.send(`\`\`\`INSERT INTO weekly_budgets (start_date, end_date, budget_amount, exchange_rate) VALUES (${startDate}, ${endDate}, ${config.weekly_budget}, ${data.rates.SEK})\`\`\``); } else { console.log(`budget found for week starting ${startDate}.`); } const notification = db.prepare(` SELECT EXISTS ( SELECT 1 FROM bot_config WHERE date(last_date_msg_receipts, 'localtime') = date('now', 'localtime') ) as was_sent_today `).get(); const debug = db.prepare(` SELECT date(last_date_msg_receipts, 'localtime') AS last_date, datetime('now', 'localtime') AS current_time_full, (date(last_date_msg_receipts, 'localtime') = date('now', 'localtime')) AS was_sent_today FROM bot_config LIMIT 1; `).get(); if (!notification.was_sent_today) { await channel.send(`\`\`\`SELECT date(last_date_msg_receipts, 'localtime') AS last_date, datetime('now', 'localtime') AS current_time_full, (date(last_date_msg_receipts, 'localtime') = date('now', 'localtime')) AS was_sent_today FROM bot_config LIMIT 1;\`\`\` ${JSON.stringify(debug)}`); const currentDate = new Date().toLocaleDateString('en-GB', { weekday: 'long', day: '2-digit', month: '2-digit', year: 'numeric' }); await channel.send(`${currentDate}`); console.log("No notification today, sending..."); db.prepare(` UPDATE bot_config SET last_date_msg_receipts = CURRENT_TIMESTAMP WHERE id = 1 `).run(); } else { console.log("Notification already sent"); } } catch (error) { console.error('[TIMER] Error:', error); } finally { // 2. Schedule the NEXT tick manually await this.scheduleNext(client, timer); } }, async scheduleNext(client, timer) { const now = new Date(); const next = new Date(); next.setHours(timer.data.targetHour, timer.data.targetMinute, 0, 0); if (next <= now) { next.setDate(next.getDate() + 1); } const delay = next.getTime() - now.getTime(); if (timer.instance) clearTimeout(timer.instance); timer.instance = setTimeout(() => { this.tick(client, timer); }, delay); const channel = await client.channels.fetch(timer.data.channelId); //if (channel) await channel.send(`Next message scheduled for: ${next.toLocaleString()} with ms delta of ${delay} / ${delay/3600000}`); console.log(`[TIMER] Next message scheduled for: ${next.toLocaleString()}`); } };