Add basic receipt logging
This commit is contained in:
@@ -14,11 +14,21 @@ module.exports = {
|
|||||||
option.setName('amount')
|
option.setName('amount')
|
||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
.setDescription('Amount as int'))
|
.setDescription('Amount as int'))
|
||||||
|
.addBooleanOption(option =>
|
||||||
|
option.setName('override')
|
||||||
|
.setRequired(false)
|
||||||
|
.setDescription('Override budget of current period'))
|
||||||
)
|
)
|
||||||
.addSubcommand(subcommand =>
|
.addSubcommand(subcommand =>
|
||||||
subcommand
|
subcommand
|
||||||
.setName('show')
|
.setName('spendings')
|
||||||
.setDescription('not implemented')
|
.setDescription('View your grocery spendings for the current or previous week')
|
||||||
|
.addBooleanOption(option =>
|
||||||
|
option
|
||||||
|
.setName('lastweek')
|
||||||
|
.setDescription('Show spendings from the previous budget cycle instead of the current one')
|
||||||
|
.setRequired(false)
|
||||||
|
)
|
||||||
),
|
),
|
||||||
async execute(interaction) {
|
async execute(interaction) {
|
||||||
console.log('budget command entrypoint');
|
console.log('budget command entrypoint');
|
||||||
@@ -31,7 +41,7 @@ module.exports = {
|
|||||||
console.log('budget command denied');
|
console.log('budget command denied');
|
||||||
await interaction.reply('This command may only be invoked by Miffy!');
|
await interaction.reply('This command may only be invoked by Miffy!');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
console.log(`Switcching on sub ${interaction.options.getSubcommand()}`);
|
console.log(`Switcching on sub ${interaction.options.getSubcommand()}`);
|
||||||
switch (interaction.options.getSubcommand()) {
|
switch (interaction.options.getSubcommand()) {
|
||||||
case 'set':
|
case 'set':
|
||||||
@@ -40,7 +50,7 @@ module.exports = {
|
|||||||
db.prepare(`INSERT OR REPLACE INTO bot_config (id, weekly_budget) VALUES (1, ?)`).run(budget);
|
db.prepare(`INSERT OR REPLACE INTO bot_config (id, weekly_budget) VALUES (1, ?)`).run(budget);
|
||||||
await interaction.reply(`Budget set to ${budget}`);
|
await interaction.reply(`Budget set to ${budget}`);
|
||||||
break;
|
break;
|
||||||
case 'show':
|
case 'spendings':
|
||||||
console.log('budget command show');
|
console.log('budget command show');
|
||||||
await interaction.reply('Not implemented');
|
await interaction.reply('Not implemented');
|
||||||
break
|
break
|
||||||
36
core/db.js
36
core/db.js
@@ -38,23 +38,39 @@ async function initDB(db) {
|
|||||||
CREATE TABLE IF NOT EXISTS bot_config (
|
CREATE TABLE IF NOT EXISTS bot_config (
|
||||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
weekly_budget REAL DEFAULT 0,
|
weekly_budget REAL DEFAULT 0,
|
||||||
exchange_rate_eur_kr REAL DEFAULT 0,
|
last_date_msg_receipts DATE NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
last_budget_notification_date TEXT
|
|
||||||
);
|
);
|
||||||
`);
|
`);
|
||||||
await db.exec(`
|
await db.exec(`
|
||||||
CREATE TABLE IF NOT EXISTS grocery_budgets (
|
CREATE TABLE IF NOT EXISTS grocery_spendings (
|
||||||
ID INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
discord_id VARCHAR(50) NOT NULL,
|
discord_id VARCHAR(50) NOT NULL,
|
||||||
budget_spent REAL,
|
message_id VARCHAR(50) NOT NULL,
|
||||||
total_spent REAL
|
message_raw TEXT DEFAULT "-",
|
||||||
|
amount DECIMAL(10, 2) NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
budget_id INTEGER,
|
||||||
|
FOREIGN KEY (budget_id) REFERENCES weekly_budgets(id)
|
||||||
);
|
);
|
||||||
`);
|
`);
|
||||||
|
await db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS weekly_budgets (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
start_date DATE NOT NULL,
|
||||||
|
end_date DATE NOT NULL,
|
||||||
|
budget_amount DECIMAL(10, 2) NOT NULL,
|
||||||
|
exchange_rate DECIMAL(10, 6) NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT date_check CHECK (end_date > start_date)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_budget_dates ON weekly_budgets (start_date, end_date);
|
||||||
|
`);
|
||||||
|
|
||||||
|
|
||||||
// Optional: Initialize the row if it doesn't exist yet
|
|
||||||
await db.exec(`
|
await db.exec(`
|
||||||
INSERT OR IGNORE INTO bot_config (id, weekly_budget, last_budget_notification_date)
|
INSERT OR IGNORE INTO bot_config (id, weekly_budget)
|
||||||
VALUES (1, 0, NULL);
|
VALUES (1, 10);
|
||||||
`);
|
`);
|
||||||
console.log('[DATABASE] Created new DB table');
|
console.log('[DATABASE] Created new DB table');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,19 +6,40 @@ module.exports = {
|
|||||||
if (message.author.bot) return;
|
if (message.author.bot) return;
|
||||||
|
|
||||||
if(message.channel.id === '1462060674766344370') {
|
if(message.channel.id === '1462060674766344370') {
|
||||||
|
const CURRENCY_MAP = {
|
||||||
|
"222457277708369928": "EUR", // Minz
|
||||||
|
"372115788498468864": "SEK", // Miffy
|
||||||
|
};
|
||||||
|
|
||||||
let reply = "";
|
let reply = "";
|
||||||
let db = await message.client.localDB;
|
let db = await message.client.localDB;
|
||||||
const receiptsChannel = message.channel;
|
const receiptsChannel = message.channel;
|
||||||
const authorId = message.author.id;
|
const authorId = message.author.id;
|
||||||
|
|
||||||
let budgets = await db.prepare(`SELECT * FROM grocery_budgets WHERE discord_id = ?`).get(authorId);
|
|
||||||
let weeklyBudget = await (await db.prepare(`SELECT weekly_budget FROM bot_config`).get()).weekly_budget;
|
const currentBudget = db.prepare(`
|
||||||
|
SELECT id, exchange_rate, budget_amount FROM weekly_budgets
|
||||||
console.log(weeklyBudget, budgets);
|
WHERE date('now', 'localtime') BETWEEN start_date AND end_date
|
||||||
if (budgets === undefined) {
|
ORDER BY created_at DESC
|
||||||
console.log(`No budget row in db for ${authorId}`);
|
LIMIT 1
|
||||||
db.prepare(`INSERT OR REPLACE INTO grocery_budgets (discord_id, budget_spent, total_spent) VALUES (?,0,0)`).run(authorId);
|
`).get();
|
||||||
|
|
||||||
|
if (message.content === "fuck") {
|
||||||
|
|
||||||
|
let lastSpend = db.prepare(`
|
||||||
|
SELECT id, amount, message_raw, created_at
|
||||||
|
FROM grocery_spendings
|
||||||
|
WHERE discord_id = ? AND budget_id = ?
|
||||||
|
ORDER BY created_at DESC, id DESC
|
||||||
|
LIMIT 1
|
||||||
|
`).get(authorId, currentBudget.id);
|
||||||
|
if (lastSpend) {
|
||||||
|
db.prepare(`DELETE FROM grocery_spendings WHERE id = ?`).run(lastSpend.id);
|
||||||
|
await message.reply(`Your last spending of ${lastSpend.amount.toFixed(2)}€ has been deleted.`);
|
||||||
|
} else {
|
||||||
|
await message.reply("You don't have any entries within the current budgeting period!");
|
||||||
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let matches = [];
|
let matches = [];
|
||||||
@@ -27,19 +48,56 @@ module.exports = {
|
|||||||
lines.forEach(line => {0
|
lines.forEach(line => {0
|
||||||
if (line.startsWith('-')) {
|
if (line.startsWith('-')) {
|
||||||
console.log(`Matching on line ${line}`);
|
console.log(`Matching on line ${line}`);
|
||||||
const regex = /-(?=[0-9])([0-9]*,?[0-9]*)/m;
|
const regex = /-(?=[0-9])([0-9]*[.,]?[0-9]*)/m;
|
||||||
let match = regex.exec(line)
|
let match = regex.exec(line)
|
||||||
console.log(match);
|
console.log(match);
|
||||||
additionalSpent = additionalSpent + parseFloat(match[1]);
|
if (match) {
|
||||||
|
additionalSpent = additionalSpent + parseFloat(match[1].replace(',', '.'));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (additionalSpent > 0) {
|
|
||||||
db.prepare(`UPDATE grocery_budgets SET budget_spent = ?, total_spent = ? WHERE discord_id = ?`).run(budgets.budget_spent + additionalSpent, budgets.total_spent + additionalSpent, authorId);
|
|
||||||
let remainingBudget = weeklyBudget - (budgets.budget_spent + additionalSpent);
|
|
||||||
|
|
||||||
reply = `${message.author.globalName} spent ${additionalSpent} of their budget.\nThey have ${remainingBudget} remaining.`;
|
if (additionalSpent > 0) {
|
||||||
await receiptsChannel.send(reply);
|
|
||||||
|
|
||||||
|
const currency = CURRENCY_MAP[authorId] || "EUR"
|
||||||
|
switch (currency) {
|
||||||
|
case "SEK":
|
||||||
|
additionalSpent = additionalSpent / currentBudget.exchange_rate;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
db.prepare(`
|
||||||
|
INSERT INTO grocery_spendings (
|
||||||
|
discord_id,
|
||||||
|
message_id,
|
||||||
|
message_raw,
|
||||||
|
amount,
|
||||||
|
budget_id
|
||||||
|
) VALUES (?, ?, ?, ?, ?)
|
||||||
|
`).run(
|
||||||
|
authorId,
|
||||||
|
message.id,
|
||||||
|
message.content,
|
||||||
|
additionalSpent,
|
||||||
|
currentBudget.id
|
||||||
|
);
|
||||||
|
|
||||||
|
const allSpendings = db.prepare(`
|
||||||
|
SELECT amount
|
||||||
|
FROM grocery_spendings
|
||||||
|
WHERE budget_id = ? AND discord_id = ?
|
||||||
|
`).all(currentBudget.id, authorId);
|
||||||
|
|
||||||
|
const totalSpent = allSpendings.reduce((acc, entry) => {
|
||||||
|
return acc + entry.amount;
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
reply = `${message.author.globalName} spent ${additionalSpent}€ / ${(additionalSpent * currentBudget.exchange_rate).toFixed(2)} kr of their budget.\nThey have ${currentBudget.budget_amount - totalSpent}€ / ${((currentBudget.budget_amount - totalSpent) * currentBudget.exchange_rate).toFixed(2)} kr remaining.`;
|
||||||
|
await message.reply(reply);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,29 +8,69 @@ module.exports = {
|
|||||||
targetMinute: 1
|
targetMinute: 1
|
||||||
},
|
},
|
||||||
async tick(client, timer) {
|
async tick(client, timer) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. Send the message
|
const today = new Date();
|
||||||
const currentDate = new Date().toLocaleDateString('en-GB', {
|
const lastMonday = new Date(today);
|
||||||
weekday: 'long',
|
lastMonday.setDate(today.getDate() - ((today.getDay() === 0) ? 6 : today.getDay() - 1));
|
||||||
day: '2-digit',
|
const startDate = lastMonday.toISOString().split('T')[0];
|
||||||
month: '2-digit',
|
|
||||||
year: 'numeric'
|
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 channel = await client.channels.fetch(timer.data.channelId);
|
||||||
await channel.send(`${currentDate}`);
|
|
||||||
if (currentDate.startsWith('Sunday')) {
|
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`);
|
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}`);
|
if (!response.ok) await channel.send(`Failed to fetch exchange rate:\n${response.statusText}`);
|
||||||
let db = await client.localDB;
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
db.prepare(`UPDATE bot_config SET exchange_rate_eur_kr = ? WHERE id = 1`).run(data.rates.SEK);
|
//await channel.send(`Fetched new exchange rate:\n${JSON.stringify(data)}`);
|
||||||
let weeklyBudget = await (await db.prepare(`SELECT weekly_budget FROM bot_config`).get()).weekly_budget;
|
//await channel.send(`Reset weekly budget to ${weeklyBudget}EUR / ${weeklyBudget*data.rates.SEK}SEK`);
|
||||||
await channel.send(`Fetched new exchange rate:\n${JSON.stringify(data)}`);
|
|
||||||
db.prepare(`UPDATE grocery_budgets SET budget_spent = 0`).run();
|
|
||||||
await channel.send(`Reset weekly budget to ${weeklyBudget}EUR / ${weeklyBudget*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) {
|
} catch (error) {
|
||||||
console.error('[TIMER] Error:', error);
|
console.error('[TIMER] Error:', error);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -58,7 +98,7 @@ module.exports = {
|
|||||||
}, delay);
|
}, delay);
|
||||||
|
|
||||||
const channel = await client.channels.fetch(timer.data.channelId);
|
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}`);
|
//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()}`);
|
console.log(`[TIMER] Next message scheduled for: ${next.toLocaleString()}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Reference in New Issue
Block a user