Lumi/plugins/echonomy-framework/stats.js
2026-05-30 20:37:42 +02:00

69 lines
2.0 KiB
JavaScript

function getProfileStats({ db, userId }) {
if (!userId) {
return { stats: [] };
}
const account = db
.prepare("SELECT balance FROM echonomy_accounts WHERE user_id = ?")
.get(userId);
const earned = db
.prepare(
"SELECT COALESCE(SUM(amount), 0) AS total FROM echonomy_transactions " +
"WHERE to_user_id = ? AND (from_user_id IS NULL OR from_user_id = '')"
)
.get(userId);
const spent = db
.prepare(
"SELECT COALESCE(SUM(amount), 0) AS total FROM echonomy_transactions " +
"WHERE from_user_id = ? AND (to_user_id IS NULL OR to_user_id = '')"
)
.get(userId);
const transfersOut = db
.prepare(
"SELECT COALESCE(SUM(amount), 0) AS total FROM echonomy_transactions " +
"WHERE from_user_id = ? AND to_user_id IS NOT NULL AND to_user_id != ''"
)
.get(userId);
const transfersIn = db
.prepare(
"SELECT COALESCE(SUM(amount), 0) AS total FROM echonomy_transactions " +
"WHERE to_user_id = ? AND from_user_id IS NOT NULL AND from_user_id != ''"
)
.get(userId);
return {
stats: [
{ label: "Balance", value: account?.balance ?? 0 },
{ label: "Total earned", value: earned?.total ?? 0 },
{ label: "Total spent", value: spent?.total ?? 0 },
{ label: "Given to others", value: transfersOut?.total ?? 0 },
{ label: "Received from others", value: transfersIn?.total ?? 0 }
]
};
}
function getLeaderboards({ db, limit = 10 }) {
const rows = db
.prepare(
"SELECT user_profiles.internal_username AS username, echonomy_accounts.balance AS value " +
"FROM echonomy_accounts " +
"JOIN user_profiles ON user_profiles.id = echonomy_accounts.user_id " +
"ORDER BY echonomy_accounts.balance DESC LIMIT ?"
)
.all(limit);
return {
boards: [
{
title: "Top balances",
valueLabel: "Balance",
rows
}
]
};
}
module.exports = {
getProfileStats,
getLeaderboards
};