budget-go/frontend/js/chart/monthThreshold.js
2025-03-26 12:34:05 +01:00

68 lines
1.4 KiB
JavaScript

import { isInRange } from '../lib/dateFilter'
const getDate = (value) => {
const d = new Date(value)
let month = d.getUTCMonth() + 1
const year = d.getUTCFullYear()
if (month < 10) {
month = `0${month}`
}
return `${month}/${year}`
}
const compute = (transactions, cats, dateFrom, dateTo) => {
let categories = {}
let datas = {}
cats.forEach((value) => {
if (value.month_threshold > 0) {
categories[value.id.toString()] = value
}
})
transactions.forEach((value) => {
if (value.category === null || !Object.hasOwn(categories, value.category.id)) {
return
}
if (!isInRange(value.date, dateFrom, dateTo)) {
return
}
const date = getDate(value.date)
if (!Object.hasOwn(datas, date)) {
datas[date] = {}
}
if (!Object.hasOwn(datas[date], value.category.id.toString())) {
datas[date][value.category.id.toString()] = 0
}
datas[date][value.category.id.toString()] += value.debit - value.credit
})
for (let dataKey in datas) {
for (let catKey in datas[dataKey]) {
if (datas[dataKey][catKey] < categories[catKey].month_threshold) {
delete datas[dataKey][catKey]
} else {
datas[dataKey][catKey] = {
amount: datas[dataKey][catKey],
category: categories[catKey],
}
}
}
if (Object.keys(datas[dataKey]).length === 0) {
delete datas[dataKey]
}
}
return datas
}
export { compute }