Open source personal finance application
feat(getTotal): change getTotalOfTrnsIds to new getTotal
ilkome8ce64af4a057
diff --git a/components/stat/ChartLines.vue b/components/stat/ChartLines.vueindex d22f781e..5f216c6c 100644--- a/components/stat/ChartLines.vue+++ b/components/stat/ChartLines.vue@@ -1,10 +1,11 @@<script lang="ts">import { Chart } from 'highcharts-vue'-import { getCatsIds } from '~/components/categories/getCategories'-import { getTrnsIds } from '~/components/trns/getTrns'import chartOptions from '~/components/stat/chartOptions'import useChart from '~/components/chart/useChart'import useFilter from '~/modules/filter/useFilter'+import { getCatsIds } from '~/components/categories/getCategories'+import { getTotal } from '~/components/trns/getTotal'+import { getTrnsIds } from '~/components/trns/getTrns'export default defineComponent({components: { Chart },@@ -87,8 +88,8 @@ export default defineComponent({const periodName = this.filterPeriodNameAllReplacedToYearconst chartPeriods = this.$store.state.chart.periodsconst trnsItems = this.$store.state.trns.items- const allTrnsIds = Object.keys(trnsItems)const catsItems = this.$store.state.categories.items+ const walletsItems = this.$store.state.wallets.itemsconst storeFilter = this.$store.state.filter// diff periods from oldest trn and today@@ -101,11 +102,6 @@ export default defineComponent({const incomesData = []const expensesData = []const totalData = []- const balanceData = []-- const dateStart = this.$day().endOf(periodName).subtract(periodsToShow, periodName).valueOf()- const trnsIdsBeforeDate = allTrnsIds.filter(id => trnsItems[id].date < dateStart)- const totalStart = this.$store.getters['trns/getTotalOfTrnsIds'](trnsIdsBeforeDate, true)for (let index = 0; index < periodsToShow; index++) {// count total period@@ -122,18 +118,12 @@ export default defineComponent({date: periodDate,})- const allTrnsIds = getTrnsIds({+ const { incomeTransactions, expenseTransactions, sumTransactions } = getTotal({+ trnsIds,trnsItems,- periodName,- date: periodDate,+ walletsItems,})- const balanceDateStart = this.$day().endOf(periodName).subtract(index, periodName).valueOf()- const balanceTrnsIds = allTrnsIds.filter(id => trnsItems[id].date > dateStart && trnsItems[id].date < balanceDateStart)- const balanceTotal = this.$store.getters['trns/getTotalOfTrnsIds'](balanceTrnsIds, true)-- const periodTotal = this.$store.getters['trns/getTotalOfTrnsIds'](trnsIds)-let format = 'MM'if (periodName === 'day')format = 'D.MM'@@ -148,25 +138,18 @@ export default defineComponent({// IncomesincomesData.unshift({date: periodDate,- y: Number(`${periodTotal.incomes.toFixed()}`),+ y: incomeTransactions,})// ExpensesexpensesData.unshift({date: periodDate,- y: Number(`${periodTotal.expenses.toFixed()}`),+ y: expenseTransactions,})// TotaltotalData.unshift({date: periodDate,- y: Number(`${(periodTotal.total).toFixed()}`),- })-- // Balance- totalStart.total = totalStart.total + Number(`${(balanceTotal.total).toFixed()}`)- balanceData.unshift({- date: periodDate,- y: totalStart.total,+ y: sumTransactions,})categories.unshift(name)@@ -214,16 +197,6 @@ export default defineComponent({marker: {lineColor: 'var(--c-expenses-1)',},- // }, {- // // Balance- // visible: true,- // type: 'areaspline',- // name: 'Balance',- // color: '#c1c1c1',- // data: balanceData,- // marker: {- // lineColor: '#c1c1c1',- // },}, {// Fake data to make good hover on bar chartzIndex: 1,diff --git a/components/stat/Laptop.vue b/components/stat/Laptop.vueindex 9239bfd7..c6f73e17 100644--- a/components/stat/Laptop.vue+++ b/components/stat/Laptop.vue@@ -27,15 +27,15 @@ const isShowGroup = (type) => {const isShowTrns = computed(() => {const proceed = statPage.activeTab === 'details'- && statPage.average?.incomes !== 0- && statPage.average?.expenses !== 0+ && statPage.average?.income !== 0+ && statPage.average?.expense !== 0&& $store.getters['trns/selectedTrnsIdsWithDate'].length > 0return proceed})const isShowGroupTrns = computed(() => {const p1 = statPage.activeTab === 'incomes' || statPage.activeTab === 'expenses'- const p2 = statPage.average.total === 0+ const p2 = statPage.average.sum === 0return (p1 || p2) && statPage.activeTab !== 'history'})diff --git a/components/stat/sum/Group.vue b/components/stat/sum/Group.vueindex 40969118..7cf9cbc4 100644--- a/components/stat/sum/Group.vue+++ b/components/stat/sum/Group.vue@@ -27,9 +27,10 @@ const typeNumber = computed(() => moneyTypes.find(t => t.id === `${props.typeTex)//- Average+ //- TODO: change everything to expense and incomeLazyStatSummaryRowItemView(v-if="statPage.average[typeText] !== 0"- :amount="statPage.average[typeText]"+ :amount="statPage.average[typeText === 'expenses' ? 'expense' : 'income']":title="$t(`money.average.${typeText}`)":type="typeNumber")diff --git a/components/stat/sum/Total.vue b/components/stat/sum/Total.vueindex 6ced78ff..4b41d2a6 100644--- a/components/stat/sum/Total.vue+++ b/components/stat/sum/Total.vue@@ -21,9 +21,9 @@ const statAverage = computed(() => $store.getters['stat/statAverage']))LazyStatSummaryRowItemView(- v-if="statAverage.incomes - statAverage.expenses !== 0"- :type="(statAverage.incomes - statAverage.expenses) > 0 ? 1 : 0"- :amount="statAverage.incomes - statAverage.expenses"+ v-if="statAverage.sum !== 0"+ :type="statAverage.sum > 0 ? 1 : 0"+ :amount="statAverage.sum":title="$t('money.averageTotal')")</template>diff --git a/components/trns/getTotal.ts b/components/trns/getTotal.tsindex 782607ff..686258e0 100644--- a/components/trns/getTotal.ts+++ b/components/trns/getTotal.ts@@ -23,15 +23,7 @@ export function getAmountInRate({return amount}-export function getTotal({- baseRate,- rates,- transferCategoriesIds,- trnsIds,- trnsItems,- walletsIds,- walletsItems,-}: {+interface TotalProps {trnsIds: TrnID[]trnsItems: Record<TrnID, TrnItem>walletsItems: Record<WalletID, WalletItem>@@ -39,7 +31,20 @@ export function getTotal({walletsIds?: WalletID[]baseRate?: string // TODO: add typingsrates?: Record<string, number> // TODO: add typings-}) {+}++export interface TotalReturns {+ incomeTransactions: number+ expenseTransactions: number+ sumTransactions: number+ incomeTransfers: number+ expenseTransfers: number+ sumTransfers: number+}++export function getTotal(props: TotalProps): TotalReturns {+ const { baseRate, rates, transferCategoriesIds, trnsIds, trnsItems, walletsIds, walletsItems } = props+function getFormattedAmount(amount: number, currency: string) {return getAmountInRate({amount,@@ -49,15 +54,10 @@ export function getTotal({})}- // Transactionslet incomeTransactions = 0let expenseTransactions = 0- let sumTransactions = 0-- // Transferslet incomeTransfers = 0let expenseTransfers = 0- let sumTransfers = 0for (const trnId of trnsIds) {const trn = trnsItems[trnId]@@ -135,8 +135,8 @@ export function getTotal({}// Total- sumTransactions = incomeTransactions - expenseTransactions- sumTransfers = incomeTransfers - expenseTransfers+ const sumTransactions = incomeTransactions - expenseTransactions+ const sumTransfers = incomeTransfers - expenseTransfersreturn {incomeTransactions,diff --git a/store/stat/getters.js b/store/stat/getters.tssimilarity index 67%rename from store/stat/getters.jsrename to store/stat/getters.tsindex f7ff758a..ee96909c 100644--- a/store/stat/getters.js+++ b/store/stat/getters.ts@@ -1,67 +1,22 @@import dayjs from 'dayjs'-import { getCatsIds } from '~/components/categories/getCategories'+import type { TotalReturns } from '~/components/trns/getTotal'+import { getCatsIds, getTransferCategoriesIds } from '~/components/categories/getCategories'+import { getTotal } from '~/components/trns/getTotal'import { getTrnsIds } from '~/components/trns/getTrns'export default {- /**- * Average stat used statByPeriods.- *- * @return {Object} Object with total- * @return {Number} return[date].incomes- * @return {Number} return[date].expenses- * @return {Number} return[date].total- */- statAverage(_state, getters) {- const statPeriods = getters.statByPeriods-- let incomes = 0- let expenses = 0- let total = 0- const periodsCounter = {- incomes: 0,- expenses: 0,- total: 0,- }-- for (const idx in statPeriods) {- const period = statPeriods[idx]- incomes = incomes + period.incomes- periodsCounter.incomes = periodsCounter.incomes + 1-- expenses = expenses + period.expenses- periodsCounter.expenses = periodsCounter.expenses + 1-- if (incomes > 0 && expenses > 0) {- total = incomes - expenses- periodsCounter.total = periodsCounter.total + 1- }- }-- return {- incomes: incomes !== 0 ? Math.ceil(incomes / periodsCounter.incomes) : 0,- expenses: expenses !== 0 ? Math.ceil(expenses / periodsCounter.expenses) : 0,- total: total !== 0 ? Math.ceil(total / periodsCounter.total) : 0,- }- },-- /**- * Stat by periods with period name and total.- *- * @return {Object} Object with periods- * @return {String} return[date].date - valueOf date- * @return {Number} return[date].incomes- * @return {Number} return[date].expenses- * @return {Number} return[date].total- */- statByPeriods(_state, _getters, rootState, rootGetters) {- const trns = rootState.trns.items+ statAverage(_state, _getters, rootState, rootGetters) {+ const trnsItems = rootState.trns.items+ const walletsItems = rootState.wallets.items+ const baseRate = rootState.currencies.base+ const rates = rootState.currencies.ratesconst transferCategoryId = rootGetters['categories/transferCategoryId']const trnsIds = rootGetters['trns/selectedTrnsIds']const periodName = rootState.filter.periodif (periodName === 'all')return- const oldestTrn = trns[rootGetters['trns/firstCreatedTrnId']]+ const oldestTrn = trnsItems[rootGetters['trns/firstCreatedTrnId']]if (!oldestTrn)return@@ -69,25 +24,63 @@ export default {let periodsToShow = dayjs().endOf(periodName).diff(oldestTrnDate, periodName) + 1periodsToShow = rootState.chart.periods[periodName].showedPeriods >= periodsToShow ? periodsToShow : rootState.chart.periods[periodName].showedPeriods- const stat = {}+ const statPeriods: Record<string, { date: number; total: TotalReturns }> = {}+// Start from 1 to remove last period from averagefor (let period = 1; period < periodsToShow; period++) {const dateStartOfPeriod = dayjs().subtract(period, periodName).startOf(periodName)const dateEndOfPeriod = dayjs().subtract(period, periodName).endOf(periodName)const ids = trnsIds.filter(trnId =>- trns[trnId].date >= dateStartOfPeriod- && trns[trnId].date <= dateEndOfPeriod- && trns[trnId].categoryId !== transferCategoryId,+ trnsItems[trnId].date >= dateStartOfPeriod+ && trnsItems[trnId].date <= dateEndOfPeriod+ && trnsItems[trnId].categoryId !== transferCategoryId,)- stat[dateStartOfPeriod.valueOf()] = {+ const total = getTotal({+ baseRate,+ rates,+ trnsIds: ids,+ trnsItems,+ walletsItems,+ })++ statPeriods[dateStartOfPeriod.valueOf()] = {date: dateStartOfPeriod.valueOf(),- ...rootGetters['trns/getTotalOfTrnsIds'](ids),+ total,}}- return stat+ let income = 0+ let expense = 0+ let sum = 0+ let periodsCounter = 0++ for (const idx in statPeriods) {+ const period = statPeriods[idx]+ periodsCounter += 1++ income += period.total.incomeTransactions+ expense += period.total.expenseTransactions+ sum = income - expense+ }++ const delimiter = periodsCounter++ // When just this period and last+ if (delimiter === 1) {+ return {+ income: 0,+ expense: 0,+ sum: 0,+ }+ }++ return {+ income: Math.ceil(income / delimiter),+ expense: Math.ceil(expense / delimiter),+ sum: Math.ceil(sum / delimiter),+ }},isFirstPeriodSelected(state, getters, rootState, rootGetters) {@@ -118,27 +111,16 @@ export default {}},- /**- * Stat by periods with period name and total.- *- * @return {Object}- * @return {Object} categories- * @return {Number} expensesBiggest- * @return {Array} expensesCategoriesIds - categories ids- * @return {Number} incomesBiggest- * @return {Array} incomesCategoriesIds - categories ids- * @return {Object} total- * @return {Number} total.expenses- * @return {Number} total.incomes- * @return {Number} total.total- *- */- statCurrentPeriod(_state, getters, rootState, rootGetters) {+ statCurrentPeriod(_state, _getters, rootState, rootGetters) {const trnsItems = rootState.trns.items- const catsItems = rootState.categories.items+ const categoriesItems = rootState.categories.items+ const walletsItems = rootState.wallets.items+ const baseRate = rootState.currencies.base+ const rates = rootState.currencies.ratesconst storeFilter = rootState.filter+ // const transferCategoriesIds = getTransferCategoriesIds(categoriesItems.value)- const categoriesIds = rootState.filter.catsIds.length > 0 ? getCatsIds(rootState.filter.catsIds, catsItems) : null+ const categoriesIds = rootState.filter.catsIds.length > 0 ? getCatsIds(rootState.filter.catsIds, categoriesItems) : nullconst walletsIds = storeFilter.walletsIds.length > 0 ? storeFilter.walletsIds : nullconst trnsIds = getTrnsIds({@@ -203,17 +185,40 @@ export default {return categoriesWithTrnsIds}- const categoriesWithTrnsIds = getCatsIdsWithTrnsIds(trnsIds)- const totalAllTrns = rootGetters['trns/getTotalOfTrnsIds'](trnsIds)+ const categoriesWithTrnsIds = getCatsIdsWithTrnsIds()++ const total = getTotal({+ baseRate,+ rates,+ trnsIds,+ trnsItems,+ walletsIds: [rootState.filter.walletsIds],+ // transferCategoriesIds,+ walletsItems,+ })// count total in categoriesconst categoriesTotal = {}for (const categoryId in categoriesWithTrnsIds) {const trnsIdsInCategory = categoriesWithTrnsIds[categoryId]- categoriesTotal[categoryId] = rootGetters['trns/getTotalOfTrnsIds'](trnsIdsInCategory)++ const totalInCategory = getTotal({+ baseRate,+ rates,+ trnsIds: trnsIdsInCategory,+ trnsItems,+ walletsIds: [rootState.filter.walletsIds],+ walletsItems,+ })++ // totalInCategory+ categoriesTotal[categoryId] = {+ incomes: totalInCategory.incomeTransactions,+ expenses: totalInCategory.expenseTransactions,+ }}- // separate catgories by incomes and expenses+ // separate categories by incomes and expensesconst statIncomes = {}const statExpenses = {}for (const categoryId in categoriesWithTrnsIds) {@@ -246,10 +251,10 @@ export default {const incomesCategoriesIds = sortCategoriesByTotal(statIncomes, 'incomes')const expensesCategoriesIds = sortCategoriesByTotal(statExpenses, 'expenses')- // get first item in sorted catgories+ // get first item in sorted categoriesfunction getBiggestAmount(categoriesTotal, categoriesIds, typeName) {const biggestAmount = categoriesIds[0]- return categoriesTotal[biggestAmount] && Math.abs(categoriesTotal[biggestAmount][typeName])+ return (categoriesTotal[biggestAmount] && Math.abs(categoriesTotal[biggestAmount][typeName])) || 0}// biggest@@ -258,16 +263,16 @@ export default {const stat = {categories: categoriesTotal,- total: totalAllTrns.total,+ total: total.sumTransactions,expenses: {biggest: expensesBiggest,categoriesIds: expensesCategoriesIds,- total: totalAllTrns.expenses,+ total: total.expenseTransactions,},incomes: {biggest: incomesBiggest,categoriesIds: incomesCategoriesIds,- total: totalAllTrns.incomes,+ total: total.incomeTransactions,},}diff --git a/store/trns/getters.js b/store/trns/getters.jsindex 792bf595..a9b9243b 100644--- a/store/trns/getters.js+++ b/store/trns/getters.js@@ -12,106 +12,6 @@ export default {return false},- /**- * Return total amounts of trnsIds- * * TODO: need full refactor- *- * @param {Array} trnsIds- * @return {Object} return- * @return {String} return.expenses- * @return {String} return.incomes- * @return {String} return.total- */- getTotalOfTrnsIds: (_state, _getters, rootState) => (trnsIds, includeTransfers = false, isConvertToBase = true, walletId) => {- const trnsItems = rootState.trns.items- const rates = rootState.currencies.rates- const walletsItems = rootState.wallets.items- const categoriesItems = rootState.categories.items- const baseRate = rootState.currencies.base- const transferCategoriesIds = getTransferCategoriesIds(categoriesItems)-- let total = 0-- if (walletId) {- total = getTotal({- transferCategoriesIds,- trnsIds,- trnsItems,- walletsItems,- walletsIds: [walletId],- })-- return {- expense: total.expenseTransactions + total.expenseTransfers,- income: total.incomeTransactions + total.incomeTransfers,- sum: total.sumTransactions + total.sumTransfers,- // @deprecated- expenses: total.expenseTransactions + total.expenseTransfers,- incomes: total.incomeTransactions + total.incomeTransfers,- total: total.sumTransactions + total.sumTransfers,- }- }- else if (includeTransfers && isConvertToBase) {- total = getTotal({- baseRate,- rates,- transferCategoriesIds,- trnsIds,- trnsItems,- walletsItems,- })-- return {- expense: total.expenseTransactions + total.expenseTransfers,- income: total.incomeTransactions + total.incomeTransfers,- sum: total.sumTransactions + total.sumTransfers,- // @deprecated- expenses: total.expenseTransactions + total.expenseTransfers,- incomes: total.incomeTransactions + total.incomeTransfers,- total: total.sumTransactions + total.sumTransfers,- }- }- else if (includeTransfers && !isConvertToBase) {- total = getTotal({- transferCategoriesIds,- trnsIds,- trnsItems,- walletsItems,- walletsIds: [walletId],- })-- return {- expense: total.expenseTransactions + total.expenseTransfers,- income: total.incomeTransactions + total.incomeTransfers,- sum: total.sumTransactions + total.sumTransfers,- // @deprecated- expenses: total.expenseTransactions + total.expenseTransfers,- incomes: total.incomeTransactions + total.incomeTransfers,- total: total.sumTransactions + total.sumTransfers,- }- }- else if (!includeTransfers) {- total = getTotal({- baseRate,- rates,- transferCategoriesIds,- trnsIds,- trnsItems,- walletsItems,- })-- return {- expense: total.expenseTransactions,- income: total.incomeTransactions,- sum: total.sumTransactions,- // @deprecated- expenses: total.expenseTransactions,- incomes: total.incomeTransactions,- total: total.sumTransactions,- }- }- },-lastCreatedTrnId(state, getters, rootState, rootGetters) {if (!getters.hasTrns)return