Skip to content

Open source personal finance application

refactor: stat components — extract shared patterns, fix naming, optimize

Ilya Komichevf18cbc9591b9
diff --git a/app/components/stat/Average.vue b/app/components/stat/Average.vue
index 366734ec..000f8623 100644
--- a/app/components/stat/Average.vue
+++ b/app/components/stat/Average.vue
@@ -2,8 +2,7 @@
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/stat/filter/types'
+import type { Range } from '~/components/date/types'
import type { SeriesSlugSelected } from '~/components/stat/types'
import type { TrnId } from '~/components/trns/types'
import type { WalletId } from '~/components/wallets/types'
@@ -11,41 +10,64 @@ 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 { TrnType } from '~/components/trns/types'
+import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
+import { getTrnTypeByAmount, TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
const props = defineProps<{
- averageConfig: number
categoryId?: CategoryId
- filter: FilterProvider
- statDate: StatDateProvider
statTabSlug: SeriesSlugSelected
trnsIds: TrnId[]
walletId?: WalletId
}>()
const { t } = useI18n()
+const filter = inject(filterKey)!
+const statConfig = inject(statConfigKey)!
+const statDate = inject(statDateKey)!
const currenciesStore = useCurrenciesStore()
const trnsStore = useTrnsStore()
const { computeTotalForTrnsIds } = useAmount()
-const untilDate = computed(() => getEndOf(sub(new Date(), { [`${props.statDate.params.value.rangeBy}s`]: props.statDate.params.value.rangeDuration }), props.statDate.params.value.rangeBy))
+const averageConfig = computed(() => statConfig.config.value.statAverage.count)
+
+const untilDate = computed(() => getEndOf(sub(new Date(), { [`${statDate.params.value.rangeBy}s`]: statDate.params.value.rangeDuration }), 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 * props.averageConfig) - 1 }), props.statDate.params.value.rangeBy).getTime(),
+ start: getStartOf(sub(untilDate.value, { [`${statDate.params.value.rangeBy}s`]: (statDate.params.value.rangeDuration * averageConfig.value) - 1 }), statDate.params.value.rangeBy).getTime(),
}))
const datedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
- categoriesIds: props.categoryId ? [...props.filter.categoriesIds.value, props.categoryId] : props.filter.categoriesIds.value,
+ categoriesIds: props.categoryId ? [...filter.categoriesIds.value, props.categoryId] : 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,
+ walletsIds: props.walletId ? [...(filter.walletsIds.value ?? []), props.walletId] : filter.walletsIds.value,
}))
const total = computed(() => computeTotalForTrnsIds(datedTrnsIds.value))
+
+const averageAmount = computed(() => {
+ if (props.statTabSlug === 'income')
+ return total.value.income / averageConfig.value
+ if (props.statTabSlug === 'expense')
+ return total.value.expense / averageConfig.value
+ return total.value.sum / averageConfig.value
+})
+
+const amountType = computed(() => {
+ if (props.statTabSlug === 'netIncome')
+ return getTrnTypeByAmount(averageAmount.value)
+ return props.statTabSlug === 'income' ? TrnType.Income : TrnType.Expense
+})
+
+const amountColorize = computed(() => {
+ if (props.statTabSlug === 'netIncome')
+ return averageAmount.value > 0 ? 'income' : 'expense'
+ return props.statTabSlug as 'expense' | 'income'
+})
</script>
<template>
@@ -58,29 +80,10 @@ const total = computed(() => computeTotalForTrnsIds(datedTrnsIds.value))
<div class="flex gap-4">
<Amount
- v-if="statTabSlug === 'income'"
- :amount="total.income / props.averageConfig"
- :currencyCode="currenciesStore.base"
- :type="TrnType.Income"
- align="left"
- colorize="income"
- variant="base"
- />
- <Amount
- v-if="statTabSlug === 'expense'"
- :amount="total.expense / props.averageConfig"
- :currencyCode="currenciesStore.base"
- :type="TrnType.Expense"
- align="left"
- colorize="expense"
- variant="base"
- />
- <Amount
- v-if="statTabSlug === 'netIncome'"
- :amount="total.sum / props.averageConfig"
- :colorize="total.sum > 0 ? 'income' : 'expense'"
+ :amount="averageAmount"
+ :colorize="amountColorize"
:currencyCode="currenciesStore.base"
- :type="total.sum > 0 ? TrnType.Income : TrnType.Expense"
+ :type="amountType"
align="left"
variant="base"
/>
diff --git a/app/components/stat/CategoriesButtons.vue b/app/components/stat/CategoriesButtons.vue
index fc2c4c79..69b592d2 100644
--- a/app/components/stat/CategoriesButtons.vue
+++ b/app/components/stat/CategoriesButtons.vue
@@ -83,25 +83,9 @@ function onChangeViewOptions(newViewOptions: Pick<DeepPartial<MiniItemConfig>, '
</div>
<div v-if="isShowMorePresets">
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.catsList.isItemsBg"
- :title="t('stat.catButtons.isItemsBg')"
- @click="statConfig.updateConfig('catsList', { isItemsBg: !statConfig.config.value.catsList.isItemsBg })"
- />
-
- <!-- Lines -->
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.catsList.isLines"
- :title="t('stat.catButtons.isLines')"
- @click="statConfig.updateConfig('catsList', { isLines: !statConfig.config.value.catsList.isLines })"
- />
-
- <!-- Round icons -->
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.catsList.isRoundIcon"
- :title="t('stat.catButtons.isRoundIcon')"
- @click="statConfig.updateConfig('catsList', { isRoundIcon: !statConfig.config.value.catsList.isRoundIcon })"
- />
+ <StatConfigSwitch configKey="catsList" field="isItemsBg" :title="t('stat.catButtons.isItemsBg')" />
+ <StatConfigSwitch configKey="catsList" field="isLines" :title="t('stat.catButtons.isLines')" />
+ <StatConfigSwitch configKey="catsList" field="isRoundIcon" :title="t('stat.catButtons.isRoundIcon')" />
</div>
</div>
@@ -112,21 +96,9 @@ function onChangeViewOptions(newViewOptions: Pick<DeepPartial<MiniItemConfig>, '
{{ t('stat.catButtons.elements') }}
</UiTitleSection>
<div>
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.vertical.isShow"
- :title="t('stat.config.categories.vertical.title')"
- @click="statConfig.updateConfig('vertical', { isShow: !statConfig.config.value.vertical.isShow })"
- />
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.catsRound.isShow"
- :title="t('stat.config.categories.rounds.title')"
- @click="statConfig.updateConfig('catsRound', { isShow: !statConfig.config.value.catsRound.isShow })"
- />
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.catsList.isShow"
- :title="t('stat.config.categories.list.title')"
- @click="statConfig.updateConfig('catsList', { isShow: !statConfig.config.value.catsList.isShow })"
- />
+ <StatConfigSwitch configKey="vertical" field="isShow" :title="t('stat.config.categories.vertical.title')" />
+ <StatConfigSwitch configKey="catsRound" field="isShow" :title="t('stat.config.categories.rounds.title')" />
+ <StatConfigSwitch configKey="catsList" field="isShow" :title="t('stat.config.categories.list.title')" />
</div>
</div>
</div>
diff --git a/app/components/stat/ConfigModal.vue b/app/components/stat/ConfigModal.vue
index 99464b26..7666f4c7 100644
--- a/app/components/stat/ConfigModal.vue
+++ b/app/components/stat/ConfigModal.vue
@@ -1,6 +1,4 @@
<script setup lang="ts">
-import type { StatConfigModal } from '~/components/stat/types'
-
import { useStatChart } from '~/components/stat/chart/useStatChart'
import { statConfigKey } from '~/components/stat/injectionKeys'
import { chartViewOptions } from '~/components/stat/useStatConfig'
@@ -8,34 +6,23 @@ import { useWalletsStore } from '~/components/wallets/useWalletsStore'
const props = defineProps<{
isShowWallets?: boolean
- statConfigModal: StatConfigModal
}>()
const statConfig = inject(statConfigKey)!
const { t } = useI18n()
const walletsStore = useWalletsStore()
-const { chartTypes } = useStatChart()
-
-function updateWalletsLimit(value: number) {
- if (value <= walletsStore.sortedIds.length && value > 0)
- statConfig.updateConfig('wallets', { count: value })
-}
+const { chartTypeOptions } = useStatChart()
-function updateStatAverage(value: number) {
- if (value <= 0)
- return
-
- statConfig.updateConfig('statAverage', { count: value })
-}
+const isOpen = ref(false)
</script>
<template>
<BottomSheetOrDropdown
:title="t('stat.config.menu.label')"
- :isOpen="props.statConfigModal.isShow"
+ :isOpen
isShowCloseBtn
- @openModal="props.statConfigModal.show"
- @closeModal="props.statConfigModal.close"
+ @openModal="isOpen = true"
+ @closeModal="isOpen = false"
>
<template #trigger>
<UTooltip :text="t('stat.config.menu.label')">
@@ -61,17 +48,16 @@ function updateStatAverage(value: number) {
{{ t('stat.config.chartShow.title') }}
</UiTitleSection>
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.isChartShow"
+ <StatConfigSwitch
+ configKey="isChartShow"
:title="t('stat.config.chartShow.label')"
- @click="statConfig.updateConfig('isChartShow', !statConfig.config.value.isChartShow)"
/>
- <UiSwitchItem
+ <StatConfigSwitch
v-if="statConfig.config.value.isChartShow"
- :checkboxValue="statConfig.config.value.date.isShowQuick"
+ configKey="date"
+ field="isShowQuick"
:title="t('stat.config.date.quick.label')"
- @click="statConfig.updateConfig('date', { isShowQuick: !statConfig.config.value.date.isShowQuick })"
/>
<!-- Chart: showed -->
@@ -79,10 +65,10 @@ function updateStatAverage(value: number) {
v-if="statConfig.config.value.isChartShow"
class="grid gap-4"
>
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.chart.isShowAverage ?? false"
+ <StatConfigSwitch
+ configKey="chart"
+ field="isShowAverage"
:title="t('stat.config.chart.average.label')"
- @click="statConfig.updateConfig('chart', { isShowAverage: !statConfig.config.value.chart.isShowAverage })"
/>
<!-- Chart: view -->
@@ -113,7 +99,7 @@ function updateStatAverage(value: number) {
<UiTabsBar>
<UiTabsItemPill
- v-for="item in chartTypes"
+ v-for="item in chartTypeOptions"
:key="item.value"
variant="outline"
:isActive="statConfig.config.value.chartType === item.value"
@@ -140,10 +126,10 @@ function updateStatAverage(value: number) {
{{ t('stat.config.wallets.title') }}
</UiTitleSection>
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.wallets.isShow"
+ <StatConfigSwitch
+ configKey="wallets"
+ field="isShow"
:title="t('stat.config.wallets.label')"
- @click="statConfig.updateConfig('wallets', { isShow: !statConfig.config.value.wallets.isShow })"
/>
<!-- Wallets: form -->
@@ -151,31 +137,12 @@ function updateStatAverage(value: number) {
v-if="statConfig.config.value.wallets.isShow"
class="flex gap-4 pt-2"
>
- <div class="flex gap-1">
- <UiChipButton
- :class="[{
- '!hover:transparent opacity-30': statConfig.config.value.wallets.count === 1,
- }]"
- @click="updateWalletsLimit(statConfig.config.value.wallets.count - 1)"
- >
- <Icon name="lucide:minus" />
- </UiChipButton>
- <FormInput
- :placeholder="t('stat.config.showedWallets.placeholder')"
- :modelValue="statConfig.config.value.wallets.count"
- min="1"
- class="!w-16 max-w-24 !px-2 text-center"
- type="number"
- @update:modelValue="value => statConfig.updateConfig('wallets', { count: +value })"
- />
-
- <UiChipButton
- :class="{ '!hover:transparent opacity-30': statConfig.config.value.wallets.count >= walletsStore.sortedIds.length }"
- @click="updateWalletsLimit(statConfig.config.value.wallets.count + 1)"
- >
- <Icon name="lucide:plus" />
- </UiChipButton>
- </div>
+ <UiNumberStepper
+ :modelValue="statConfig.config.value.wallets.count"
+ :min="1"
+ :max="walletsStore.sortedIds.length"
+ @update:modelValue="value => statConfig.updateConfig('wallets', { count: value })"
+ />
</div>
</div>
@@ -187,10 +154,10 @@ function updateStatAverage(value: number) {
{{ t('statistics.title') }}
</UiTitleSection>
- <UiSwitchItem
- :checkboxValue="statConfig.config.value.statAverage.isShow"
+ <StatConfigSwitch
+ configKey="statAverage"
+ field="isShow"
:title="t('stat.config.statAverage.count.label')"
- @click="statConfig.updateConfig('statAverage', { isShow: !statConfig.config.value.statAverage.isShow })"
/>
<!-- Average -->
@@ -198,30 +165,11 @@ function updateStatAverage(value: number) {
v-if="statConfig.config.value.statAverage.isShow"
class="flex gap-4 pt-2"
>
- <div class="flex gap-1">
- <UiChipButton
- :class="[{
- '!hover:transparent opacity-30': statConfig.config.value.statAverage.count === 1,
- }]"
- @click="updateStatAverage(statConfig.config.value.statAverage.count - 1)"
- >
- <Icon name="lucide:minus" />
- </UiChipButton>
- <FormInput
- :placeholder="t('stat.config.showedWallets.placeholder')"
- :modelValue="statConfig.config.value.statAverage.count"
- min="1"
- class="!w-16 max-w-24 !px-2 text-center"
- type="number"
- @update:modelValue="value => statConfig.updateConfig('statAverage', { count: +value })"
- />
-
- <UiChipButton
- @click="updateStatAverage(statConfig.config.value.statAverage.count + 1)"
- >
- <Icon name="lucide:plus" />
- </UiChipButton>
- </div>
+ <UiNumberStepper
+ :modelValue="statConfig.config.value.statAverage.count"
+ :min="1"
+ @update:modelValue="value => statConfig.updateConfig('statAverage', { count: value })"
+ />
</div>
</div>
diff --git a/app/components/stat/ConfigSwitch.vue b/app/components/stat/ConfigSwitch.vue
new file mode 100644
index 00000000..83003e29
--- /dev/null
+++ b/app/components/stat/ConfigSwitch.vue
@@ -0,0 +1,35 @@
+<script setup lang="ts">
+import type { MiniItemConfig } from '~/components/stat/useStatConfig'
+
+import { statConfigKey } from '~/components/stat/injectionKeys'
+
+const props = defineProps<{
+ configKey: keyof MiniItemConfig
+ field?: string
+ title: string
+}>()
+
+const statConfig = inject(statConfigKey)!
+
+const isChecked = computed(() => {
+ const val = statConfig.config.value[props.configKey]
+ if (props.field && typeof val === 'object')
+ return (val as Record<string, boolean>)[props.field]
+ return val as boolean
+})
+
+function toggle() {
+ if (props.field)
+ statConfig.updateConfig(props.configKey, { [props.field]: !isChecked.value })
+ else
+ statConfig.updateConfig(props.configKey, !isChecked.value as any)
+}
+</script>
+
+<template>
+ <UiSwitchItem
+ :checkboxValue="isChecked"
+ :title="props.title"
+ @click="toggle"
+ />
+</template>
diff --git a/app/components/stat/Header.vue b/app/components/stat/Header.vue
index 02881244..a2a819df 100644
--- a/app/components/stat/Header.vue
+++ b/app/components/stat/Header.vue
@@ -1,21 +1,19 @@
<script setup lang="ts">
-import type { StatConfigModal } from '~/components/stat/types'
+import type { StatTabSlug } from '~/components/stat/types'
import type { WalletId } from '~/components/wallets/types'
import { filterKey, statConfigKey } from '~/components/stat/injectionKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
import { useWalletsStore } from '~/components/wallets/useWalletsStore'
-const props = defineProps<{
- config?: {
- isShowWallets?: boolean
- }
- filter?: {
- isShowCategories?: boolean
- isShowWallets?: boolean
- }
+defineProps<{
+ configWallets?: boolean
+ filterCategories?: boolean
+ filterWallets?: boolean
}>()
+const activeTab = defineModel<StatTabSlug>('activeTab')
+
const filter = inject(filterKey)!
const statConfig = inject(statConfigKey)!
const walletsStore = useWalletsStore()
@@ -34,12 +32,6 @@ function onClickWallet(walletId: WalletId) {
trnsFormStore.values.walletId = walletId
}
-const statConfigModal: Ref<StatConfigModal> = ref({
- close: () => statConfigModal.value.isShow = false,
- isShow: false,
- show: () => statConfigModal.value.isShow = true,
-})
-
const isPopoverOpen = ref(false)
</script>
@@ -48,20 +40,15 @@ const isPopoverOpen = ref(false)
<slot name="title" />
<template #actions>
- <div
- v-if="props.filter || props.config || $slots.popover"
- class="ml-auto flex items-center gap-1"
- >
+ <div class="ml-auto flex items-center gap-1">
<StatFilterSelector
- v-if="props.filter"
- :isShowCategories="!!props.filter.isShowCategories"
- :isShowWallets="!!props.filter.isShowWallets"
+ v-if="filterCategories || filterWallets"
+ :isShowCategories="!!filterCategories"
+ :isShowWallets="!!filterWallets"
/>
<StatConfigModal
- v-if="props.config || $slots.popover"
- :isShowWallets="!!props.config?.isShowWallets"
- :statConfigModal
+ :isShowWallets="!!configWallets"
/>
<BottomSheetOrDropdown
@@ -89,10 +76,10 @@ const isPopoverOpen = ref(false)
</div>
</template>
- <template #selected>
- <slot
- v-if="$slots.selected"
- name="selected"
+ <template v-if="activeTab" #selected>
+ <StatMenu
+ :active="activeTab"
+ @click="(id: StatTabSlug) => activeTab = id"
/>
</template>
diff --git a/app/components/stat/Item.vue b/app/components/stat/Item.vue
index 10f4b380..074d2f9d 100644
--- a/app/components/stat/Item.vue
+++ b/app/components/stat/Item.vue
@@ -10,8 +10,8 @@ import { useStatItem } from '~/components/stat/useStatItem'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
const props = defineProps<{
+ categoryId?: CategoryId
hasChildren?: boolean
- isOneCategory?: boolean
preCategoriesIds?: CategoryId[]
statTab: StatTabSlug
storageKey: string
@@ -20,7 +20,6 @@ const props = defineProps<{
walletId?: WalletId
}>()
-const route = useRoute()
const { t } = useI18n()
const filter = inject(filterKey)!
const statDate = inject(statDateKey)!
@@ -28,8 +27,12 @@ const statConfig = inject(statConfigKey)!
const categoriesStore = useCategoriesStore()
const trnsStore = useTrnsStore()
-const categoryId = computed(() => props.isOneCategory ? route.params.id as CategoryId : undefined)
-const isNotTransferCategory = computed(() => !props.isOneCategory || categoryId.value !== 'transfer')
+const isOneCategory = computed(() => !!props.categoryId)
+const shouldShowAmounts = computed(() => !props.categoryId || props.categoryId !== 'transfer')
+const isRoundShow = computed(() => statConfig.config.value.catsRound.isShow)
+const isListShow = computed(() => statConfig.config.value.catsList.isShow)
+const isVerticalShow = computed(() => statConfig.config.value.vertical.isShow)
+const isShowAverage = computed(() => statConfig.config.value.statAverage.isShow)
const {
averageTotal,
@@ -38,13 +41,13 @@ const {
filteredCategoriesIds,
filteredType,
isPeriodOneDay,
- newBaseStorageKey,
onClickSumItem,
onSetCategoryFilter,
rangeTotal,
selectedAndFilteredTrnsIds,
selectedTrnsIds,
selectedTypeForSum,
+ statItemStorageKey,
} = useStatItem({
filter,
statConfig,
@@ -55,12 +58,27 @@ const {
type: computed(() => props.type),
})
-const quickViewTrns = ref<TrnId[]>([])
-const isShowTrns = ref(false)
const hasCategoriesData = computed(() => props.hasChildren || (props.preCategoriesIds ?? []).length > 0)
+const shouldUseTwoColumnLayout = computed(() => props.statTab !== 'split' && isListShow.value)
+
+// Modal state: 'quickView' shows snapshot trnsIds, 'fullTrns' shows reactive selectedAndFilteredTrnsIds
+const modalSource = ref<'fullTrns' | 'quickView' | null>(null)
+const quickViewTrnsIds = ref<TrnId[]>([])
+const modalTrnsIds = computed(() => {
+ if (modalSource.value === 'quickView')
+ return quickViewTrnsIds.value
+ if (modalSource.value === 'fullTrns')
+ return selectedAndFilteredTrnsIds.value
+ return []
+})
+
+function closeModal() {
+ modalSource.value = null
+ quickViewTrnsIds.value = []
+}
function onClickCategory(clickedCategoryId: CategoryId) {
- if (route.name === 'categories-id') {
+ if (props.categoryId) {
filter.setCategoryId(clickedCategoryId)
const baseParams = {
@@ -73,17 +91,17 @@ function onClickCategory(clickedCategoryId: CategoryId) {
return useRouter().push(`/categories/${clickedCategoryId}?${queryParams}`)
}
- // Show quick view
- quickViewTrns.value = trnsStore.getStoreTrnsIds({
+ quickViewTrnsIds.value = trnsStore.getStoreTrnsIds({
categoriesIds: [clickedCategoryId],
sort: true,
trnsIds: selectedAndFilteredTrnsIds.value,
})
+ modalSource.value = 'quickView'
}
function onClickSumItemWrap(type: SeriesSlugSelected) {
if (type === 'netIncome')
- isShowTrns.value = true
+ modalSource.value = 'fullTrns'
onClickSumItem(type)
}
@@ -92,14 +110,11 @@ function onClickSumItemWrap(type: SeriesSlugSelected) {
<template>
<div class="@container/stat">
<StatChartWrap
- v-if="isNotTransferCategory"
- :chartView="statConfig.config.value.chartView"
+ v-if="shouldShowAmounts"
:series="chartSeries"
:xAxisLabels="chartXAxisLabels"
class="pb-3"
- >
- <StatDateQuick v-if="statConfig.config.value.date.isShowQuick" />
- </StatChartWrap>
+ />
<div class="grid min-w-0 content-start gap-3">
<StatDateNavigation>
@@ -111,29 +126,23 @@ function onClickSumItemWrap(type: SeriesSlugSelected) {
</StatDateNavigation>
<StatSumWrap
- v-if="isNotTransferCategory"
- :averageConfig="statConfig.config.value.statAverage.count"
+ v-if="shouldShowAmounts"
:averageTotal
- :categoryId
- :filter
+ :categoryId="props.categoryId"
:filteredType="filteredType"
- :isShowAverage="statConfig.config.value.statAverage.isShow"
- :isShowExpense="true"
- :isShowIncome="true"
- :statDate
:total="rangeTotal"
:trnsIds
:type="selectedTypeForSum"
:walletId
@click="onClickSumItemWrap"
- @clickAverage="statConfig.updateConfig('statAverage', { isShow: !statConfig.config.value.statAverage.isShow })"
+ @clickAverage="statConfig.updateConfig('statAverage', { isShow: !isShowAverage })"
/>
<div class="_min-h-dvh grid min-w-0 content-start items-start gap-4">
- <StatCategoriesSection
- v-if="statConfig.config.value.catsRound.isShow && hasCategoriesData"
+ <StatCategoriesRoundSection
+ v-if="isRoundShow && hasCategoriesData"
:filteredCategoriesIds
- :isOneCategory="props.isOneCategory"
+ :isOneCategory="isOneCategory"
:preCategoriesIds="props.preCategoriesIds || categoriesStore.favoriteCategoriesIds"
:selectedTrnsIds
@clickCategory="onClickCategory"
@@ -142,15 +151,15 @@ function onClickSumItemWrap(type: SeriesSlugSelected) {
<div
:class="{
- 'grid gap-5 @3xl/page:grid-cols-2 @3xl/page:gap-6': props.statTab !== 'split' && statConfig.config.value.catsList.isShow,
+ 'grid gap-5 @3xl/page:grid-cols-2 @3xl/page:gap-6': shouldUseTwoColumnLayout,
}"
>
- <StatCategoriesSection2
- v-if="(statConfig.config.value.catsList.isShow || statConfig.config.value.vertical.isShow) && hasCategoriesData"
- :isOneCategory="props.isOneCategory"
+ <StatCategoriesDetailedSection
+ v-if="(isListShow || isVerticalShow) && hasCategoriesData"
+ :isOneCategory="isOneCategory"
:preCategoriesIds="props.preCategoriesIds"
:selectedTrnsIds="selectedAndFilteredTrnsIds"
- :storageKey="newBaseStorageKey"
+ :storageKey="statItemStorageKey"
:type="props.type ?? 'netIncome'"
@clickCategory="onClickCategory"
@setCategoryFilter="onSetCategoryFilter"
@@ -165,37 +174,12 @@ function onClickSumItemWrap(type: SeriesSlugSelected) {
</div>
</div>
- <!-- Quick View Trns -->
- <BottomSheetModal
- v-if="quickViewTrns?.length > 0"
- @closed="quickViewTrns = []"
- >
- <UiTitleModal>
- {{ t('trns.title') }} {{ quickViewTrns.length > 0 ? quickViewTrns.length : '' }}
- </UiTitleModal>
-
- <div class="scrollerBlock bottomSheetContentInside pb-2">
- <TrnsList
- :isShowDates="!isPeriodOneDay"
- :isShowGroupSum="!isPeriodOneDay"
- :size="50"
- :trnsIds="quickViewTrns"
- isShowExpense
- isShowFilterByDesc
- isShowFilterByType
- isShowIncome
- isShowTransfers
- @click="() => quickViewTrns = []"
- />
- </div>
- </BottomSheetModal>
-
<BottomSheetModal
- v-if="isShowTrns"
- @closed="isShowTrns = false"
+ v-if="modalSource"
+ @closed="closeModal"
>
<UiTitleModal>
- {{ t('trns.title') }} {{ selectedAndFilteredTrnsIds.length > 0 ? selectedAndFilteredTrnsIds.length : '' }}
+ {{ t('trns.title') }} {{ modalTrnsIds.length > 0 ? modalTrnsIds.length : '' }}
</UiTitleModal>
<div class="scrollerBlock bottomSheetContentInside">
@@ -203,12 +187,13 @@ function onClickSumItemWrap(type: SeriesSlugSelected) {
:isShowDates="!isPeriodOneDay"
:isShowGroupSum="!isPeriodOneDay"
:size="50"
- :trnsIds="selectedAndFilteredTrnsIds"
+ :trnsIds="modalTrnsIds"
isShowExpense
isShowFilterByDesc
isShowFilterByType
isShowIncome
isShowTransfers
+ @click="modalSource === 'quickView' ? closeModal() : undefined"
/>
</div>
</BottomSheetModal>
diff --git a/app/components/stat/Wrap.vue b/app/components/stat/Wrap.vue
index 23e77693..c3fb8399 100644
--- a/app/components/stat/Wrap.vue
+++ b/app/components/stat/Wrap.vue
@@ -1,30 +1,39 @@
<script setup lang="ts">
import type { CategoryId } from '~/components/categories/types'
-import type { Range } from '~/components/date/types'
import type { StatTabSlug } from '~/components/stat/types'
import type { TrnId } from '~/components/trns/types'
import type { WalletId } from '~/components/wallets/types'
+import { statDateKey } from '~/components/stat/injectionKeys'
import { TrnType } from '~/components/trns/types'
import { useTrnsStore } from '~/components/trns/useTrnsStore'
const props = defineProps<{
activeTab: StatTabSlug
+ categoryId?: CategoryId
hasChildren?: boolean
- isOneCategory?: boolean
preCategoriesIds?: CategoryId[]
- range: Range
storageKey: string
trnsIds: TrnId[]
walletId?: WalletId
}>()
const trnsStore = useTrnsStore()
+const statDate = inject(statDateKey)!
+
+const sharedItemProps = computed(() => ({
+ categoryId: props.categoryId,
+ hasChildren: props.hasChildren,
+ preCategoriesIds: props.preCategoriesIds,
+ statTab: props.activeTab,
+ storageKey: props.storageKey,
+ walletId: props.walletId,
+}))
const datedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
dates: {
- from: props.range.start,
- until: props.range.end,
+ from: statDate.range.value.start,
+ until: statDate.range.value.end,
},
trnsIds: props.trnsIds,
}))
@@ -47,24 +56,14 @@ const incomeTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
class="grid max-w-7xl gap-8 px-2 pb-24 lg:px-4 xl:py-2 2xl:px-8 @3xl/page:grid-cols-2 @3xl/page:gap-8"
>
<StatItem
- :statTab="props.activeTab"
- :hasChildren="props.hasChildren"
- :isOneCategory="props.isOneCategory"
- :preCategoriesIds="props.preCategoriesIds"
- :storageKey="props.storageKey"
+ v-bind="sharedItemProps"
:trnsIds="expenseTrnsIds"
- :walletId="props.walletId"
type="expense"
/>
<StatItem
- :statTab="props.activeTab"
- :hasChildren="props.hasChildren"
- :isOneCategory="props.isOneCategory"
- :preCategoriesIds="props.preCategoriesIds"
- :storageKey="props.storageKey"
+ v-bind="sharedItemProps"
:trnsIds="incomeTrnsIds"
- :walletId="props.walletId"
type="income"
/>
</div>
@@ -72,13 +71,8 @@ const incomeTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
<!-- Net income, income, expense -->
<StatItem
v-else
- :hasChildren="props.hasChildren"
- :isOneCategory="props.isOneCategory"
- :preCategoriesIds="props.preCategoriesIds"
- :statTab="props.activeTab"
- :storageKey="props.storageKey"
+ v-bind="sharedItemProps"
:trnsIds="datedTrnsIds"
- :walletId="props.walletId"
class="max-w-7xl p-2 pt-0 lg:px-4 2xl:px-8"
/>
</template>
diff --git a/app/components/stat/categories/Section2.vue b/app/components/stat/categories/DetailedSection.vue
similarity index 50%
rename from app/components/stat/categories/Section2.vue
rename to app/components/stat/categories/DetailedSection.vue
index 8e652471..f4f5f18c 100644
--- a/app/components/stat/categories/Section2.vue
+++ b/app/components/stat/categories/DetailedSection.vue
@@ -1,11 +1,10 @@
<script setup lang="ts">
-import { useStorage } from '@vueuse/core'
-
-import type { Categories, CategoryId } from '~/components/categories/types'
+import type { CategoryId } from '~/components/categories/types'
import type { CategoryWithData, SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
import type { TrnId } from '~/components/trns/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
+import { useCategoriesExpanded } from '~/components/stat/categories/useCategoriesExpanded'
import { useStatCategories } from '~/components/stat/categories/useStatCategories'
import { statConfigKey } from '~/components/stat/injectionKeys'
@@ -27,87 +26,55 @@ const { computeCategoriesWithData } = useStatCategories()
const categoriesStore = useCategoriesStore()
const statConfig = inject(statConfigKey)!
-// Lazy computeds — each computed only when accessed (Vue computed is lazy).
-// Replaces the old `categoriesStat` which eagerly computed BOTH variants on every change.
+// Config
+const catsList = computed(() => statConfig.config.value.catsList)
+const isVerticalShow = computed(() => statConfig.config.value.vertical.isShow)
+const isVerticalGrouped = computed(() => statConfig.config.value.vertical.isGrouped)
+const isListShow = computed(() => catsList.value.isShow)
+const isListGrouped = computed(() => catsList.value.isGrouped)
+const isItemsBg = computed(() => catsList.value.isItemsBg)
+const isLines = computed(() => catsList.value.isLines)
+
+// Categories data (lazy — each variant computed only when accessed)
const groupedCategories = computed(() => computeCategoriesWithData(props.selectedTrnsIds ?? [], true))
const ungroupedCategories = computed(() => computeCategoriesWithData(props.selectedTrnsIds ?? [], false))
const categoriesWithData = computed<CategoryWithData[]>(() => {
const isGrouped = statConfig.config.value[statConfig.config.value.catsView === 'list' ? 'catsList' : 'catsRound'].isGrouped
- // When showing empty categories, need a separate call with preCategoriesIds
- if (statConfig.config.value.isShowEmptyCategories && props.preCategoriesIds?.length) {
+ if (statConfig.config.value.isShowEmptyCategories && props.preCategoriesIds?.length)
return computeCategoriesWithData(props.selectedTrnsIds ?? [], isGrouped, props.preCategoriesIds)
- }
return isGrouped ? groupedCategories.value : ungroupedCategories.value
})
-const verticalCategories = computed<CategoryWithData[]>(() => statConfig.config.value.vertical.isGrouped ? groupedCategories.value : ungroupedCategories.value)
+// Vertical
+const verticalCategories = computed<CategoryWithData[]>(() => isVerticalGrouped.value ? groupedCategories.value : ungroupedCategories.value)
const visibleVerticalCategories = computed(() => verticalCategories.value.filter(c => c.value !== 0))
-const verticalBiggestCatNumber = computed(() => getBiggestCatNumber(verticalCategories.value))
-
-const linesCategories = computed<CategoryWithData[]>(() => statConfig.config.value.catsList.isGrouped ? groupedCategories.value : ungroupedCategories.value)
-const linesBiggestCatNumber = computed(() => getBiggestCatNumber(linesCategories.value))
+const verticalMaxValues = computed(() => getMaxCategoryValues(verticalCategories.value))
-const biggestCatNumber = computed(() => getBiggestCatNumber(categoriesWithData.value))
+// List
+const linesCategories = computed<CategoryWithData[]>(() => isListGrouped.value ? groupedCategories.value : ungroupedCategories.value)
+const linesMaxValues = computed(() => getMaxCategoryValues(linesCategories.value))
+const childrenMaxValues = computed(() => getMaxCategoryValues(categoriesWithData.value))
-function getBiggestCatNumber(categories: CategoryWithData[]) {
+function getMaxCategoryValues(categories: CategoryWithData[]) {
const income = categories.find(c => c.value > 0)?.value ?? 0
const expense = categories.find(c => c.value < 0)?.value ?? 0
-
- return {
- expense: Math.abs(expense),
- income,
- }
+ return { expense: Math.abs(expense), income }
}
-type CategoryState = { show: boolean }
-type CategoriesState = Record<CategoryId, CategoryState>
-
-function createInitialState(storeCategories: Categories): CategoriesState {
- return Object.entries(storeCategories).reduce((acc, [id]) => {
- acc[id] = { show: false }
- return acc
- }, {} as CategoriesState)
-}
-
-const categoriesOpened = useStorage<CategoriesState>(
- `statCategoriesOpened1${props.storageKey}`,
- createInitialState(categoriesStore.items ?? {}),
+// Expand/collapse state
+const {
+ folderIcon,
+ isExpanded,
+ toggle: toggleCategory,
+ toggleAll: toggleAllCategories,
+} = useCategoriesExpanded(
+ props.storageKey,
+ categoriesStore.items ?? {},
+ categoriesWithData,
)
-
-function getCurrentState(categories: CategoryWithData[]): CategoriesState {
- return categories.reduce((acc, cat) => {
- acc[cat.id] = {
- show: categoriesOpened.value[cat.id]?.show ?? false,
- }
- return acc
- }, {} as CategoriesState)
-}
-
-const currentState = computed(() => getCurrentState(categoriesWithData.value))
-
-const openedStatus = computed(() => {
- const cats = Object.values(currentState.value)
- return {
- isAllRootOpen: cats.every(cat => cat.show),
- isAnyRootOpen: cats.some(cat => cat.show),
- }
-})
-
-function toggleOpened() {
- const newShow = !openedStatus.value.isAnyRootOpen
- Object.keys(currentState.value).forEach((id) => {
- categoriesOpened.value[id] = { show: newShow }
- })
-}
-
-function toggleRoot(id: CategoryId) {
- categoriesOpened.value[id] = {
- show: !categoriesOpened.value[id]?.show,
- }
-}
</script>
<template>
@@ -117,7 +84,7 @@ function toggleRoot(id: CategoryId) {
>
<!-- Vertical -->
<UiToggle
- v-if="statConfig.config.value.vertical.isShow"
+ v-if="isVerticalShow"
:storageKey="`${storageKey}-${type}-vertical`"
:initStatus="true"
>
@@ -131,16 +98,10 @@ function toggleRoot(id: CategoryId) {
v-if="isShown && !props.isOneCategory"
class="flex items-center"
>
- <UiActionButton
- :ariaLabel="$t('base.toggleGrouping')"
- :isActive="statConfig.config.value.vertical.isGrouped"
- @click="statConfig.config.value.vertical.isGrouped = !statConfig.config.value.vertical.isGrouped"
- >
- <Icon
- :name="statConfig.config.value.vertical.isGrouped ? 'lucide:network' : 'lucide:folder-tree'"
- :size="20"
- />
- </UiActionButton>
+ <StatCategoriesGroupingToggle
+ :isGrouped="isVerticalGrouped"
+ @toggle="statConfig.config.value.vertical.isGrouped = !isVerticalGrouped"
+ />
</div>
</div>
@@ -153,7 +114,7 @@ function toggleRoot(id: CategoryId) {
v-for="item in visibleVerticalCategories"
:key="item.id"
:item="item"
- :biggestCatNumber="verticalBiggestCatNumber"
+ :maxCategoryValues="verticalMaxValues"
@click="emit('clickCategory', item.id)"
/>
</div>
@@ -163,7 +124,7 @@ function toggleRoot(id: CategoryId) {
<!-- List -->
<UiToggle
- v-if="statConfig.config.value.catsList.isShow"
+ v-if="isListShow"
:storageKey="`${storageKey}-${type}-list`"
:initStatus="true"
class="@3xl/main:max-w-md"
@@ -179,46 +140,29 @@ function toggleRoot(id: CategoryId) {
class="flex items-center gap-1"
>
<UiActionButton
- v-if="statConfig.config.value.catsView === 'list' && !props.isOneCategory && statConfig.config.value.catsList.isGrouped"
+ v-if="statConfig.config.value.catsView === 'list' && !props.isOneCategory && isListGrouped"
:ariaLabel="$t('base.toggleFolders')"
- @click="toggleOpened"
+ @click="toggleAllCategories"
>
<Icon
- v-if="openedStatus.isAllRootOpen"
- name="lucide:folder-open"
- size="20"
- />
- <Icon
- v-if="!openedStatus.isAllRootOpen && openedStatus.isAnyRootOpen"
- name="lucide:folder-open-dot"
- size="20"
- />
- <Icon
- v-if="!openedStatus.isAllRootOpen && !openedStatus.isAnyRootOpen"
- name="lucide:folder"
+ :name="folderIcon"
size="20"
/>
</UiActionButton>
- <UiActionButton
+ <StatCategoriesGroupingToggle
v-if="!props.isOneCategory"
- :ariaLabel="$t('base.toggleGrouping')"
- :isActive="statConfig.config.value.catsList.isGrouped"
- @click="statConfig.config.value.catsList.isGrouped = !statConfig.config.value.catsList.isGrouped"
- >
- <Icon
- :name="statConfig.config.value.catsList.isGrouped ? 'lucide:network' : 'lucide:folder-tree'"
- :size="20"
- />
- </UiActionButton>
+ :isGrouped="isListGrouped"
+ @toggle="statConfig.config.value.catsList.isGrouped = !isListGrouped"
+ />
</div>
</div>
<div
v-if="isShown"
:class="{
- '@3xl/main:max-w-md': !statConfig.config.value.catsList.isGrouped,
- 'grid gap-1': statConfig.config.value.catsList.isItemsBg,
+ '@3xl/main:max-w-md': !isListGrouped,
+ 'grid gap-1': isItemsBg,
}"
class="pt-2"
>
@@ -226,44 +170,44 @@ function toggleRoot(id: CategoryId) {
v-for="item in linesCategories"
:key="item.id"
:class="{
- group: !statConfig.config.value.catsList.isItemsBg,
+ group: !isItemsBg,
}"
- :isShown="categoriesOpened[item.id]?.show ?? false"
+ :isShown="isExpanded(item.id)"
>
<template #header>
<div class="-mt-px flex items-stretch justify-between">
<StatCategoriesLine
- :isShowParent="props.isOneCategory ? false : !statConfig.config.value.catsList.isGrouped"
+ :isShowParent="props.isOneCategory ? false : !isListGrouped"
:item="item"
- :biggestCatNumber="linesBiggestCatNumber"
- :lineWidth="statConfig.config.value.catsList.isLines ? 0 : 1"
+ :maxCategoryValues="linesMaxValues"
+ :lineWidth="isLines ? 0 : 1"
class="grow"
- @click="item.categories?.length ? toggleRoot(item.id) : emit('clickCategory', item.id)"
+ @click="item.categories?.length ? toggleCategory(item.id) : emit('clickCategory', item.id)"
/>
</div>
</template>
<!-- Inside -->
<div
- v-if="categoriesOpened[item.id]?.show && item.categories?.length"
+ v-if="isExpanded(item.id) && item.categories?.length"
class="mt-[-2px] ml-5 -translate-x-px pb-3 pl-3"
>
<div
:class="{
- 'mt-1': statConfig.config.value.catsList.isItemsBg,
+ 'mt-1': isItemsBg,
}"
class="grid"
>
<StatCategoriesLine
v-for="itemInside in item.categories"
:key="itemInside.id"
- :isShowParent="!statConfig.config.value.catsList.isGrouped"
+ :isShowParent="!isListGrouped"
:item="itemInside"
- :biggestCatNumber="biggestCatNumber"
- :lineWidth="statConfig.config.value.catsList.isLines ? 0 : 1"
+ :maxCategoryValues="childrenMaxValues"
+ :lineWidth="isLines ? 0 : 1"
class="grow"
:class="{
- 'my-px': statConfig.config.value.catsList.isItemsBg,
+ 'my-px': isItemsBg,
}"
@click="emit('clickCategory', itemInside.id)"
/>
diff --git a/app/components/stat/categories/GroupingToggle.vue b/app/components/stat/categories/GroupingToggle.vue
new file mode 100644
index 00000000..4d02b3fc
--- /dev/null
+++ b/app/components/stat/categories/GroupingToggle.vue
@@ -0,0 +1,24 @@
+<script setup lang="ts">
+const props = defineProps<{
+ isGrouped: boolean
+ size?: string
+}>()
+
+const emit = defineEmits<{
+ toggle: []
+}>()
+</script>
+
+<template>
+ <UiActionButton
+ :ariaLabel="$t('base.toggleGrouping')"
+ :isActive="props.isGrouped"
+ :size="props.size"
+ @click="emit('toggle')"
+ >
+ <Icon
+ :name="props.isGrouped ? 'lucide:network' : 'lucide:folder-tree'"
+ :size="20"
+ />
+ </UiActionButton>
+</template>
diff --git a/app/components/stat/categories/Line.vue b/app/components/stat/categories/Line.vue
index 9b81ea7a..05a407bf 100644
--- a/app/components/stat/categories/Line.vue
+++ b/app/components/stat/categories/Line.vue
@@ -4,82 +4,48 @@ import type { CategoryWithData } from '~/components/stat/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
-import { statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
-import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
+import { computeBarStyle } from '~/components/stat/categories/barUtils'
+import { useCategoryLongPress } from '~/components/stat/categories/useCategoryLongPress'
+import { statConfigKey } from '~/components/stat/injectionKeys'
const props = defineProps<{
- biggestCatNumber: {
- expense: number
- income: number
- }
insideClass?: string
insideStyle?: string
isActive?: boolean
isShowParent?: boolean
item: CategoryWithData
lineWidth?: number
+ maxCategoryValues: {
+ expense: number
+ income: number
+ }
}>()
const emit = defineEmits<{
click: [categoryId: CategoryId]
}>()
-const statDate = inject(statDateKey)!
const statConfig = inject(statConfigKey)!
-const trnsFormStore = useTrnsFormStore()
const categoriesStore = useCategoriesStore()
const currenciesStore = useCurrenciesStore()
+const isItemsBg = computed(() => statConfig.config.value.catsList.isItemsBg)
+const isLines = computed(() => statConfig.config.value.catsList.isLines)
+const isRoundIcon = computed(() => statConfig.config.value.catsList.isRoundIcon)
+
const category = computed(() => categoriesStore.items[props.item.id])
const parentCategory = computed(() => {
const pid = category.value?.parentId
return pid ? categoriesStore.items[pid] : undefined
})
-function getBarStyle() {
- if (!props.item.value || props.item.value === 0)
- return
-
- const isIncome = props.item.value > 0
- const reference = isIncome ? props.biggestCatNumber.income : props.biggestCatNumber.expense
-
- return {
- backgroundColor: category.value?.color,
- width: `${(Math.abs(props.item.value) / Math.abs(reference)) * 100}%`,
- }
-}
-
-const longPressRef = ref(null)
-onLongPress(
- longPressRef,
- () => {
- const isTransactible = categoriesStore.isTransactible(props.item.id)
- if (!isTransactible)
- return
-
- trnsFormStore.openFormForCreate()
- trnsFormStore.$patch((state) => {
- state.values.amount = [0, 0, 0]
- state.values.amountRaw = ['', '', '']
- state.values.categoryId = props.item.id
- state.ui.isShow = true
+const barStyle = computed(() =>
+ computeBarStyle(props.item.value, category.value?.color, props.maxCategoryValues, 'width'),
+)
- const isDayDate = statDate.params.value.intervalSelected !== -1 && statDate.params.value.intervalsBy === 'day'
- if (isDayDate && statDate.selectedInterval.value?.start) {
- state.values.date = statDate.selectedInterval.value!.start
- }
- else {
- state.values.date = Date.now()
- }
- })
- },
- {
- onMouseUp: (duration: number, distance: number, isLongPress: boolean) => {
- if (!isLongPress && distance < 100) {
- emit('click', props.item.id)
- }
- },
- },
+const { longPressRef } = useCategoryLongPress(
+ () => props.item.id,
+ () => emit('click', props.item.id),
)
</script>
@@ -89,7 +55,7 @@ onLongPress(
ref="longPressRef"
:class="[props.insideClass, {
'-bg-item-3 ': props.isActive,
- 'bg-item-2 rounded-lg': statConfig.config.value.catsList.isItemsBg,
+ 'bg-item-2 rounded-lg': isItemsBg,
}]"
:style="props.insideStyle"
class="relative"
@@ -97,18 +63,18 @@ onLongPress(
<slot name="before" />
<UiElement
:isActive="props.isActive"
- :lineWidth="!statConfig.config.value.catsList.isItemsBg ? props.lineWidth : 0"
+ :lineWidth="!isItemsBg ? props.lineWidth : 0"
class="relative"
insideClasses="!min-h-[44px]"
>
<template #line>
<div
- v-if="statConfig.config.value.catsList.isLines"
+ v-if="isLines"
class="absolute bottom-2 left-0 w-full overflow-hidden rounded-lg pr-3 pl-[52px]"
>
<div class="bg-item-4 overflow-hidden rounded-lg">
<div
- :style="getBarStyle()"
+ :style="barStyle"
class="h-1 opacity-60"
/>
</div>
@@ -117,7 +83,7 @@ onLongPress(
<template #leftIcon>
<UiIconBase
- v-if="statConfig.config.value.catsList.isRoundIcon"
+ v-if="isRoundIcon"
:color="category?.color"
:name="category?.icon"
invert
@@ -132,7 +98,7 @@ onLongPress(
<CategoriesName
:category
- :class="{ '!pb-2': statConfig.config.value.catsList.isLines }"
+ :class="{ '!pb-2': isLines }"
:hasChildren="categoriesStore.getChildrenIds(props.item.id).length > 0"
:isShowParent="props.isShowParent"
:parentCategory
@@ -142,13 +108,13 @@ onLongPress(
<div
v-if="props.item.value !== 0"
:class="{
- '!pb-2': statConfig.config.value.catsList.isLines,
+ '!pb-2': isLines,
}"
class="grow pr-1"
>
<Amount
:amount="props.item.value"
- :type="props.item.value > 0 ? 1 : 0"
+ :type="getTrnTypeByAmount(props.item.value)"
:currencyCode="currenciesStore.base"
:isShowBaseRate="false"
:isShowSymbol="false"
diff --git a/app/components/stat/categories/Round2lines.vue b/app/components/stat/categories/Round2lines.vue
index d45965d3..40eb4502 100644
--- a/app/components/stat/categories/Round2lines.vue
+++ b/app/components/stat/categories/Round2lines.vue
@@ -4,8 +4,7 @@ import type { CategoryWithData } from '~/components/stat/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
import { useCurrenciesStore } from '~/components/currencies/useCurrenciesStore'
-import { statDateKey } from '~/components/stat/injectionKeys'
-import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
+import { useCategoryLongPress } from '~/components/stat/categories/useCategoryLongPress'
const props = defineProps<{
isShowAmount?: boolean
@@ -16,44 +15,14 @@ const emit = defineEmits<{
click: [categoryId: CategoryId]
}>()
-const statDate = inject(statDateKey)!
const categoriesStore = useCategoriesStore()
const currenciesStore = useCurrenciesStore()
-const trnsFormStore = useTrnsFormStore()
const category = computed(() => categoriesStore.items[props.item.id])
-const longPressRef = ref(null)
-onLongPress(
- longPressRef,
- () => {
- const isTransactible = categoriesStore.isTransactible(props.item.id)
- if (!isTransactible)
- return
-
- trnsFormStore.openFormForCreate()
- trnsFormStore.$patch((state) => {
- state.values.amount = [0, 0, 0]
- state.values.amountRaw = ['', '', '']
- state.values.categoryId = props.item.id
- state.ui.isShow = true
-
- const isDayDate = statDate.params.value.intervalSelected !== -1 && statDate.params.value.intervalsBy === 'day'
- if (isDayDate && statDate.selectedInterval.value?.start) {
- state.values.date = statDate.selectedInterval.value!.start
- }
- else {
- state.values.date = Date.now()
- }
- })
- },
- {
- onMouseUp: (duration: number, distance: number, isLongPress: boolean) => {
- if (!isLongPress && distance < 100) {
- emit('click', props.item.id)
- }
- },
- },
+const { longPressRef } = useCategoryLongPress(
+ () => props.item.id,
+ () => emit('click', props.item.id),
)
</script>
@@ -89,7 +58,7 @@ onLongPress(
>
<Amount
:amount="props.item.value"
- :type="props.item.value > 0 ? 1 : 0"
+ :type="getTrnTypeByAmount(props.item.value)"
:currencyCode="currenciesStore.base"
:isShowBaseRate="false"
:isShowSymbol="false"
diff --git a/app/components/stat/categories/Section.vue b/app/components/stat/categories/RoundSection.vue
similarity index 81%
rename from app/components/stat/categories/Section.vue
rename to app/components/stat/categories/RoundSection.vue
index 214f1eb5..3d186672 100644
--- a/app/components/stat/categories/Section.vue
+++ b/app/components/stat/categories/RoundSection.vue
@@ -23,7 +23,8 @@ const { computeCategoriesWithData } = useStatCategories()
const statConfig = inject(statConfigKey)!
const isExpanded = ref(false)
-const roundCategories = computed(() => computeCategoriesWithData(props.selectedTrnsIds ?? [], statConfig.config.value.catsRound.isGrouped, props.preCategoriesIds))
+const isGrouped = computed(() => statConfig.config.value.catsRound.isGrouped)
+const roundCategories = computed(() => computeCategoriesWithData(props.selectedTrnsIds ?? [], isGrouped.value, props.preCategoriesIds))
const visibleCategories = computed(() => isExpanded.value ? roundCategories.value : roundCategories.value.slice(0, visibleCategoriesLimit))
const filteredSet = computed(() => new Set(props.filteredCategoriesIds))
</script>
@@ -61,16 +62,11 @@ const filteredSet = computed(() => new Set(props.filteredCategoriesIds))
/>
</UiActionButton>
- <UiActionButton
- :ariaLabel="$t('base.toggleGrouping')"
+ <StatCategoriesGroupingToggle
+ :isGrouped="isGrouped"
size="sm"
- @click="statConfig.config.value.catsRound.isGrouped = !statConfig.config.value.catsRound.isGrouped"
- >
- <Icon
- :name="statConfig.config.value.catsRound.isGrouped ? 'lucide:network' : 'lucide:folder-tree'"
- :size="20"
- />
- </UiActionButton>
+ @toggle="statConfig.config.value.catsRound.isGrouped = !isGrouped"
+ />
</UiTabsBar>
</div>
</div>
diff --git a/app/components/stat/categories/Vertical.vue b/app/components/stat/categories/Vertical.vue
index 980f2190..34d3e7fc 100644
--- a/app/components/stat/categories/Vertical.vue
+++ b/app/components/stat/categories/Vertical.vue
@@ -3,85 +3,34 @@ import type { CategoryId } from '~/components/categories/types'
import type { CategoryWithData } from '~/components/stat/types'
import { useCategoriesStore } from '~/components/categories/useCategoriesStore'
-import { statDateKey } from '~/components/stat/injectionKeys'
-import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
+import { computeBarStyle, formatCompactAmount } from '~/components/stat/categories/barUtils'
+import { useCategoryLongPress } from '~/components/stat/categories/useCategoryLongPress'
const props = defineProps<{
- biggestCatNumber: {
+ item: CategoryWithData
+ maxCategoryValues: {
expense: number
income: number
}
- item: CategoryWithData
}>()
const emit = defineEmits<{
click: [categoryId: CategoryId]
}>()
-const statDate = inject(statDateKey)!
-const trnsFormStore = useTrnsFormStore()
const categoriesStore = useCategoriesStore()
const category = computed(() => categoriesStore.items[props.item.id])
-function getBarStyle() {
- if (!props.item.value || props.item.value === 0)
- return
-
- const isIncome = props.item.value > 0
- const reference = isIncome ? props.biggestCatNumber.income : props.biggestCatNumber.expense
-
- return {
- backgroundColor: category.value?.color,
- height: `${(Math.abs(props.item.value) / Math.abs(reference)) * 100}%`,
- }
-}
-
-const amount = computed(() => {
- const abs = Math.abs(props.item.value)
- const sign = props.item.value > 0 ? '' : '-'
-
- if (abs >= 1000000)
- return `${(props.item.value / 1000000).toFixed(2)}M`
- else if (abs >= 10000)
- return `${sign}${(abs / 1000).toFixed()}K`
- else if (abs > 999)
- return `${sign}${(abs / 1000).toFixed(1)}K`
-
- return `${props.item.value.toFixed()}`
-})
-
-const longPressRef = ref(null)
-onLongPress(
- longPressRef,
- () => {
- const isTransactible = categoriesStore.isTransactible(props.item.id)
- if (!isTransactible)
- return
+const barStyle = computed(() =>
+ computeBarStyle(props.item.value, category.value?.color, props.maxCategoryValues, 'height'),
+)
- trnsFormStore.openFormForCreate()
- trnsFormStore.$patch((state) => {
- state.values.amount = [0, 0, 0]
- state.values.amountRaw = ['', '', '']
- state.values.categoryId = props.item.id
- state.ui.isShow = true
+const amount = computed(() => formatCompactAmount(props.item.value))
- const isDayDate = statDate.params.value.intervalSelected !== -1 && statDate.params.value.intervalsBy === 'day'
- if (isDayDate && statDate.selectedInterval.value?.start) {
- state.values.date = statDate.selectedInterval.value!.start
- }
- else {
- state.values.date = Date.now()
- }
- })
- },
- {
- onMouseUp: (duration: number, distance: number, isLongPress: boolean) => {
- if (!isLongPress && distance < 100) {
- emit('click', props.item.id)
- }
- },
- },
+const { longPressRef } = useCategoryLongPress(
+ () => props.item.id,
+ () => emit('click', props.item.id),
)
</script>
@@ -94,7 +43,7 @@ onLongPress(
<div class="bg-item-3 flex h-28 items-end rounded-sm">
<div
class="relative w-7 rounded-t"
- :style="getBarStyle()"
+ :style="barStyle"
>
<div
:class="cn('font-secondary absolute top-[-14px] w-full text-center text-xs leading-none',
diff --git a/app/components/stat/categories/barUtils.test.ts b/app/components/stat/categories/barUtils.test.ts
new file mode 100644
index 00000000..a1347632
--- /dev/null
+++ b/app/components/stat/categories/barUtils.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest'
+
+import { computeBarStyle, formatCompactAmount } from '~/components/stat/categories/barUtils'
+
+describe('computeBarStyle', () => {
+ const biggest = { expense: 500, income: 1000 }
+
+ it('returns undefined for zero value', () => {
+ expect(computeBarStyle(0, 'red', biggest, 'width')).toBeUndefined()
+ })
+
+ it('computes width for positive (income) value', () => {
+ const result = computeBarStyle(500, 'green', biggest, 'width')
+ expect(result).toEqual({ backgroundColor: 'green', width: '50%' })
+ })
+
+ it('computes height for negative (expense) value', () => {
+ const result = computeBarStyle(-250, 'red', biggest, 'height')
+ expect(result).toEqual({ backgroundColor: 'red', height: '50%' })
+ })
+
+ it('computes 100% for value equal to reference', () => {
+ const result = computeBarStyle(1000, 'blue', biggest, 'width')
+ expect(result).toEqual({ backgroundColor: 'blue', width: '100%' })
+ })
+
+ it('handles undefined color', () => {
+ const result = computeBarStyle(500, undefined, biggest, 'width')
+ expect(result).toEqual({ backgroundColor: undefined, width: '50%' })
+ })
+})
+
+describe('formatCompactAmount', () => {
+ it('formats millions', () => {
+ expect(formatCompactAmount(1500000)).toBe('1.50M')
+ expect(formatCompactAmount(-2300000)).toBe('-2.30M')
+ })
+
+ it('formats tens of thousands', () => {
+ expect(formatCompactAmount(15000)).toBe('15K')
+ expect(formatCompactAmount(-42000)).toBe('-42K')
+ })
+
+ it('formats thousands with decimal', () => {
+ expect(formatCompactAmount(1500)).toBe('1.5K')
+ expect(formatCompactAmount(-5600)).toBe('-5.6K')
+ })
+
+ it('formats small numbers as integers', () => {
+ expect(formatCompactAmount(999)).toBe('999')
+ expect(formatCompactAmount(42)).toBe('42')
+ expect(formatCompactAmount(-100)).toBe('-100')
+ })
+
+ it('formats zero', () => {
+ expect(formatCompactAmount(0)).toBe('0')
+ })
+})
diff --git a/app/components/stat/categories/barUtils.ts b/app/components/stat/categories/barUtils.ts
new file mode 100644
index 00000000..b6102632
--- /dev/null
+++ b/app/components/stat/categories/barUtils.ts
@@ -0,0 +1,43 @@
+type MaxCategoryValues = {
+ expense: number
+ income: number
+}
+
+/**
+ * Compute bar style for category proportional display.
+ * Used in Vertical (height) and Line (width) category views.
+ */
+export function computeBarStyle(
+ value: number,
+ color: string | undefined,
+ maxCategoryValues: MaxCategoryValues,
+ dimension: 'height' | 'width',
+) {
+ if (!value || value === 0)
+ return
+
+ const isIncome = value > 0
+ const reference = isIncome ? maxCategoryValues.income : maxCategoryValues.expense
+
+ return {
+ backgroundColor: color,
+ [dimension]: `${(Math.abs(value) / Math.abs(reference)) * 100}%`,
+ }
+}
+
+/**
+ * Format amount with K/M abbreviations for compact display.
+ */
+export function formatCompactAmount(value: number): string {
+ const abs = Math.abs(value)
+ const sign = value > 0 ? '' : '-'
+
+ if (abs >= 1000000)
+ return `${(value / 1000000).toFixed(2)}M`
+ if (abs >= 10000)
+ return `${sign}${(abs / 1000).toFixed()}K`
+ if (abs > 999)
+ return `${sign}${(abs / 1000).toFixed(1)}K`
+
+ return `${value.toFixed()}`
+}
diff --git a/app/components/stat/categories/useCategoriesExpanded.ts b/app/components/stat/categories/useCategoriesExpanded.ts
new file mode 100644
index 00000000..802a250e
--- /dev/null
+++ b/app/components/stat/categories/useCategoriesExpanded.ts
@@ -0,0 +1,69 @@
+import type { ComputedRef } from 'vue'
+
+import { useStorage } from '@vueuse/core'
+
+import type { Categories, CategoryId } from '~/components/categories/types'
+import type { CategoryWithData } from '~/components/stat/types'
+
+type CategoryState = { show: boolean }
+type CategoriesState = Record<CategoryId, CategoryState>
+
+function createInitialState(categories: Categories): CategoriesState {
+ return Object.keys(categories).reduce((acc, id) => {
+ acc[id] = { show: false }
+ return acc
+ }, {} as CategoriesState)
+}
+
+export function useCategoriesExpanded(
+ storageKey: string,
+ storeCategories: Categories,
+ categoriesWithData: ComputedRef<CategoryWithData[]>,
+) {
+ const expandedState = useStorage<CategoriesState>(
+ `statCategoriesOpened1${storageKey}`,
+ createInitialState(storeCategories),
+ )
+
+ const currentState = computed(() =>
+ categoriesWithData.value.reduce((acc, cat) => {
+ acc[cat.id] = { show: expandedState.value[cat.id]?.show ?? false }
+ return acc
+ }, {} as CategoriesState),
+ )
+
+ const isAllExpanded = computed(() => Object.values(currentState.value).every(c => c.show))
+ const isAnyExpanded = computed(() => Object.values(currentState.value).some(c => c.show))
+
+ const folderIcon = computed(() => {
+ if (isAllExpanded.value)
+ return 'lucide:folder-open'
+ if (isAnyExpanded.value)
+ return 'lucide:folder-open-dot'
+ return 'lucide:folder'
+ })
+
+ function toggleAll() {
+ const newShow = !isAnyExpanded.value
+ Object.keys(currentState.value).forEach((id) => {
+ expandedState.value[id] = { show: newShow }
+ })
+ }
+
+ function toggle(id: CategoryId) {
+ expandedState.value[id] = { show: !expandedState.value[id]?.show }
+ }
+
+ function isExpanded(id: CategoryId) {
+ return expandedState.value[id]?.show ?? false
+ }
+
+ return {
+ folderIcon,
+ isAllExpanded,
+ isAnyExpanded,
+ isExpanded,
+ toggle,
+ toggleAll,
+ }
+}
diff --git a/app/components/stat/chart/Intervals.vue b/app/components/stat/chart/Intervals.vue
index 00ee4a1e..2fa8a8b3 100644
--- a/app/components/stat/chart/Intervals.vue
+++ b/app/components/stat/chart/Intervals.vue
@@ -14,10 +14,10 @@ const emit = defineEmits<{
const { t } = useI18n()
-const items = computed(() => {
+const availableIntervals = computed(() => {
const dayDiff = differenceInDays(props.range.end, props.range.start)
- const items = [{
+ return [{
isShow: props.period !== 'day' || dayDiff > 7,
label: t('dates.day.simple'),
value: 'day',
@@ -33,24 +33,22 @@ const items = computed(() => {
isShow: dayDiff >= 400,
label: t('dates.year.simple'),
value: 'year',
- }]
-
- return items.filter(i => i.isShow)
+ }].filter(i => i.isShow)
})
-const value = ref(props.period)
+const selectedPeriod = ref(props.period)
</script>
<template>
<USelect
- v-if="items.length > 1"
- v-model="value"
- :items="items"
+ v-if="availableIntervals.length > 1"
+ v-model="selectedPeriod"
+ :items="availableIntervals"
:ui="{
base: 'ring-0 text-muted text-2xs hover:bg-(--item-5)',
trailingIcon: 'size-4',
content: 'w-24',
}"
- @change="emit('changePeriod', value)"
+ @change="emit('changePeriod', selectedPeriod)"
/>
</template>
diff --git a/app/components/stat/chart/View.vue b/app/components/stat/chart/View.vue
index 720ced4b..94060cf7 100644
--- a/app/components/stat/chart/View.vue
+++ b/app/components/stat/chart/View.vue
@@ -11,8 +11,8 @@ import type { ChartType } from '~/components/stat/chart/types'
import type { ChartSeries } from '~/components/stat/types'
import { formatByLocale } from '~/components/date/utils'
-import { config, lineConfig } from '~/components/stat/chart/config'
-import { getLocalAmount } from '~/components/stat/chart/utils'
+import { config, defaultSeriesConfig } from '~/components/stat/chart/config'
+import { formatChartAmount } from '~/components/stat/chart/utils'
type TooltipParam = {
color: string
@@ -64,7 +64,7 @@ function getFormatForChart(periodName: Period) {
const option = computed(() => {
const data = defu(config, {
- series: setChartSeries(series),
+ series: buildChartSeries(series),
xAxis: {
data: xAxisLabels,
type: 'category',
@@ -80,6 +80,10 @@ const option = computed(() => {
return formatByLocale(new Date(+value), getFormatForChart(period), locale.value)
}
+ const yAxis = data.yAxis as Record<string, any>
+ yAxis.axisPointer.label.formatter = (props: { value: number }) =>
+ formatChartAmount(+props.value, locale.value) ?? ''
+
return data
})
@@ -92,11 +96,11 @@ async function onClickChart(params: { offsetX: number, offsetY: number }) {
emit('click', index)
}
-function setChartSeries(series: ChartSeries[]) {
+function buildChartSeries(series: ChartSeries[]) {
return series
.map((item: ChartSeries) => ({
- ...defu(lineConfig, item),
- label: lineConfig.label,
+ ...defu(defaultSeriesConfig, item),
+ label: defaultSeriesConfig.label,
stack: (chartType || item.type) === 'bar' ? 'b' : false,
type: item.markedArea ? 'bar' : (chartType || item.type),
}))
@@ -132,7 +136,7 @@ function setChartSeries(series: ChartSeries[]) {
</div>
<div class="font-secondary text-1 text-right text-lg">
- {{ getLocalAmount(param.value) }}
+ {{ formatChartAmount(param.value, locale) }}
</div>
</div>
</div>
diff --git a/app/components/stat/chart/Wrap.vue b/app/components/stat/chart/Wrap.vue
index 7acc6dc7..69fec2c2 100644
--- a/app/components/stat/chart/Wrap.vue
+++ b/app/components/stat/chart/Wrap.vue
@@ -1,13 +1,11 @@
<script setup lang="ts">
import type { Period } from '~/components/date/types'
import type { ChartSeries } from '~/components/stat/types'
-import type { MiniItemConfig } from '~/components/stat/useStatConfig'
import { statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
import { useTrnsFormStore } from '~/components/trnForm/useTrnsFormStore'
-const props = defineProps<{
- chartView: MiniItemConfig['chartView']
+defineProps<{
series: ChartSeries[]
xAxisLabels: number[]
}>()
@@ -16,49 +14,35 @@ const statDate = inject(statDateKey)!
const statConfig = inject(statConfigKey)!
const trnsFormStore = useTrnsFormStore()
-function onClickChart(idx: number) {
- const newPeriod = idx
-
- // Handle when click outside of chart
- if (newPeriod === statDate.intervalsInRange.value.length) {
- statDate.params.value.intervalSelected = -1
- return
- }
+const isChartShow = computed(() => statConfig.config.value.isChartShow)
+const chartView = computed(() => statConfig.config.value.chartView)
+const chartType = computed(() => statConfig.config.value.chartType)
+const isShowQuick = computed(() => statConfig.config.value.date.isShowQuick)
- // Handle when click on the same period
- if (statDate.params.value.intervalSelected === newPeriod) {
- statDate.params.value.intervalSelected = -1
- }
- else {
- statDate.params.value.intervalSelected = newPeriod
-
- if (statDate.params.value.intervalsBy === 'day' && statDate.params.value.intervalsDuration === 1) {
- const day = statDate.intervalsInRange.value[statDate.params.value.intervalSelected]?.start
- if (day)
- trnsFormStore.values.date = day
- }
- }
+function onClickChart(idx: number) {
+ const day = statDate.selectInterval(idx)
+ if (day)
+ trnsFormStore.values.date = day
}
function onChangePeriod(period: Period) {
- statDate.params.value.intervalSelected = -1
- statDate.params.value.intervalsBy = period
+ statDate.setIntervalsBy(period)
}
</script>
<template>
<div
- v-if="statConfig.config.value.isChartShow"
+ v-if="isChartShow"
:class="{
- '@3xl/main:max-w-xl': props.chartView === 'half',
+ '@3xl/main:max-w-xl': chartView === 'half',
}"
>
<div class="-mb-1 flex justify-end">
- <slot />
+ <StatDateQuick v-if="isShowQuick" />
<div class="h-7">
<StatChartIntervals
- :class="{ 'border-item-4 border-l': statConfig.config.value.date.isShowQuick }"
+ :class="{ 'border-item-4 border-l': isShowQuick }"
:period="statDate.params.value.intervalsBy"
:range="statDate.range.value"
@changePeriod="onChangePeriod"
@@ -67,10 +51,10 @@ function onChangePeriod(period: Period) {
</div>
<LazyStatChartView
- :chartType="statConfig.config.value.chartType"
+ :chartType
:period="statDate.params.value.intervalsBy"
- :series="props.series"
- :xAxisLabels="props.xAxisLabels"
+ :series
+ :xAxisLabels
@click="onClickChart"
/>
</div>
diff --git a/app/components/stat/chart/config.ts b/app/components/stat/chart/config.ts
index c2bae728..7c1ed087 100644
--- a/app/components/stat/chart/config.ts
+++ b/app/components/stat/chart/config.ts
@@ -5,7 +5,7 @@ import type { ComposeOption } from 'echarts/core'
import type { SeriesSlug } from '~/components/stat/types'
-import { getCompactAmount, getLocalAmount } from '~/components/stat/chart/utils'
+import { formatChartAmount, formatCompactChartAmount } from '~/components/stat/chart/utils'
type EChartsOption = ComposeOption<
| TooltipComponentOption
@@ -79,7 +79,7 @@ export const config: EChartsOption['baseOption'] = {
yAxis: {
axisLabel: {
color: 'var(--chart-label)',
- formatter: (n: number) => getCompactAmount(n),
+ formatter: (n: number) => formatCompactChartAmount(n),
show: false, // TODO: config
},
axisLine: {
@@ -91,7 +91,7 @@ export const config: EChartsOption['baseOption'] = {
label: {
backgroundColor: 'var(--chart-line)',
color: 'var(--chart-axisLabel)',
- formatter: props => getLocalAmount(+props.value) ?? '',
+ formatter: props => formatChartAmount(+props.value) ?? '',
},
snap: true,
},
@@ -108,7 +108,7 @@ export const config: EChartsOption['baseOption'] = {
},
}
-export const lineConfig = {
+export const defaultSeriesConfig = {
areaStyle: {
opacity: 0.1,
},
@@ -120,7 +120,7 @@ export const lineConfig = {
disabled: true,
},
label: {
- formatter: ({ value }: { value: number }) => getCompactAmount(value),
+ formatter: ({ value }: { value: number }) => formatCompactChartAmount(value),
position: 'top',
show: false,
},
diff --git a/app/components/stat/chart/useStatChart.ts b/app/components/stat/chart/useStatChart.ts
index 13ac0051..9c976c23 100644
--- a/app/components/stat/chart/useStatChart.ts
+++ b/app/components/stat/chart/useStatChart.ts
@@ -4,12 +4,12 @@ import type { ChartType } from '~/components/stat/chart/types'
import type { ChartSeries, SeriesSlug } from '~/components/stat/types'
import { seriesOptions } from '~/components/stat/chart/config'
-import { markArea } from '~/components/stat/chart/utils'
+import { createMarkAreaData } from '~/components/stat/chart/utils'
export function useStatChart() {
const { t } = useI18n()
- const chartTypes = computed<{ icon: string, label: string, value: ChartType }[]>(() => [{
+ const chartTypeOptions = computed<{ icon: string, label: string, value: ChartType }[]>(() => [{
icon: 'lucide:chart-line',
label: t('chart.types.bar'),
value: 'bar',
@@ -49,20 +49,20 @@ export function useStatChart() {
}
}
- function addMarkArea(series: ChartSeries[], markedDate: DateUTC, chartType?: ChartType) {
+ function withMarkArea(series: ChartSeries[], markedDate: DateUTC, chartType?: ChartType) {
if (!markedDate)
return series
if (chartType === 'bar') {
if (series[0])
- series[0].markArea = markArea(markedDate)
+ series[0].markArea = createMarkAreaData(markedDate)
return series
}
const markAreaIdx = series.findIndex(s => s.markedArea === 'markedArea')
const markAreaSeries: ChartSeries = {
data: [],
- markArea: markArea(markedDate),
+ markArea: createMarkAreaData(markedDate),
markedArea: 'markedArea',
name: 'markArea',
type: 'bar',
@@ -74,8 +74,8 @@ export function useStatChart() {
}
return {
- addMarkArea,
- chartTypes,
+ chartTypeOptions,
createSeriesItem,
+ withMarkArea,
}
}
diff --git a/app/components/stat/chart/utils.ts b/app/components/stat/chart/utils.ts
index a45902b2..b24bd7b1 100644
--- a/app/components/stat/chart/utils.ts
+++ b/app/components/stat/chart/utils.ts
@@ -1,4 +1,4 @@
-export function markArea(value: number): {
+export function createMarkAreaData(value: number): {
data: [{ xAxis: string }, { xAxis: string }][]
itemStyle: { color: string, opacity: number }
} {
@@ -8,13 +8,22 @@ export function markArea(value: number): {
}
}
-export function getCompactAmount(amount: number) {
- return new Intl.NumberFormat('en', { notation: 'compact' }).format(amount)
+const compactFormatter = new Intl.NumberFormat('en', { notation: 'compact' })
+
+export function formatCompactChartAmount(amount: number) {
+ return compactFormatter.format(amount)
}
-export function getLocalAmount(amount: number) {
- return new Intl.NumberFormat('ru', {
- maximumFractionDigits: 0,
- minimumFractionDigits: 0,
- }).format(amount)
+const amountFormatters = new Map<string, Intl.NumberFormat>()
+
+export function formatChartAmount(amount: number, locale = 'en') {
+ let formatter = amountFormatters.get(locale)
+ if (!formatter) {
+ formatter = new Intl.NumberFormat(locale, {
+ maximumFractionDigits: 0,
+ minimumFractionDigits: 0,
+ })
+ amountFormatters.set(locale, formatter)
+ }
+ return formatter.format(amount)
}
diff --git a/app/components/stat/filter/Selector.vue b/app/components/stat/filter/Selector.vue
index e3b6d0a0..019779e6 100644
--- a/app/components/stat/filter/Selector.vue
+++ b/app/components/stat/filter/Selector.vue
@@ -8,108 +8,38 @@ const props = defineProps<{
const filter = inject(filterKey)!
const { t } = useI18n()
-
-const modals = ref({
- categories: false,
- wallets: false,
-})
</script>
<template>
<div class="flex gap-1">
- <BottomSheetOrDropdown
+ <StatFilterSelectorItem
v-if="props.isShowWallets"
+ :hasSelection="filter?.walletsIds.value.length > 0"
:title="t('wallets.filter')"
- :isOpen="modals.wallets"
- isShowCloseBtn
- @openModal="modals.wallets = true"
- @closeModal="modals.wallets = false"
+ icon="hugeicons:wallet-01"
>
- <template #trigger>
- <UTooltip :text="t('wallets.filter')">
- <UChip
- :show="filter?.walletsIds.value.length > 0"
- color="secondary"
- inset
- size="xs"
- >
- <UButton
- :aria-label="t('wallets.filter')"
- class="text-muted"
- color="neutral"
- icon="hugeicons:wallet-01"
- size="lg"
- square
- variant="ghost"
- />
- </UChip>
- </UTooltip>
- </template>
-
- <template #custom="{ close }">
- <div class="grid h-full max-h-[60dvh] grid-rows-[1fr_auto] overflow-hidden">
- <WalletsSelector
- :selectedIds="filter?.walletsIds.value"
- class="min-w-80 px-3"
- @selected="filter.toggleWalletId"
- />
-
- <div class="px-3 py-2">
- <UiButtonAccent @click="close">
- {{ t('base.apply') }}
- </UiButtonAccent>
- </div>
- </div>
- </template>
- </BottomSheetOrDropdown>
-
- <BottomSheetOrDropdown
+ <WalletsSelector
+ :selectedIds="filter?.walletsIds.value"
+ class="min-w-80 px-3"
+ @selected="filter.toggleWalletId"
+ />
+ </StatFilterSelectorItem>
+
+ <StatFilterSelectorItem
v-if="props.isShowCategories"
+ :buttonLabel="t('base.close')"
+ :hasSelection="filter?.categoriesIds.value.length > 0"
:title="t('categories.filter')"
- :isOpen="modals.categories"
- isShowCloseBtn
- @openModal="modals.categories = true"
- @closeModal="modals.categories = false"
+ icon="hugeicons:folder-library"
>
- <template #trigger>
- <UTooltip :text="t('categories.filter')">
- <UChip
- :show="filter?.categoriesIds.value.length > 0"
- color="secondary"
- inset
- size="xs"
- >
- <UButton
- :aria-label="t('categories.filter')"
- class="text-muted"
- color="neutral"
- icon="hugeicons:folder-library"
- size="lg"
- square
- variant="ghost"
- />
- </UChip>
- </UTooltip>
- </template>
-
- <template #custom="{ close }">
- <div class="grid h-full max-h-[60dvh] grid-rows-[1fr_auto] overflow-hidden">
- <div class="scrollerBlock overflow-y-auto">
- <CategoriesSelectorTree
- :selectedIds="filter?.categoriesIds.value"
- class="min-w-80 px-3"
- @selected="filter.toggleCategoryId"
- @setCategories="filter.setCategories"
- />
- </div>
-
- <div class="px-3 py-2">
- <UiButtonAccent @click="close">
- {{ t('base.close') }}
- </UiButtonAccent>
- </div>
- </div>
- </template>
- </BottomSheetOrDropdown>
+ <div class="scrollerBlock overflow-y-auto">
+ <CategoriesSelectorTree
+ :selectedIds="filter?.categoriesIds.value"
+ class="min-w-80 px-3"
+ @selected="filter.toggleCategoryId"
+ @setCategories="filter.setCategories"
+ />
+ </div>
+ </StatFilterSelectorItem>
</div>
</template>
diff --git a/app/components/stat/filter/SelectorItem.vue b/app/components/stat/filter/SelectorItem.vue
new file mode 100644
index 00000000..7206bedd
--- /dev/null
+++ b/app/components/stat/filter/SelectorItem.vue
@@ -0,0 +1,55 @@
+<script setup lang="ts">
+const props = defineProps<{
+ buttonLabel?: string
+ hasSelection: boolean
+ icon: string
+ title: string
+}>()
+
+const { t } = useI18n()
+
+const isOpen = ref(false)
+</script>
+
+<template>
+ <BottomSheetOrDropdown
+ :title="props.title"
+ :isOpen="isOpen"
+ isShowCloseBtn
+ @openModal="isOpen = true"
+ @closeModal="isOpen = false"
+ >
+ <template #trigger>
+ <UTooltip :text="props.title">
+ <UChip
+ :show="props.hasSelection"
+ color="secondary"
+ inset
+ size="xs"
+ >
+ <UButton
+ :aria-label="props.title"
+ :icon="props.icon"
+ class="text-muted"
+ color="neutral"
+ size="lg"
+ square
+ variant="ghost"
+ />
+ </UChip>
+ </UTooltip>
+ </template>
+
+ <template #custom="{ close }">
+ <div class="grid h-full max-h-[60dvh] grid-rows-[1fr_auto] overflow-hidden">
+ <slot :close="close" />
+
+ <div class="px-3 py-2">
+ <UiButtonAccent @click="close">
+ {{ props.buttonLabel ?? t('base.apply') }}
+ </UiButtonAccent>
+ </div>
+ </div>
+ </template>
+ </BottomSheetOrDropdown>
+</template>
diff --git a/app/components/stat/sum/Item.vue b/app/components/stat/sum/Item.vue
index 57e7f00b..37600dde 100644
--- a/app/components/stat/sum/Item.vue
+++ b/app/components/stat/sum/Item.vue
@@ -28,12 +28,8 @@ const currenciesStore = useCurrenciesStore()
>
<div class="flex items-end gap-5">
<div class="grid gap-1">
- <UiTextSubtitle v-if="props.title">
- {{ props.title }}
- </UiTextSubtitle>
-
- <UiTextSubtitle v-if="!props.title">
- {{ t(`money.${props.type}`) }}
+ <UiTextSubtitle>
+ {{ props.title ?? t(`money.${props.type}`) }}
</UiTextSubtitle>
<Amount
diff --git a/app/components/stat/sum/Wrap.vue b/app/components/stat/sum/Wrap.vue
index 5945db61..ad272af0 100644
--- a/app/components/stat/sum/Wrap.vue
+++ b/app/components/stat/sum/Wrap.vue
@@ -5,15 +5,12 @@ import type { SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
import type { TrnId } from '~/components/trns/types'
import type { WalletId } from '~/components/wallets/types'
-import { filterKey, statConfigKey, statDateKey } from '~/components/stat/injectionKeys'
+import { statConfigKey } from '~/components/stat/injectionKeys'
const props = defineProps<{
averageTotal?: Record<string, number>
categoryId?: CategoryId
filteredType: SeriesSlugSelected
- isShowAverage: boolean
- isShowExpense: boolean
- isShowIncome: boolean
total: TotalReturns
trnsIds: TrnId[]
type: SeriesSlugSelected | StatTabSlug
@@ -26,20 +23,18 @@ const emit = defineEmits<{
}>()
const statConfig = inject(statConfigKey)!
-const filter = inject(filterKey)!
-const statDate = inject(statDateKey)!
+
+const isShowAverage = computed(() => statConfig.config.value.statAverage.isShow)
const className = computed(() => cn(
'min-w-min rounded-sm min-h-[42px] flex items-center px-3',
{
- interactive: props.isShowIncome && props.isShowExpense && props.type === 'summary',
+ interactive: props.type === 'summary',
},
))
function onClick(type: SeriesSlugSelected) {
- if (props.isShowIncome && props.isShowExpense) {
- emit('click', type)
- }
+ emit('click', type)
}
</script>
@@ -50,7 +45,6 @@ function onClick(type: SeriesSlugSelected) {
class="flex flex-wrap gap-2 @2xl/page:justify-start"
>
<StatSumItem
- v-if="props.isShowExpense"
:amount="-total.expense"
:isActive="filteredType === 'expense'"
:class="className"
@@ -58,11 +52,8 @@ function onClick(type: SeriesSlugSelected) {
@click="onClick('expense')"
>
<StatAverage
- v-if="props.isShowAverage"
- :averageConfig="statConfig.config.value.statAverage.count"
+ v-if="isShowAverage"
:categoryId
- :filter
- :statDate
:trnsIds
:walletId
statTabSlug="expense"
@@ -70,7 +61,6 @@ function onClick(type: SeriesSlugSelected) {
</StatSumItem>
<StatSumItem
- v-if="props.isShowIncome"
:amount="total.income"
:isActive="filteredType === 'income'"
:class="className"
@@ -78,11 +68,8 @@ function onClick(type: SeriesSlugSelected) {
@click="onClick('income')"
>
<StatAverage
- v-if="props.isShowAverage"
- :averageConfig="statConfig.config.value.statAverage.count"
+ v-if="isShowAverage"
:categoryId
- :filter
- :statDate
:trnsIds
:walletId
statTabSlug="income"
@@ -90,18 +77,14 @@ function onClick(type: SeriesSlugSelected) {
</StatSumItem>
<StatSumItem
- v-if="props.isShowIncome && props.isShowExpense"
:amount="total.sum"
:class="className"
type="netIncome"
@click="onClick('netIncome')"
>
<StatAverage
- v-if="props.isShowAverage"
- :averageConfig="statConfig.config.value.statAverage.count"
+ v-if="isShowAverage"
:categoryId
- :filter
- :statDate
:trnsIds
:walletId
statTabSlug="netIncome"
@@ -114,15 +97,12 @@ function onClick(type: SeriesSlugSelected) {
:amount="props.type === 'income' ? total.income : -((total as Record<string, number>)[props.type]!)"
:class="className"
:type="(props.type as SeriesSlugSelected)"
- :averageTotal="props.isShowAverage ? props.averageTotal : undefined"
+ :averageTotal="isShowAverage ? props.averageTotal : undefined"
@click="emit('clickAverage')"
>
<StatAverage
- v-if="props.isShowAverage"
- :averageConfig="statConfig.config.value.statAverage.count"
+ v-if="isShowAverage"
:categoryId
- :filter
- :statDate
:statTabSlug="(props.type ?? 'netIncome') as SeriesSlugSelected"
:trnsIds
:walletId
diff --git a/app/components/stat/types.ts b/app/components/stat/types.ts
index 5c4c39c8..52618df9 100644
--- a/app/components/stat/types.ts
+++ b/app/components/stat/types.ts
@@ -41,9 +41,3 @@ export type IntervalData = {
total: TotalReturns
trnsIds: TrnId[]
}
-
-export type StatConfigModal = {
- close: () => void
- isShow: boolean
- show: () => void
-}
diff --git a/app/components/stat/useStatConfig.ts b/app/components/stat/useStatConfig.ts
index c54a0ccc..edaa85d5 100644
--- a/app/components/stat/useStatConfig.ts
+++ b/app/components/stat/useStatConfig.ts
@@ -54,13 +54,13 @@ type StatConfigParams = {
}
export function useStatConfig({ props, storageKey }: StatConfigParams) {
- const newBaseStorageKey = computed(() => {
+ const configStorageKey = computed(() => {
const query = useRouter().currentRoute.value.query
const queryKey = Object.entries(query).map(([k, v]) => `${k}=${v}`).join('&')
return `finapp-${storageKey}-${queryKey}`
})
- const config = useStorage<MiniItemConfig>(newBaseStorageKey.value, {
+ const config = useStorage<MiniItemConfig>(configStorageKey.value, {
catsList: {
isGrouped: true,
isItemsBg: false,
diff --git a/app/components/stat/useStatItem.test.ts b/app/components/stat/useStatItem.test.ts
new file mode 100644
index 00000000..a23f2404
--- /dev/null
+++ b/app/components/stat/useStatItem.test.ts
@@ -0,0 +1,381 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { computed, ref } from 'vue'
+
+import type { TotalReturns } from '~/components/amount/getTotal'
+import type { Range } from '~/components/date/types'
+import type { IntervalData } from '~/components/stat/types'
+
+// ---------------------------------------------------------------------------
+// Stub Nuxt/Vue auto-imports used by useStatItem
+// ---------------------------------------------------------------------------
+vi.stubGlobal('computed', computed)
+vi.stubGlobal('ref', ref)
+vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
+
+// ---------------------------------------------------------------------------
+// Mock @vueuse/core — useStorage as a plain ref
+// ---------------------------------------------------------------------------
+vi.mock('@vueuse/core', () => ({
+ useStorage: (_key: string, defaultValue: any) => ref(defaultValue),
+}))
+
+// ---------------------------------------------------------------------------
+// Mock stores / composables used inside useStatItem
+// ---------------------------------------------------------------------------
+const getStoreTrnsIdsMock = vi.fn(({ trnsIds }: { trnsIds?: string[] }) => trnsIds ?? [])
+
+vi.mock('~/components/trns/useTrnsStore', () => ({
+ useTrnsStore: () => ({
+ getStoreTrnsIds: getStoreTrnsIdsMock,
+ items: {},
+ }),
+}))
+
+const computeTotalMock = vi.fn((): TotalReturns => ({
+ expense: 0,
+ income: 0,
+ sum: 0,
+ transfer: 0,
+}))
+
+vi.mock('~/components/amount/useAmount', () => ({
+ useAmount: () => ({
+ computeTotalForTrnsIds: computeTotalMock,
+ }),
+}))
+
+vi.mock('~/components/stat/chart/useStatChart', () => ({
+ useStatChart: () => ({
+ createSeriesItem: (type: string, _data: any[], _avg?: any) => ({
+ data: [],
+ name: type,
+ type: 'bar',
+ }),
+ withMarkArea: (series: any[]) => series,
+ }),
+}))
+
+const bucketTrnsByIntervalsMock = vi.fn(
+ (
+ _items: Record<string, unknown>,
+ trnsIds: string[],
+ intervals: Range[],
+ computeTotal: (ids: string[]) => TotalReturns,
+ ): IntervalData[] =>
+ intervals.map(range => ({
+ range,
+ total: computeTotal(trnsIds),
+ trnsIds,
+ })),
+)
+
+vi.mock('~/components/stat/intervals', async (importOriginal) => {
+ const actual = await importOriginal() as any
+ return {
+ ...actual,
+ bucketTrnsByIntervals: (...args: any[]) => bucketTrnsByIntervalsMock(...args),
+ }
+})
+
+// ---------------------------------------------------------------------------
+// Import after mocks
+// ---------------------------------------------------------------------------
+const { useStatItem } = await import('~/components/stat/useStatItem')
+
+// ---------------------------------------------------------------------------
+// Helpers to build mock params
+// ---------------------------------------------------------------------------
+function makeStatDate(overrides?: Partial<{
+ intervalsInRange: Range[]
+ params: Record<string, any>
+ range: Range
+ selectedInterval: Range
+}>) {
+ const defaults = {
+ intervalsInRange: [] as Range[],
+ params: {
+ intervalsBy: 'month' as const,
+ intervalSelected: -1,
+ rangeBy: 'year' as const,
+ rangeDuration: 1,
+ },
+ range: { end: Date.now(), start: Date.now() - 86400000 * 30 },
+ selectedInterval: undefined as Range | undefined,
+ }
+ const merged = { ...defaults, ...overrides }
+ return {
+ intervalsInRange: computed(() => merged.intervalsInRange),
+ params: computed(() => merged.params),
+ range: computed(() => merged.range),
+ selectedInterval: computed(() => merged.selectedInterval),
+ }
+}
+
+function makeFilter(categoriesIds: string[] = []) {
+ return {
+ categoriesIds: computed(() => categoriesIds),
+ clearFilter: vi.fn(),
+ isShow: computed(() => categoriesIds.length > 0),
+ }
+}
+
+function makeStatConfig() {
+ return {
+ config: computed(() => ({
+ chart: { isShowAverage: false },
+ chartType: 'bar' as const,
+ })),
+ }
+}
+
+function createStatItem(overrides?: {
+ filterCategories?: string[]
+ intervalSelected?: number
+ intervalsInRange?: Range[]
+ statTab?: 'summary' | 'expense' | 'income' | 'split'
+ trnsIds?: string[]
+ type?: 'income' | 'expense' | 'netIncome'
+}) {
+ const {
+ filterCategories = [],
+ intervalSelected = -1,
+ intervalsInRange = [],
+ statTab = 'summary',
+ trnsIds = [],
+ type,
+ } = overrides ?? {}
+
+ return useStatItem({
+ filter: makeFilter(filterCategories) as any,
+ statConfig: makeStatConfig() as any,
+ statDate: makeStatDate({
+ intervalsInRange,
+ params: {
+ intervalsBy: 'month',
+ intervalSelected,
+ rangeBy: 'year',
+ rangeDuration: 1,
+ },
+ }) as any,
+ statTab: computed(() => statTab),
+ storageKey: computed(() => 'test'),
+ trnsIds: computed(() => trnsIds),
+ type: computed(() => type),
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+describe('useStatItem', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ getStoreTrnsIdsMock.mockImplementation(({ trnsIds }: { trnsIds?: string[] }) => trnsIds ?? [])
+ })
+
+ // -------------------------------------------------------------------------
+ // hasCategoryFilter optimization
+ // -------------------------------------------------------------------------
+ describe('hasCategoryFilter optimization', () => {
+ it('reuses intervalsData when filteredCategoriesIds is empty', () => {
+ const intervals: Range[] = [
+ { end: 200, start: 100 },
+ { end: 400, start: 300 },
+ ]
+
+ const item = createStatItem({
+ intervalsInRange: intervals,
+ trnsIds: ['t1', 't2'],
+ })
+
+ // Access both computed values to trigger evaluation
+ const baseData = item.chartSeries.value
+ void baseData
+
+ // bucketTrnsByIntervals should be called only once because
+ // intervalsDataWithFilteredCategories reuses intervalsData
+ // when no category filter is active
+ expect(bucketTrnsByIntervalsMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('calls bucketTrnsByIntervals twice when category filter is active and both paths accessed', () => {
+ const intervals: Range[] = [
+ { end: 200, start: 100 },
+ ]
+
+ const item = createStatItem({
+ intervalSelected: 0,
+ intervalsInRange: intervals,
+ trnsIds: ['t1', 't2'],
+ })
+
+ // Set a category filter
+ item.filteredCategoriesIds.value = ['cat1']
+
+ // Access selectedTrnsIds to trigger intervalsData (via baseTrnsIdsForSelection with interval selected)
+ void item.selectedTrnsIds.value
+ // Access chartSeries to trigger intervalsDataWithFilteredCategories (separate call due to filter)
+ void item.chartSeries.value
+
+ // Should call bucket twice: once for intervalsData, once for filtered
+ expect(bucketTrnsByIntervalsMock).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // baseTrnsIdsForSelection
+ // -------------------------------------------------------------------------
+ describe('baseTrnsIdsForSelection', () => {
+ it('uses rangeTrnsIds when no interval is selected', () => {
+ const rangeTrnsIds = ['t1', 't2', 't3']
+
+ const item = createStatItem({
+ intervalSelected: -1,
+ trnsIds: rangeTrnsIds,
+ })
+
+ // selectedTrnsIds uses baseTrnsIdsForSelection internally
+ // When no interval selected, it should pass rangeTrnsIds
+ void item.selectedTrnsIds.value
+
+ // getStoreTrnsIds is called multiple times:
+ // 1. rangeTrnsIds computed
+ // 2. selectedTrnsIds computed (which uses baseTrnsIdsForSelection = rangeTrnsIds)
+ const selectedCall = getStoreTrnsIdsMock.mock.calls.find(
+ call => call[0].sort === true,
+ )
+ expect(selectedCall).toBeDefined()
+ expect(selectedCall![0].trnsIds).toEqual(rangeTrnsIds)
+ })
+
+ it('uses interval trnsIds when an interval is selected', () => {
+ const intervalTrnsIds = ['t2']
+ const intervals: Range[] = [
+ { end: 200, start: 100 },
+ ]
+
+ bucketTrnsByIntervalsMock.mockReturnValue([{
+ range: intervals[0],
+ total: { expense: 0, income: 0, sum: 0, transfer: 0 },
+ trnsIds: intervalTrnsIds,
+ }])
+
+ const item = createStatItem({
+ intervalSelected: 0,
+ intervalsInRange: intervals,
+ trnsIds: ['t1', 't2', 't3'],
+ })
+
+ void item.selectedTrnsIds.value
+
+ // The selectedTrnsIds call (with sort: true) should receive interval trnsIds
+ const selectedCall = getStoreTrnsIdsMock.mock.calls.find(
+ call => call[0].sort === true,
+ )
+ expect(selectedCall).toBeDefined()
+ expect(selectedCall![0].trnsIds).toEqual(intervalTrnsIds)
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // onClickSumItem
+ // -------------------------------------------------------------------------
+ describe('onClickSumItem', () => {
+ it('sets filteredType to the clicked type', () => {
+ const item = createStatItem()
+
+ // Default filteredType is 'netIncome'
+ expect(item.filteredType.value).toBe('netIncome')
+
+ item.onClickSumItem('expense')
+ expect(item.filteredType.value).toBe('expense')
+ })
+
+ it('toggles back to netIncome when clicking the same type', () => {
+ const item = createStatItem()
+
+ item.onClickSumItem('expense')
+ expect(item.filteredType.value).toBe('expense')
+
+ item.onClickSumItem('expense')
+ expect(item.filteredType.value).toBe('netIncome')
+ })
+
+ it('switches between types', () => {
+ const item = createStatItem()
+
+ item.onClickSumItem('income')
+ expect(item.filteredType.value).toBe('income')
+
+ item.onClickSumItem('expense')
+ expect(item.filteredType.value).toBe('expense')
+
+ item.onClickSumItem('expense')
+ expect(item.filteredType.value).toBe('netIncome')
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // onSetCategoryFilter
+ // -------------------------------------------------------------------------
+ describe('onSetCategoryFilter', () => {
+ it('sets the category filter when empty', () => {
+ const item = createStatItem()
+
+ expect(item.filteredCategoriesIds.value).toEqual([])
+
+ item.onSetCategoryFilter('cat1')
+ expect(item.filteredCategoriesIds.value).toEqual(['cat1'])
+ })
+
+ it('clears filter when the same category is clicked again', () => {
+ const item = createStatItem()
+
+ item.onSetCategoryFilter('cat1')
+ expect(item.filteredCategoriesIds.value).toEqual(['cat1'])
+
+ item.onSetCategoryFilter('cat1')
+ expect(item.filteredCategoriesIds.value).toEqual([])
+ })
+
+ it('replaces filter when a different category is clicked', () => {
+ const item = createStatItem()
+
+ item.onSetCategoryFilter('cat1')
+ expect(item.filteredCategoriesIds.value).toEqual(['cat1'])
+
+ item.onSetCategoryFilter('cat2')
+ expect(item.filteredCategoriesIds.value).toEqual(['cat2'])
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // selectedTypeForSum
+ // -------------------------------------------------------------------------
+ describe('selectedTypeForSum', () => {
+ it('returns summary for summary tab', () => {
+ const item = createStatItem({ statTab: 'summary' })
+ expect(item.selectedTypeForSum.value).toBe('summary')
+ })
+
+ it('returns statTab for expense tab', () => {
+ const item = createStatItem({ statTab: 'expense' })
+ expect(item.selectedTypeForSum.value).toBe('expense')
+ })
+
+ it('returns type for split tab', () => {
+ const item = createStatItem({ statTab: 'split', type: 'income' })
+ expect(item.selectedTypeForSum.value).toBe('income')
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // isPeriodOneDay
+ // -------------------------------------------------------------------------
+ describe('isPeriodOneDay', () => {
+ it('returns false for month range', () => {
+ const item = createStatItem()
+ expect(item.isPeriodOneDay.value).toBe(false)
+ })
+ })
+})
diff --git a/app/components/stat/useStatItem.ts b/app/components/stat/useStatItem.ts
index db876551..15044f9a 100644
--- a/app/components/stat/useStatItem.ts
+++ b/app/components/stat/useStatItem.ts
@@ -7,7 +7,7 @@ import type { TotalReturns } from '~/components/amount/getTotal'
import type { CategoryId } from '~/components/categories/types'
import type { StatDateProvider } from '~/components/date/types'
import type { FilterProvider } from '~/components/stat/filter/types'
-import type { ChartSeries, SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
+import type { ChartSeries, IntervalData, SeriesSlug, SeriesSlugSelected, StatTabSlug } from '~/components/stat/types'
import type { StatConfigProvider } from '~/components/stat/useStatConfig'
import type { TrnId } from '~/components/trns/types'
@@ -38,14 +38,14 @@ export function useStatItem({
}: UseStatItemParams) {
const trnsStore = useTrnsStore()
const { computeTotalForTrnsIds } = useAmount()
- const { addMarkArea, createSeriesItem } = useStatChart()
+ const { createSeriesItem, withMarkArea } = useStatChart()
- const newBaseStorageKey = computed(() =>
+ const statItemStorageKey = computed(() =>
`finapp-${statDate.params.value.intervalsBy}-${storageKey.value}-${(filter?.categoriesIds?.value ?? []).join(',')}`,
)
const filteredType = useStorage<SeriesSlugSelected>(
- `finapp-filtered-type-${type.value}-${newBaseStorageKey.value}`,
+ `finapp-filtered-type-${type.value}-${statItemStorageKey.value}`,
'netIncome',
)
@@ -62,33 +62,43 @@ export function useStatItem({
trnsIds: trnsIds.value,
}))
- const rangeTrnsIdsWithFilteredCategories = computed(() => trnsStore.getStoreTrnsIds({
- categoriesIds: filteredCategoriesIds.value,
- trnsIds: trnsIds.value,
- }))
+ const hasCategoryFilter = computed(() => filteredCategoriesIds.value.length > 0)
+
+ const rangeTrnsIdsWithFilteredCategories = computed(() => {
+ if (!hasCategoryFilter.value)
+ return rangeTrnsIds.value
+ return trnsStore.getStoreTrnsIds({
+ categoriesIds: filteredCategoriesIds.value,
+ trnsIds: trnsIds.value,
+ })
+ })
const intervalsData = computed(() =>
bucketTrnsByIntervals(trnsStore.items ?? {}, rangeTrnsIds.value, statDate.intervalsInRange.value, computeTotalForTrnsIds),
)
- const intervalsDataWithFilteredCategories = computed(() =>
- bucketTrnsByIntervals(trnsStore.items ?? {}, rangeTrnsIdsWithFilteredCategories.value, statDate.intervalsInRange.value, computeTotalForTrnsIds),
+ const intervalsDataWithFilteredCategories = computed(() => {
+ if (!hasCategoryFilter.value)
+ return intervalsData.value
+ return bucketTrnsByIntervals(trnsStore.items ?? {}, rangeTrnsIdsWithFilteredCategories.value, statDate.intervalsInRange.value, computeTotalForTrnsIds)
+ })
+
+ const baseTrnsIdsForSelection = computed(() =>
+ isIntervalSelected.value
+ ? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds
+ : rangeTrnsIds.value,
)
const selectedTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
sort: true,
- trnsIds: isIntervalSelected.value
- ? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds
- : rangeTrnsIds.value,
+ trnsIds: baseTrnsIdsForSelection.value,
trnsTypes: selectedTypesMapping.value,
}))
const selectedAndFilteredTrnsIds = computed(() => trnsStore.getStoreTrnsIds({
categoriesIds: filteredCategoriesIds.value,
sort: true,
- trnsIds: isIntervalSelected.value
- ? intervalsData.value[statDate.params.value.intervalSelected]?.trnsIds
- : rangeTrnsIds.value,
+ trnsIds: baseTrnsIdsForSelection.value,
trnsTypes: selectedTypesMapping.value,
}))
@@ -103,7 +113,8 @@ export function useStatItem({
if (differenceInDays(statDate.range.value.end, statDate.range.value.start) < 2)
return
- const sum = filteredType.value === 'netIncome' ? rangeTotal.value.sum : rangeTotal.value[type.value as keyof TotalReturns] as number
+ const key = filteredType.value === 'netIncome' ? 'sum' : (type.value ?? 'sum')
+ const sum = rangeTotal.value[key as keyof TotalReturns] as number ?? 0
const dateRange = isIntervalSelected.value
? statDate.selectedInterval.value
@@ -114,23 +125,25 @@ export function useStatItem({
const typesToShow = computed(() => getTypesToShow(statTab.value, filteredType.value, type.value))
+ function computeSeriesAverage(typeSlug: SeriesSlug, intervals: IntervalData[]): number | false {
+ if (!statConfig.config.value.chart.isShowAverage || intervals.length === 0)
+ return false
+ return intervals.reduce((acc, i) => acc + i.total[typeSlug], 0) / intervals.length
+ }
+
const chartSeries = computed<ChartSeries[]>(() => {
- const intervalTotals = intervalsDataWithFilteredCategories.value.map(g => g.total)
+ const intervals = intervalsDataWithFilteredCategories.value
+ const intervalTotals = intervals.map(g => g.total)
+
const baseSeries = typesToShow.value.map(t =>
- createSeriesItem(
- t,
- intervalTotals,
- statConfig.config.value.chart.isShowAverage
- ? intervalsDataWithFilteredCategories.value.reduce((acc, i) => acc + i.total[t], 0) / intervalsData.value.length
- : false,
- ),
+ createSeriesItem(t, intervalTotals, computeSeriesAverage(t, intervals)),
)
- const selectedInterval = intervalsDataWithFilteredCategories.value?.[statDate.params.value.intervalSelected]
+ const selectedInterval = intervals[statDate.params.value.intervalSelected]
if (!selectedInterval?.range.start || statDate.params.value.intervalSelected < 0)
return baseSeries
- return addMarkArea(baseSeries, selectedInterval.range.start, statConfig.config.value?.chartType)
+ return withMarkArea(baseSeries, selectedInterval.range.start, statConfig.config.value?.chartType)
})
const chartXAxisLabels = computed(() =>
@@ -156,12 +169,12 @@ export function useStatItem({
filteredCategoriesIds,
filteredType,
isPeriodOneDay,
- newBaseStorageKey,
onClickSumItem,
onSetCategoryFilter,
rangeTotal,
selectedAndFilteredTrnsIds,
selectedTrnsIds,
selectedTypeForSum,
+ statItemStorageKey,
}
}
diff --git a/app/components/trns/types.ts b/app/components/trns/types.ts
index 2a0b74bd..90905c20 100644
--- a/app/components/trns/types.ts
+++ b/app/components/trns/types.ts
@@ -11,6 +11,10 @@ export enum TrnType {
export type TrnId = string
+export function getTrnTypeByAmount(amount: number): TrnType {
+ return amount > 0 ? TrnType.Income : TrnType.Expense
+}
+
export type TrnsViewType = 'adjustment' | 'all' | 'expense' | 'income' | 'transfer'
export type TransferSide = 'expense' | 'income'