Open source personal finance application
refactor: stat code
Ilya Komichevf25240ee8352
diff --git a/app/components/amount/Amount.vue b/app/components/amount/Amount.vueindex 7b240660..4a506c32 100644--- a/app/components/amount/Amount.vue+++ b/app/components/amount/Amount.vue@@ -2,7 +2,7 @@import type { CurrencyCode } from '~/components/currencies/types'import type { MoneyTypeNumber, MoneyTypeSlug } from '~/components/stat/types'-import useAmount from '~/components/amount/useAmount'+import { useAmount } from '~/components/amount/useAmount'import { formatAmount, getCurrencySymbol } from '~/components/amount/utils'export type AmountProps = {@@ -36,7 +36,7 @@ const { baseCurrencyCode, getAmountInBaseRate } = useAmount()<template><div:class="{- '': props.colorize === 'expense' && props.type === 0,+ '!text-expense-1': props.colorize === 'expense' && props.type === 0,'!text-income-1': props.colorize === 'income' && props.type === 1,'text-2xs': props.variant === '2xs','text-xs': props.variant === 'sm',diff --git a/app/components/amount/useAmount.ts b/app/components/amount/useAmount.tsindex 77e2681c..3315ceb8 100644--- a/app/components/amount/useAmount.ts+++ b/app/components/amount/useAmount.ts@@ -8,7 +8,7 @@ import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'import { useTrnsStore } from '~/components/trns/useTrnsStore'import { useWalletsStore } from '~/components/wallets/useWalletsStore'-export default function useAmount() {+export function useAmount() {const currenciesStore = useCurrenciesStore()const walletsStore = useWalletsStore()const categoriesStore = useCategoriesStore()diff --git a/app/components/categories/StatPage.vue b/app/components/categories/StatPage.vueindex 202b9131..c73979a2 100644--- a/app/components/categories/StatPage.vue+++ b/app/components/categories/StatPage.vue@@ -84,7 +84,6 @@ useHead({ title: category.value?.name })isShow: true,isShowSelected: filter.isShow?.value && filter.categoriesIds.value.length > 0,}"- :maxRange:config="{isShowWallets: true,}"diff --git a/app/components/categories/page/id/Index.vue b/app/components/categories/page/id/Index.vueindex 050ed3ff..9192ec7e 100644--- a/app/components/categories/page/id/Index.vue+++ b/app/components/categories/page/id/Index.vue@@ -81,7 +81,6 @@ useHead({ title: category.value?.name })<template><UiPage v-if="category"><StatHeader- :maxRange="maxRange":filter="{ isShow: true, isShowCategories: true }":config="{ isShowCategories: true }":menu="{ active: activeTab, click: id => activeTab = id }"diff --git a/app/components/date/useDateFormats.ts b/app/components/date/useDateFormats.tsindex 4a65829e..d207dd20 100644--- a/app/components/date/useDateFormats.ts+++ b/app/components/date/useDateFormats.ts@@ -31,6 +31,7 @@ export function useDateFormats() {case 'full':return {day: formatByLocale(date, 'd', locale.value),+ full: formatByLocale(date, 'dd.MM.yyyy HH:mm', locale.value),month: formatByLocale(date, 'MMM', locale.value),week: formatByLocale(date, 'dd.MM', locale.value),weekday: `${diff < 2 ? `${calculateDate({ by: 'day', duration: 1, end: date, start: date, type: 'start' })}, ` : ''} ${formatByLocale(date, 'EEEE', locale.value)}`,diff --git a/app/components/date/useStatDate.ts b/app/components/date/useStatDate.tsindex 996cbbd8..6399fdee 100644--- a/app/components/date/useStatDate.ts+++ b/app/components/date/useStatDate.ts@@ -1,8 +1,9 @@import { useStorage } from '@vueuse/core'+import { differenceInDays } from 'date-fns'import type { Grouped, IntervalGroupedLabel, Range, StatDateParams, StatDateParamsQuery } from '~/components/date/types'-import { calculateIntervalInRange, getEndOf, getIntervalsInRange } from '~/components/date/utils'+import { calculateBestIntervalsBy, calculateIntervalInRange, getEndOf, getIntervalsInRange } from '~/components/date/utils'export function useStatDate({key,@@ -129,6 +130,20 @@ export function useStatDate({params.value.intervalsDuration = 1}+ function setMaxRange(isSkipEmpty = false) {+ const rangeDuration = differenceInDays(maxRange.value.end, maxRange.value.start)+ const intervalsBy = calculateBestIntervalsBy(maxRange.value)++ setRangeByPeriod({+ intervalsBy,+ intervalsDuration: 1,+ isShowMaxRange: true,+ isSkipEmpty,+ rangeBy: 'day',+ rangeDuration,+ })+ }+function addInterval() {resetCustomAndMaxRangeParams()++params.value.intervalsDuration@@ -168,6 +183,7 @@ export function useStatDate({range,selectedInterval,setInterval,+ setMaxRange,setRangeByCalendar,setRangeByPeriod,}diff --git a/app/components/stat/Average.vue b/app/components/stat/Average.vuenew file mode 100644index 00000000..a950e815--- /dev/null+++ b/app/components/stat/Average.vue@@ -0,0 +1,146 @@+<script setup lang="ts">+import { useStorage } from '@vueuse/core'+import { sub } from 'date-fns'++import type { CategoryId } from '~/components/categories/types'+import type { Range, StatDateProvider } from '~/components/date/types'+import type { FilterProvider } from '~/components/filter/types'+import type { TrnId } from '~/components/trns/types'+import type { WalletId } from '~/components/wallets/types'++import { useAmount } from '~/components/amount/useAmount'+import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'+import { getEndOf, getStartOf } from '~/components/date/utils'+import { useGetDateRange } from '~/components/stat/date/useGetDateRange'+import { useTrnsStore } from '~/components/trns/useTrnsStore'++const props = defineProps<{+ categoryId?: CategoryId+ filter: FilterProvider+ statDate: StatDateProvider+ trnsIds: TrnId[]+ walletId?: WalletId+}>()++const currenciesStore = useCurrenciesStore()+const trnsStore = useTrnsStore()+const { getTotalOfTrnsIds } = useAmount()++const averageConfig = useStorage('averageConfig', {+ count: 1,+})++const untilDate = computed(() => getEndOf(sub(new Date(), { [`${props.statDate.params.value.rangeBy}s`]: props.statDate.params.value.rangeDuration }), props.statDate.params.value.rangeBy))++const dates = computed<Range>(() => ({+ end: untilDate.value.getTime(),+ start: getStartOf(sub(untilDate.value, { [`${props.statDate.params.value.rangeBy}s`]: (props.statDate.params.value.rangeDuration * averageConfig.value.count) - 1 }), props.statDate.params.value.rangeBy).getTime(),+}))++const datedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({+ categoriesIds: props.categoryId ? [...props.filter.categoriesIds.value, props.categoryId] : props.filter.categoriesIds.value,+ dates: {+ from: dates.value.start,+ until: dates.value.end,+ },+ walletsIds: props.walletId ? [...(props.filter.walletsIds.value ?? []), props.walletId] : props.filter.walletsIds.value,+}, {+ includesChildCategories: true,+}))++const { locale, t } = useI18n()+const { getStringDateRange } = useGetDateRange(t, locale.value)++const total = computed(() => getTotalOfTrnsIds(datedTrnsIds.value))++const last = computed(() => {+ const rangeBy = props.statDate.params.value.rangeBy+ const rangeDuration = props.statDate.params.value.rangeDuration+ const count = averageConfig.value.count++ const getCount = () => {+ const value = count * rangeDuration+ return `${value} ${t(`dates.${rangeBy}.plural`, value)}`+ }++ const periods = {+ day: { count: getCount() },+ month: { count: getCount() },+ week: { count: getCount() },+ year: { count: getCount() },+ }++ return periods[rangeBy]+})+</script>++<template>+ <div class="flex items-start gap-4 pb-2 pl-3 md:max-w-lg">+ <div class="grid w-full grow gap-1 pb-[2px]">+ <UiTitle6 class="text-nowrap !leading-3">+ {{ t('money.average') }}+ <br>{{ t('for') }} ~{{ last.count }}+ <br>{{ getStringDateRange(dates, props.statDate.params.value.rangeBy, props.statDate.params.value.rangeDuration) }}+ </UiTitle6>++ <div class="flex gap-4 overflow-x-auto pb-2">+ <Amount+ :amount="total.income / averageConfig.count"+ :currencyCode="currenciesStore.base"+ :type="1"+ align="left"+ colorize="income"+ variant="xl"+ />+ <Amount+ :amount="total.expense / averageConfig.count"+ :currencyCode="currenciesStore.base"+ :type="0"+ align="left"+ colorize="expense"+ variant="xl"+ />+ <Amount+ :amount="total.sum / averageConfig.count"+ :currencyCode="currenciesStore.base"+ :type="total.sum > 0 ? 1 : 0"+ align="left"+ :colorize="total.sum > 0 ? 'income' : 'expense'"+ variant="xl"+ />+ </div>+ </div>++ <div class="flex gap-1">+ <UiItem2+ :class="[{+ '!hocus:transparent opacity-30': averageConfig.count === 1,+ }]"+ @click="averageConfig.count = averageConfig.count - 1"+ >+ <Icon name="lucide:minus" />+ </UiItem2>+ <FormInput+ :value="averageConfig.count"+ :max="100"+ min="1"+ class="min-w-16 max-w-20 !px-2 text-center"+ type="number"+ @updateValue="value => averageConfig.count = Number(value)"+ />+ <UiItem2+ :class="{ '!hocus:transparent opacity-30': averageConfig.count >= 100 }"+ @click="averageConfig.count = averageConfig.count + 1"+ >+ <Icon name="lucide:plus" />+ </UiItem2>+ </div>+ </div>+</template>++<i18n lang="yaml">+en:+ for: for the last+ru:+ for: за прошлые+</i18n>diff --git a/app/components/stat/Dashboard.vue b/app/components/stat/Dashboard.vueindex 01103d24..18fc8794 100644--- a/app/components/stat/Dashboard.vue+++ b/app/components/stat/Dashboard.vue@@ -45,7 +45,6 @@ watch(filter.categoriesIds, () => {active: activeTab,click: id => activeTab = id,}"- :maxRange:filter="{isShowCategories: true,isShowWallets: true,diff --git a/app/components/stat/Header.vue b/app/components/stat/Header.vueindex e14063bc..82f69e98 100644--- a/app/components/stat/Header.vue+++ b/app/components/stat/Header.vue@@ -1,5 +1,4 @@<script setup lang="ts">-import type { Range } from '~/components/date/types'import type { FilterProvider } from '~/components/filter/types'import type { StatConfigModal, StatTabSlug } from '~/components/stat/types'import type { StatConfigProvider } from '~/components/stat/useStatConfig'@@ -19,7 +18,6 @@ const props = defineProps<{isShowSelected?: booleanisShowWallets?: boolean}- maxRange?: Rangemenu?: {active: StatTabSlugclick: (id: StatTabSlug) => voiddiff --git a/app/components/stat/Item.vue b/app/components/stat/Item.vueindex 21ca6d17..f458d7b1 100644--- a/app/components/stat/Item.vue+++ b/app/components/stat/Item.vue@@ -10,7 +10,7 @@ import type { StatConfigProvider } from '~/components/stat/useStatConfig'import type { TrnId } from '~/components/trns/types'import type { WalletId } from '~/components/wallets/types'-import useAmount from '~/components/amount/useAmount'+import { useAmount } from '~/components/amount/useAmount'import { useCategoriesStore } from '~/components/categories/useCategoriesStore'import StatCategoriesSection from '~/components/stat/categories/Section.vue'import { useStatChart } from '~/components/stat/chart/useStatChart'@@ -33,7 +33,7 @@ const route = useRoute()const filter = inject('filter') as FilterProviderconst statDate = inject('statDate') as StatDateProviderconst statConfig = inject('statConfig') as StatConfigProvider-const categoryId = computed(() => props.isOneCategory ? route.params.id : undefined)+const categoryId = computed(() => props.isOneCategory ? route.params.id as CategoryId : undefined)const categoriesStore = useCategoriesStore()const trnsStore = useTrnsStore()@@ -67,13 +67,7 @@ const statTypeShow = computed(() => ({const isPeriodOneDay = computed(() => (statDate.params.value.rangeBy === 'day' && statDate.params.value.rangeDuration === 1) || (statDate.params.value.intervalsBy === 'day' && statDate.params.value.intervalSelected !== -1))-const rangeTrnsIds = computed(() => {- const params = {- trnsIds: props.trnsIds,- }-- return trnsStore.getStoreTrnsIds(params, { includesChildCategories: false })-})+const rangeTrnsIds = computed(() => trnsStore.getStoreTrnsIds({ trnsIds: props.trnsIds }, { includesChildCategories: false }))const intervalsData = computed(() => getIntervalsData(rangeTrnsIds.value, statDate.intervalsInRange.value))@@ -224,14 +218,11 @@ function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {:series="chart.series.value":xAxisLabels="chart.xAxisLabels.value">- <StatDateQuick- v-if="statConfig.config.value.date.isShowQuick"- :maxRange="statDate.maxRange.value"- />+ <StatDateQuick v-if="statConfig.config.value.date.isShowQuick" /></StatChartWrap><div class="grid pb-5 md:max-w-lg">- <StatDateNavigation :maxRange="statDate.maxRange.value" />+ <StatDateNavigation /></div><StatSumWrap@@ -245,6 +236,14 @@ function getIntervalsData(trnsIds: TrnId[], intervalsInRange: Range[]) {@click="onClickSumItem"/>+ <StatAverage+ :trnsIds+ :statDate+ :filter+ :categoryId+ :walletId+ />+<div class="grid w-full gap-2"><StatCategoriesSectionv-if="props.hasChildren || (props.preCategoriesIds ?? []).length > 0"diff --git a/app/components/stat/categories/useStatCategories.ts b/app/components/stat/categories/useStatCategories.tsindex b8c86a98..89f1f61b 100644--- a/app/components/stat/categories/useStatCategories.ts+++ b/app/components/stat/categories/useStatCategories.ts@@ -2,7 +2,7 @@ import type { CategoryId } from '~/components/categories/types'import type { CategoriesWithData, CategoryWithData } from '~/components/stat/types'import type { TrnId } from '~/components/trns/types'-import useAmount from '~/components/amount/useAmount'+import { useAmount } from '~/components/amount/useAmount'import { useCategoriesStore } from '~/components/categories/useCategoriesStore'import { sortCategoriesByAmount } from '~/components/stat/utils'import { useTrnsStore } from '~/components/trns/useTrnsStore'diff --git a/app/components/stat/date/Navigation.vue b/app/components/stat/date/Navigation.vueindex 1d392ea9..802966ab 100644--- a/app/components/stat/date/Navigation.vue+++ b/app/components/stat/date/Navigation.vue@@ -1,20 +1,19 @@<script setup lang="ts">import { sub } from 'date-fns'-import type { Range, StatDateProvider } from '~/components/date/types'+import type { StatDateProvider } from '~/components/date/types'import { getEndOf, getStartOf } from '~/components/date/utils'-const props = defineProps<{- maxRange: Range-}>()-const { t } = useI18n()const statDate = inject('statDate') as StatDateProvider-const isShowNav = computed(() => {- return !statDate.params.value.isShowMaxRange && (statDate.range.value.start < new Date().getTime() || (statDate.range.value.start !== props.maxRange.start && statDate.range.value.end !== props.maxRange.end))-})+const isShowNav = computed(() =>+ !statDate.params.value.isShowMaxRange+ && (statDate.range.value.start < new Date().getTime()+ || (+ statDate.range.value.start !== statDate.maxRange.value.start+ && statDate.range.value.end !== statDate.maxRange.value.end)))const isDayToday = computed(() => statDate.params.value.rangeBy === 'day' && statDate.params.value.rangeDuration === 1 && statDate.range.value.end < getEndOf(new Date(), 'day').getTime())@@ -26,7 +25,7 @@ const isEnd = computed(() => {})const isStart = computed(() => {- if (statDate.range.value.start <= props.maxRange.start)+ if (statDate.range.value.start <= statDate.maxRange.value.start)return truereturn false@@ -74,7 +73,6 @@ function changeDate(way: 'next' | 'prev' | 'today') {<template #content="{ close }"><StatDateSelectorclass="min-w-[362px] pb-2 md:px-3 md:pb-0"- :maxRange@onClose="close"/></template>diff --git a/app/components/stat/date/Quick.vue b/app/components/stat/date/Quick.vueindex d6d40148..a5049b56 100644--- a/app/components/stat/date/Quick.vue+++ b/app/components/stat/date/Quick.vue@@ -1,19 +1,11 @@<script setup lang="ts">-import { differenceInDays } from 'date-fns'import Swiper from 'swiper'import 'swiper/css'-import type { Range, StatDateProvider } from '~/components/date/types'--import { calculateBestIntervalsBy } from '~/components/date/utils'--const props = defineProps<{- maxRange: Range-}>()+import type { StatDateProvider } from '~/components/date/types'const emit = defineEmits<{onClose: []-}>()const { t } = useI18n()@@ -40,18 +32,7 @@ onMounted(() => {function setMaxRange(isSkipEmpty = false) {emit('onClose')-- const rangeDuration = differenceInDays(props.maxRange.end, props.maxRange.start)- const intervalsBy = calculateBestIntervalsBy(props.maxRange)-- statDate.setRangeByPeriod({- intervalsBy,- intervalsDuration: 1,- isShowMaxRange: true,- isSkipEmpty,- rangeBy: 'day',- rangeDuration,- })+ statDate.setMaxRange(isSkipEmpty)}</script>diff --git a/app/components/stat/date/Selector.vue b/app/components/stat/date/Selector.vueindex 3b27d167..dd275164 100644--- a/app/components/stat/date/Selector.vue+++ b/app/components/stat/date/Selector.vue@@ -1,17 +1,8 @@<script setup lang="ts">-import { differenceInDays } from 'date-fns'-import type { Grouped, Range, StatDateProvider } from '~/components/date/types'-import { calculateBestIntervalsBy } from '~/components/date/utils'--const props = defineProps<{- maxRange: Range-}>()-const emit = defineEmits<{onClose: []-}>()function close() {@@ -28,18 +19,7 @@ const tabs = {function setMaxRange(isSkipEmpty = false) {emit('onClose')-- const rangeDuration = differenceInDays(props.maxRange.end, props.maxRange.start)- const intervalsBy = calculateBestIntervalsBy(props.maxRange)-- statDate.setRangeByPeriod({- intervalsBy,- intervalsDuration: 1,- isShowMaxRange: true,- isSkipEmpty,- rangeBy: 'day',- rangeDuration,- })+ statDate.setMaxRange(isSkipEmpty)}const intervals = computed<Grouped[]>(() => [{diff --git a/app/components/trns/List.vue b/app/components/trns/List.vueindex dec063a8..d68c28fa 100644--- a/app/components/trns/List.vue+++ b/app/components/trns/List.vue@@ -1,7 +1,7 @@<script setup lang="ts">import type { TrnId, TrnsViewType } from '~/components/trns/types'-import useAmount from '~/components/amount/useAmount'+import { useAmount } from '~/components/amount/useAmount'import { useCategoriesStore } from '~/components/categories/useCategoriesStore'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'import { useDateFormats } from '~/components/date/useDateFormats'diff --git a/app/components/wallets/page/List.vue b/app/components/wallets/page/List.vueindex 7d17b429..fed9ef20 100644--- a/app/components/wallets/page/List.vue+++ b/app/components/wallets/page/List.vue@@ -5,7 +5,7 @@ import { groupBy } from 'es-toolkit'import type { CurrencyCode } from '~/components/currencies/types'import type { WalletId, WalletItem, WalletViewTypes, WalletViewTypesObj } from '~/components/wallets/types'-import useAmount from '~/components/amount/useAmount'+import { useAmount } from '~/components/amount/useAmount'import { useAppNav } from '~/components/app/useAppNav'import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'import { viewTypes } from '~/components/wallets/types'diff --git a/app/components/wallets/page/id/Index.vue b/app/components/wallets/page/id/Index.vueindex 68cf0556..070a104f 100644--- a/app/components/wallets/page/id/Index.vue+++ b/app/components/wallets/page/id/Index.vue@@ -74,7 +74,6 @@ useHead({ title: wallet.value?.name })<UiPage v-if="wallet"><StatHeader:menu="{ active: activeTab, click: id => activeTab = id }"- :maxRange="maxRange":filter="{ isShowCategories: true }":config="{ isShowCategories: true }">