add trends analysis chart

This commit is contained in:
MaysWind
2024-06-09 02:31:13 +08:00
parent 1489854444
commit e88d803232
7 changed files with 496 additions and 13 deletions
+293
View File
@@ -0,0 +1,293 @@
<template>
<v-chart autoresize class="trends-chart-container" :class="{ 'transition-in': skeleton }" :option="chartOptions"
@click="clickItem" />
</template>
<script>
import { useTheme } from 'vuetify';
import { mapStores } from 'pinia';
import { useSettingsStore } from '@/stores/setting.js';
import { useUserStore } from '@/stores/user.js';
import colorConstants from '@/consts/color.js';
import statisticsConstants from '@/consts/statistics.js';
import { isNumber } from '@/lib/common.js';
import {
getYearMonthStringFromObject,
getAllYearMonthUnixTimesBetweenStartYearMonthAndEndYearMonth
} from '@/lib/datetime.js';
export default {
props: [
'skeleton',
'type',
'items',
'startYearMonth',
'endYearMonth',
'idField',
'nameField',
'valueField',
'currencyField',
'colorField',
'hiddenField',
'defaultCurrency',
'showValue',
'enableClickItem'
],
emits: [
'click'
],
data() {
return {
selectedLegends: null
};
},
computed: {
...mapStores(useSettingsStore, useUserStore),
isDarkMode() {
return this.globalTheme.global.name.value === 'dark';
},
itemsMap: function () {
const map = {};
for (let i = 0; i < this.items.length; i++) {
const item = this.items[i];
let id = '';
if (this.idField && item[this.idField]) {
id = item[this.idField];
} else {
id = item[this.nameField];
}
map[id] = item;
}
return map;
},
allYearMonthTimes: function () {
if (this.startYearMonth && this.endYearMonth) {
return getAllYearMonthUnixTimesBetweenStartYearMonthAndEndYearMonth(this.startYearMonth, this.endYearMonth);
} else if (this.items && this.items.length) {
let minYear = Number.MAX_SAFE_INTEGER, minMonth = Number.MAX_SAFE_INTEGER, maxYear = 0, maxMonth = 0;
for (let i = 0; i < this.items.length; i++) {
const item = this.items[i];
for (let j = 0; j < item.items.length; j++) {
const dataItem = item.items[j];
if (dataItem.year < minYear || (dataItem.year === minYear && dataItem.month < minMonth)) {
minYear = dataItem.year;
minMonth = dataItem.month;
}
if (dataItem.year > maxYear || (dataItem.year === maxYear && dataItem.month > maxMonth)) {
maxYear = dataItem.year;
maxMonth = dataItem.month;
}
}
}
return getAllYearMonthUnixTimesBetweenStartYearMonthAndEndYearMonth(`${minYear}-${minMonth}`, `${maxYear}-${maxMonth}`);
}
return [];
},
allDisplayMonths: function () {
const allDisplayMonths = [];
for (let i = 0; i < this.allYearMonthTimes.length; i++) {
const yearMonthTime = this.allYearMonthTimes[i];
allDisplayMonths.push(this.$locale.formatUnixTimeToShortYearMonth(this.userStore, yearMonthTime.minUnixTime));
}
return allDisplayMonths;
},
allSeries: function () {
const allSeries = [];
for (let i = 0; i < this.items.length; i++) {
const item = this.items[i];
if (!this.hiddenField || item[this.hiddenField]) {
continue;
}
const allAmounts = [];
const yearMonthDataMap = {};
for (let j = 0; j < item.items.length; j++) {
const dataItem = item.items[j];
yearMonthDataMap[`${dataItem.year}-${dataItem.month}`] = dataItem;
}
for (let j = 0; j < this.allYearMonthTimes.length; j++) {
const yearMonth = getYearMonthStringFromObject(this.allYearMonthTimes[j]);
const dataItem = yearMonthDataMap[yearMonth];
let amount = 0;
if (dataItem && isNumber(dataItem[this.valueField])) {
amount = dataItem[this.valueField];
}
allAmounts.push(amount);
}
const finalItem = {
id: (this.idField && item[this.idField]) ? item[this.idField] : item[this.nameField],
name: (this.idField && item[this.idField]) ? item[this.idField] : item[this.nameField],
currency: item[this.currencyField],
itemStyle: {
color: this.getColor(item[this.colorField] ? item[this.colorField] : colorConstants.defaultChartColors[i % colorConstants.defaultChartColors.length]),
},
selected: true,
type: 'line',
stack: 'a',
animation: !self.skeleton,
data: allAmounts
};
if (this.type === statisticsConstants.allTrendChartTypes.Area) {
finalItem.areaStyle = {};
} else if (this.type === statisticsConstants.allTrendChartTypes.Column) {
finalItem.type = 'bar';
}
allSeries.push(finalItem);
}
return allSeries;
},
chartOptions: function () {
const self = this;
return {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: self.isDarkMode ? '#333' : '#fff',
color: self.isDarkMode ? '#eee' : '#333'
},
},
backgroundColor: self.isDarkMode ? '#333' : '#fff',
borderColor: self.isDarkMode ? '#333' : '#fff',
textStyle: {
color: self.isDarkMode ? '#eee' : '#333'
},
formatter: params => {
let tooltip = '';
if (params.length && params[0].name) {
tooltip += `${params[0].name}<br/>`;
}
for (let i = 0; i < params.length; i++) {
const id = params[i].seriesId;
const name = self.itemsMap[id] && self.nameField && self.itemsMap[id][self.nameField] ? self.itemsMap[id][self.nameField] : id;
if (params[i].data !== 0) {
const currency = self.itemsMap[id] && self.currencyField && self.itemsMap[id][self.currencyField] ? self.itemsMap[id][self.currencyField] : self.defaultCurrency;
const value = self.getDisplayCurrency(params[i].data, currency);
tooltip += '<div><span class="chart-pointer" style="background-color: ' + params[i].color + '"></span>';
tooltip += `<span>${name}</span><span style="margin-left: 20px; float: right">${value}</span><br/>`;
tooltip += '</div>';
}
}
return tooltip;
}
},
legend: {
orient: 'horizontal',
data: self.allSeries.map(item => item.name),
selected: self.selectedLegends,
textStyle: {
color: self.isDarkMode ? '#eee' : '#333'
},
formatter: id => {
return self.itemsMap[id] && self.nameField && self.itemsMap[id][self.nameField] ? self.itemsMap[id][self.nameField] : id;
}
},
xAxis: [
{
type: 'category',
data: self.allDisplayMonths
}
],
yAxis: [
{
type: 'value',
axisLabel: {
formatter: function (value) {
return self.getDisplayCurrency(value, self.defaultCurrency);
}
},
axisPointer: {
label: {
formatter: function (params) {
return self.getDisplayCurrency(parseInt(params.value), self.defaultCurrency);
}
}
}
}
],
series: self.allSeries
}
}
},
setup() {
const theme = useTheme();
return {
globalTheme: theme
};
},
methods: {
clickItem: function (e) {
if (!this.enableClickItem || e.componentType !== 'series') {
return;
}
const id = e.seriesId;
const item = this.itemsMap[id];
const yearMonthTime = this.allYearMonthTimes[e.dataIndex];
this.$emit('click', {
yearMonth: getYearMonthStringFromObject(yearMonthTime),
item: item
});
},
getColor: function (color) {
if (color && color !== colorConstants.defaultColor) {
color = '#' + color;
}
return color;
},
getDisplayCurrency(value, currencyCode) {
return this.$locale.getDisplayCurrency(value, currencyCode, {
currencyDisplayMode: this.settingsStore.appSettings.currencyDisplayMode,
enableThousandsSeparator: this.settingsStore.appSettings.thousandsSeparator
});
}
}
}
</script>
<style scoped>
.trends-chart-container {
width: 100%;
height: 500px;
margin-top: 10px;
}
@media (min-width: 600px) {
.pie-chart-container {
height: 500px;
}
}
</style>
+1 -1
View File
@@ -39,7 +39,7 @@ const allTrendChartTypesArray = [
}
];
const defaultTrendChartType = allTrendChartTypes.Area;
const defaultTrendChartType = allTrendChartTypes.Column;
const allChartDataTypes = {
ExpenseByAccount: {
+4 -1
View File
@@ -50,7 +50,7 @@ import 'vuetify/styles';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, PieChart } from 'echarts/charts';
import { LineChart, BarChart, PieChart } from 'echarts/charts';
import {
GridComponent,
TooltipComponent,
@@ -92,6 +92,7 @@ import StepsBar from '@/components/desktop/StepsBar.vue';
import ConfirmDialog from '@/components/desktop/ConfirmDialog.vue';
import SnackBar from '@/components/desktop/SnackBar.vue';
import PieChartComponent from '@/components/desktop/PieChart.vue';
import TrendsChartComponent from '@/components/desktop/TrendsChart.vue';
import DateRangeSelectionDialog from '@/components/desktop/DateRangeSelectionDialog.vue';
import MonthRangeSelectionDialog from '@/components/desktop/MonthRangeSelectionDialog.vue';
import SwitchToMobileDialog from '@/components/desktop/SwitchToMobileDialog.vue';
@@ -422,6 +423,7 @@ const vuetify = createVuetify({
echarts.use([
CanvasRenderer,
LineChart,
BarChart,
PieChart,
GridComponent,
@@ -453,6 +455,7 @@ app.component('StepsBar', StepsBar);
app.component('ConfirmDialog', ConfirmDialog);
app.component('SnackBar', SnackBar);
app.component('PieChart', PieChartComponent);
app.component('TrendsChart', TrendsChartComponent);
app.component('DateRangeSelectionDialog', DateRangeSelectionDialog);
app.component('MonthRangeSelectionDialog', MonthRangeSelectionDialog);
app.component('SwitchToMobileDialog', SwitchToMobileDialog);
+37
View File
@@ -328,6 +328,43 @@ export function getYearMonthLastUnixTime(yearMonth) {
return moment.unix(getYearMonthFirstUnixTime(yearMonth)).add(1, 'months').subtract(1, 'seconds').unix();
}
export function getAllYearMonthUnixTimesBetweenStartYearMonthAndEndYearMonth(startYearMonth, endYearMonth) {
if (isString(startYearMonth)) {
startYearMonth = getYearMonthObjectFromString(startYearMonth);
}
if (isString(endYearMonth)) {
endYearMonth = getYearMonthObjectFromString(endYearMonth);
}
const allYearMonthTimes = [];
for (let year = startYearMonth.year, month = startYearMonth.month; year <= endYearMonth.year || month <= endYearMonth.month; ) {
const yearMonthTime = {
year: year,
month: month
};
yearMonthTime.minUnixTime = getYearMonthFirstUnixTime(yearMonthTime);
yearMonthTime.maxUnixTime = getYearMonthLastUnixTime(yearMonthTime);
allYearMonthTimes.push(yearMonthTime);
if (year === endYearMonth.year && month === endYearMonth.month) {
break;
}
if (month >= 11) {
year++;
month = 0;
} else {
month++;
}
}
return allYearMonthTimes;
}
export function getDateTimeFormatType(allFormatMap, allFormatArray, localeDefaultFormatTypeName, systemDefaultFormatType, formatTypeValue) {
if (formatTypeValue > dateTimeConstants.defaultDateTimeFormatValue && allFormatArray[formatTypeValue - 1] && allFormatArray[formatTypeValue - 1].key) {
return allFormatArray[formatTypeValue - 1];
+96 -4
View File
@@ -422,6 +422,95 @@ export const useStatisticsStore = defineStore('statistics', {
totalAmount: combinedData.totalAmount,
items: allStatisticsItems
};
},
transactionCategoryTrendsDataWithCategoryAndAccountInfo(state) {
const trendsData = state.transactionCategoryTrendsData;
const finalTrendsData = [];
if (trendsData && trendsData.length) {
const userStore = useUserStore();
const accountsStore = useAccountsStore();
const transactionCategoriesStore = useTransactionCategoriesStore();
const exchangeRatesStore = useExchangeRatesStore();
for (let i = 0; i < trendsData.length; i++) {
const trendItem = trendsData[i];
const finalTrendItem = {
year: trendItem.year,
month: trendItem.month,
items: []
};
if (trendItem && trendItem.items && trendItem.items.length) {
finalTrendItem.items = assembleAccountAndCategoryInfo(userStore, accountsStore, transactionCategoriesStore, exchangeRatesStore, trendItem.items);
}
finalTrendsData.push(finalTrendItem);
}
}
return finalTrendsData;
},
trendsAnalysisData(state) {
if (!state.transactionCategoryTrendsDataWithCategoryAndAccountInfo || !state.transactionCategoryTrendsDataWithCategoryAndAccountInfo.length) {
return null;
}
const combinedDataMap = {};
for (let i = 0; i < state.transactionCategoryTrendsDataWithCategoryAndAccountInfo.length; i++) {
const trendItem = state.transactionCategoryTrendsDataWithCategoryAndAccountInfo[i];
const totalAmountItems = getCategoryTotalAmountItems(trendItem.items, state.transactionStatisticsFilter);
for (let id in totalAmountItems.items) {
if (!Object.prototype.hasOwnProperty.call(totalAmountItems.items, id)) {
continue;
}
const item = totalAmountItems.items[id];
let combinedData = combinedDataMap[id];
if (!combinedData) {
combinedData = {
name: item.name,
type: item.type,
id: item.id,
icon: item.icon,
color: item.color,
hidden: item.hidden,
displayOrders: item.displayOrders,
totalAmount: 0,
items: []
};
}
combinedData.items.push({
year: trendItem.year,
month: trendItem.month,
totalAmount: item.totalAmount
});
combinedData.totalAmount += item.totalAmount;
combinedDataMap[id] = combinedData;
}
}
const totalAmountsTrends = [];
for (let id in combinedDataMap) {
if (!Object.prototype.hasOwnProperty.call(combinedDataMap, id)) {
continue;
}
const trendData = combinedDataMap[id];
totalAmountsTrends.push(trendData);
}
sortCategoryTotalAmountItems(totalAmountsTrends, state.transactionStatisticsFilter);
return {
items: totalAmountsTrends
};
}
},
actions: {
@@ -625,7 +714,7 @@ export const useStatisticsStore = defineStore('statistics', {
this.transactionStatisticsFilter.sortingType = filter.sortingType;
}
},
getTransactionListPageParams(item) {
getTransactionListPageParams(analysisType, item, dateRange) {
const querys = [];
if (this.transactionStatisticsFilter.chartDataType === statisticsConstants.allChartDataTypes.IncomeByAccount.type
@@ -650,7 +739,8 @@ export const useStatisticsStore = defineStore('statistics', {
querys.push('categoryId=' + item.id);
}
if (this.transactionStatisticsFilter.chartDataType !== statisticsConstants.allChartDataTypes.AccountTotalAssets.type
if (analysisType === statisticsConstants.allAnalysisTypes.CategoricalAnalysis
&& this.transactionStatisticsFilter.chartDataType !== statisticsConstants.allChartDataTypes.AccountTotalAssets.type
&& this.transactionStatisticsFilter.chartDataType !== statisticsConstants.allChartDataTypes.AccountTotalLiabilities.type) {
querys.push('dateType=' + this.transactionStatisticsFilter.categoricalChartDateType);
@@ -658,6 +748,10 @@ export const useStatisticsStore = defineStore('statistics', {
querys.push('minTime=' + this.transactionStatisticsFilter.categoricalChartStartTime);
querys.push('maxTime=' + this.transactionStatisticsFilter.categoricalChartEndTime);
}
} else if (analysisType === statisticsConstants.allAnalysisTypes.TrendAnalysis && dateRange) {
querys.push('dateType=' + dateRange.type);
querys.push('minTime=' + dateRange.minTime);
querys.push('maxTime=' + dateRange.maxTime);
}
return querys.join('&');
@@ -709,8 +803,6 @@ export const useStatisticsStore = defineStore('statistics', {
const settingsStore = useSettingsStore();
return new Promise((resolve, reject) => {
resolve(true);
services.getTransactionStatisticsTrends({
startYearMonth: self.transactionStatisticsFilter.trendChartStartYearMonth,
endYearMonth: self.transactionStatisticsFilter.trendChartEndYearMonth,
@@ -131,7 +131,8 @@
</v-card-text>
<v-card-text class="statistics-overview-title pt-0"
v-else-if="!initing && (analysisType === allAnalysisTypes.CategoricalAnalysis && !categoricalAnalysisData || !categoricalAnalysisData.items || !categoricalAnalysisData.items.length)">
v-else-if="!initing && ((analysisType === allAnalysisTypes.CategoricalAnalysis && (!categoricalAnalysisData || !categoricalAnalysisData.items || !categoricalAnalysisData.items.length))
|| (analysisType === allAnalysisTypes.TrendAnalysis && (!trendsAnalysisData || !trendsAnalysisData.items || !trendsAnalysisData.items.length)))">
<span class="statistics-subtitle statistics-overview-empty-tip">{{ $t('No transaction data') }}</span>
</v-card-text>
@@ -220,6 +221,37 @@
</template>
</v-list>
</v-card-text>
<v-card-text :class="{ 'readonly': loading }" v-if="analysisType === allAnalysisTypes.TrendAnalysis">
<trends-chart
:type="queryChartType"
:start-year-month="query.trendChartStartYearMonth"
:end-year-month="query.trendChartEndYearMonth"
:items="[]"
:skeleton="true"
id-field="id"
name-field="name"
value-field="value"
color-field="color"
v-if="initing"
></trends-chart>
<trends-chart
:type="queryChartType"
:start-year-month="query.trendChartStartYearMonth"
:end-year-month="query.trendChartEndYearMonth"
:items="trendsAnalysisData && trendsAnalysisData.items && trendsAnalysisData.items.length ? trendsAnalysisData.items : []"
:show-value="showAmountInChart"
:enable-click-item="true"
:default-currency="defaultCurrency"
id-field="id"
name-field="name"
value-field="totalAmount"
currency-field="currency"
hidden-field="hidden"
v-else-if="!initing"
@click="clickTrendChartItem"
/>
</v-card-text>
</v-card>
</v-window-item>
</v-window>
@@ -446,6 +478,9 @@ export default {
categoricalAnalysisData() {
return this.statisticsStore.categoricalAnalysisData;
},
trendsAnalysisData() {
return this.statisticsStore.trendsAnalysisData;
},
statisticsTextColor() {
if (this.query.chartDataType === this.allChartDataTypes.ExpenseByAccount.type ||
this.query.chartDataType === this.allChartDataTypes.ExpenseByPrimaryCategory.type ||
@@ -470,11 +505,21 @@ export default {
},
watch: {
'analysisType': function (newValue) {
if (!isChartDataTypeAvailableForAnalysisType(this.query.chartDataType, newValue)) {
this.query.chartDataType = statisticsConstants.defaultChartDataType;
const self = this;
if (!isChartDataTypeAvailableForAnalysisType(self.query.chartDataType, newValue)) {
self.query.chartDataType = statisticsConstants.defaultChartDataType;
}
this.reload(null);
self.initing = true;
const promise = self.reload(null);
if (promise) {
promise.then(() => {
self.initing = false;
});
}
},
'query.chartDataType': function (newValue) {
this.statisticsStore.updateTransactionStatisticsFilter({
@@ -572,6 +617,8 @@ export default {
}
});
}
return dispatchPromise;
},
setChartType(chartType) {
if (this.analysisType === statisticsConstants.allAnalysisTypes.CategoricalAnalysis) {
@@ -736,6 +783,17 @@ export default {
clickPieChartItem(item) {
this.$router.push(this.getItemLinkUrl(item));
},
clickTrendChartItem(item) {
const minUnixTime = getYearMonthFirstUnixTime(item.yearMonth);
const maxUnixTime = getYearMonthLastUnixTime(item.yearMonth);
const dateRangeType = getDateTypeByDateRange(minUnixTime, maxUnixTime, this.firstDayOfWeek, datetimeConstants.allDateRangeScenes.Normal);
this.$router.push(this.getItemLinkUrl(item.item, {
minTime: minUnixTime,
maxTime: maxUnixTime,
type: dateRangeType,
}));
},
getDisplayAmount(amount, currency, textLimit) {
amount = this.getDisplayCurrency(amount, currency);
@@ -761,8 +819,8 @@ export default {
getDisplayPercent(value, precision, lowPrecisionValue) {
return formatPercent(value, precision, lowPrecisionValue);
},
getItemLinkUrl(item) {
return `/transaction/list?${this.statisticsStore.getTransactionListPageParams(item)}`;
getItemLinkUrl(item, dateRange) {
return `/transaction/list?${this.statisticsStore.getTransactionListPageParams(this.analysisType, item, dateRange)}`;
}
}
}
@@ -569,7 +569,7 @@ export default {
return formatPercent(value, precision, lowPrecisionValue);
},
getItemLinkUrl(item) {
return `/transaction/list?${this.statisticsStore.getTransactionListPageParams(item)}`;
return `/transaction/list?${this.statisticsStore.getTransactionListPageParams(statisticsConstants.allAnalysisTypes.CategoricalAnalysis, item)}`;
}
}
};