moy-buhgalter/rates.js

36 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const fs = require("fs");
const path = require("path");
// Курс валют: 1 USD/EUR в KZT (запись вручную, обновляется при /rate)
const RATES_FILE = path.join(__dirname, "rates.json");
function defaultRates() {
return { usd: 540, eur: 580, updated: null };
}
function readRates() {
try {
return { ...defaultRates(), ...JSON.parse(fs.readFileSync(RATES_FILE, "utf8")) };
} catch (_) {
return defaultRates();
}
}
function writeRates(r) {
fs.writeFileSync(RATES_FILE, JSON.stringify(r, null, 2));
}
function convert(amount, from) {
const r = readRates();
if (!from) return Math.round(amount);
const f = String(from).toLowerCase();
if (f === "kzt") return Math.round(amount);
const rate = r[f];
if (!rate) return null;
return Math.round(amount * rate);
}
function fmtRate() {
const r = readRates();
const d = r.updated ? new Date(r.updated).toLocaleDateString("ru-RU") : "не обновлён";
return `Курс (от 0${d}): USD=${r.usd} ₸, EUR=${r.eur} ₸`;
}
module.exports = { readRates, writeRates, convert, fmtRate };