Files
general-purpose-bot/timers/receiptTimer.js
2026-01-19 13:59:06 +01:00

104 lines
4.0 KiB
JavaScript

module.exports = {
timeout: 1000,
immediate: false,
name: 'Receipt Day Announcements',
data: {
channelId: '1462060674766344370',
targetHour: 0,
targetMinute: 1
},
async tick(client, timer) {
try {
const today = new Date();
const lastMonday = new Date(today);
lastMonday.setDate(today.getDate() - ((today.getDay() === 0) ? 6 : today.getDay() - 1));
const startDate = lastMonday.toISOString().split('T')[0];
const nextSunday = new Date(lastMonday);
nextSunday.setDate(lastMonday.getDate() + 6);
const endDate = nextSunday.toISOString().split('T')[0];
// 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) {
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}EUR / ${config.weekly_budget*data.rates.SEK}SEK`);
db.prepare(`
INSERT INTO weekly_budgets (start_date, end_date, budget_amount, exchange_rate)
VALUES (?, ?, ?, ?)
`).run(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) = date('now', 'localtime')
) as was_sent_today
`).get();
if (!notification.was_sent_today) {
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()}`);
}
};