feat: Implement dedicated dashboard service and data models, revamp upcoming transactions UI, and update dashboard charts to use new category data.

This commit is contained in:
xds
2025-11-21 19:11:36 +03:00
parent d969551491
commit f3286d2f4c
10 changed files with 385 additions and 199 deletions

View File

@@ -181,6 +181,12 @@ body {
box-shadow: 0 2px 8px var(--shadow-color);
border-radius: 1rem;
}
.p-button-rounded{
background-color: white !important;
}
.p-button-rounded:hover{
background-color: lightgray !important;
}
.p-menu .p-menuitem:hover {
background-color: var(--menu-item-hover-bg-color) !important;

View File

@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import Chart from 'primevue/chart';
import { DashboardCategory } from '@/models/dashboard';
import { Transaction } from '@/models/transaction';
import { TransactionType } from '@/models/enums';
import { formatAmount } from '@/utils/utils';
@@ -10,30 +11,29 @@ import isoWeek from 'dayjs/plugin/isoWeek';
dayjs.extend(isoWeek);
const props = defineProps<{
categories: DashboardCategory[];
transactions: Transaction[];
}>();
const chartType = ref<'category' | 'weekly'>('category');
const expenses = computed(() => props.transactions.filter(t => t.type === TransactionType.EXPENSE));
const expenses = computed(() => props.categories.filter(c => c.category.type === TransactionType.EXPENSE));
// --- Category Chart Logic ---
const categoryData = computed(() => {
const categoryMap = new Map<string, number>();
expenses.value.forEach(t => {
const categoryName = t.category?.name || 'Uncategorized';
const currentAmount = categoryMap.get(categoryName) || 0;
categoryMap.set(categoryName, currentAmount + t.amount);
});
return Array.from(categoryMap.entries())
.map(([name, amount]) => ({ name, amount }))
return expenses.value
.map(c => ({
name: c.category.name,
amount: c.currentPeriodAmount,
currentPeriodAmount: c.currentPeriodAmount,
previousPeriodAmount: c.previousPeriodAmount,
changeDiffPercentage: c.changeDiffPercentage
}))
.sort((a, b) => b.amount - a.amount);
});
const totalExpenseAmount = computed(() => {
return expenses.value.reduce((sum, t) => sum + t.amount, 0);
return expenses.value.reduce((sum, c) => sum + c.currentPeriodAmount, 0);
});
const topCategories = computed(() => {
@@ -107,7 +107,10 @@ const weeklyData = computed(() => {
});
}
expenses.value.forEach(t => {
// Filter expense transactions from the transactions prop
const expenseTransactions = props.transactions;
expenseTransactions.forEach(t => {
const tDate = dayjs(t.date);
const week = weeks.find(w => tDate.isAfter(w.start.subtract(1, 'second')) && tDate.isBefore(w.end.add(1, 'second')));
if (week) {
@@ -163,76 +166,100 @@ const weeklyChartOptions = computed(() => {
</script>
<template>
<div class="flex flex-col gap-6">
<!-- Chart Switcher -->
<div class="flex justify-center">
<div class="bg-surface-100 dark:bg-surface-800 p-1 rounded-lg inline-flex">
<button @click="chartType = 'category'"
class="px-4 py-1.5 rounded-md text-sm font-medium transition-all duration-200"
:class="chartType === 'category' ? 'bg-white dark:bg-surface-700 shadow-sm text-primary-600 dark:text-primary-400' : 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-surface-200'">
By Category
</button>
<button @click="chartType = 'weekly'"
class="px-4 py-1.5 rounded-md text-sm font-medium transition-all duration-200"
:class="chartType === 'weekly' ? 'bg-white dark:bg-surface-700 shadow-sm text-primary-600 dark:text-primary-400' : 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-surface-200'">
Last 4 Weeks
</button>
</div>
</div>
<div class="flex flex-col gap-1">
<span class="text-xl !font-semibold pl-1">Expences by category </span>
<div class="flex flex-col md:flex-row items-start gap-8">
<!-- Chart Area -->
<div class="w-full md:w-1/2 flex justify-center h-[250px] items-center top-4">
<Chart v-if="chartType === 'category'" type="doughnut" :data="categoryChartData" :options="categoryChartOptions"
class="w-full max-w-[250px]" />
<Chart v-else type="bar" :data="weeklyChartData" :options="weeklyChartOptions" class="w-full h-full" />
</div>
<div
class="bg-surface-0 dark:bg-surface-900 p-4 rounded-xl shadow-sm border border-surface-200 dark:border-surface-700">
<div class="flex flex-col gap-6">
<!-- Legend / Details Area -->
<div class="w-full md:w-1/2 flex flex-col gap-3 max-h-[400px] overflow-y-auto pr-2 custom-scrollbar">
<template v-if="chartType === 'category'">
<div v-for="(category, index) in topCategories" :key="category.name"
class="flex items-center justify-between p-2 rounded-lg hover:bg-surface-50 dark:hover:bg-surface-800 transition-colors">
<div class="flex items-center gap-3">
<div class="w-3 h-3 rounded-full" :class="getCategoryColor(index)"></div>
<span class="font-medium text-surface-700 dark:text-surface-200">{{ category.name }}</span>
</div>
<div class="flex items-center gap-3">
<span class="font-semibold text-surface-900 dark:text-surface-0">{{ formatAmount(category.amount) }}
</span>
<span class="text-sm text-surface-500 dark:text-surface-400 w-10 text-right">{{ category.percentage
}}%</span>
</div>
<!-- Chart Switcher -->
<div class="flex justify-center">
<div class="bg-surface-100 dark:bg-surface-800 p-1 rounded-lg inline-flex">
<button @click="chartType = 'category'"
class="px-4 py-1.5 rounded-md text-sm font-medium transition-all duration-200"
:class="chartType === 'category' ? 'bg-white dark:bg-surface-700 shadow-sm !text-primary-600 !dark:text-primary-400' : 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-surface-200'">
By Category
</button>
<button @click="chartType = 'weekly'"
class="px-4 py-1.5 rounded-md text-sm font-medium transition-all duration-200"
:class="chartType === 'weekly' ? 'bg-white dark:bg-surface-700 shadow-sm !text-primary-600 !dark:text-primary-400' : 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-surface-200'">
Last 4 Weeks
</button>
</div>
</template>
</div>
<template v-else>
<div class="flex flex-col gap-4">
<div v-for="week in weeklyData" :key="week.label" class="flex flex-col gap-2">
<div class="flex items-center justify-between p-2 bg-surface-50 dark:bg-surface-800 rounded-lg">
<span class="font-medium text-surface-700 dark:text-surface-200">{{ week.label }}</span>
<span class="font-semibold text-surface-900 dark:text-surface-0">{{ formatAmount(week.amount) }}
</span>
</div>
<div class="flex flex-col md:flex-row items-start gap-8">
<!-- Chart Area -->
<div class="w-full md:w-1/2 flex justify-center h-[250px] items-center top-4">
<Chart v-if="chartType === 'category'" type="doughnut" :data="categoryChartData"
:options="categoryChartOptions" class="w-full max-w-[250px]" />
<Chart v-else type="bar" :data="weeklyChartData" :options="weeklyChartOptions" class="w-full h-full" />
</div>
<!-- Legend / Details Area -->
<div class="w-full md:w-1/2 flex flex-col gap-3 max-h-[400px] overflow-y-auto pr-2 custom-scrollbar">
<template v-if="chartType === 'category'">
<div v-for="(category, index) in topCategories" :key="category.name"
class="flex items-center justify-between p-2 rounded-lg hover:bg-surface-50 dark:hover:bg-surface-800 transition-colors">
<div class="flex items-center gap-3">
<div class="w-3 h-3 rounded-full" :class="getCategoryColor(index)"></div>
<span class="font-medium text-surface-700 dark:text-surface-200">{{ category.name }}</span>
</div>
<div class="flex items-center gap-3">
<div class="flex items-center font-semibold gap-1 text-surface-900 dark:text-surface-0">
<div class="flex items-center gap-0">
<span>{{ formatAmount(category.amount) }}</span>
<span class="ml-0.5"></span>
</div>
<span class="text-xs text-surface-500 dark:text-surface-400 ml-1"> ({{
formatAmount(category.previousPeriodAmount) }})</span>
</div>
<div class="flex items-center text-sm gap-1 text-surface-500 dark:text-surface-400 w-10 text-right">
<div class="flex items-center gap-0">
<span>{{ category.percentage }}</span>
<span class="ml-0.5">%</span>
</div>
<span class="text-xs text-surface-500 dark:text-surface-400 ml-1"> ({{
category.changeDiffPercentage > 0 ? '+' : category.changeDiffPercentage < 0 ? '-' : '' +
Math.round(category.changeDiffPercentage) }})</span>
<!-- Transactions List -->
<div class="flex flex-col gap-1 pl-2 border-l-2 border-surface-100 dark:border-surface-700 ml-2 h-fit">
<div v-for="tx in week.transactions.slice(0, 5)" :key="tx.id"
class="flex items-center justify-between py-1 px-2 text-sm hover:bg-surface-50 dark:hover:bg-surface-800 rounded transition-colors">
<div class="flex items-center gap-2 overflow-hidden">
<span class="text-lg">{{ tx.category.icon }}</span>
<span class="text-surface-600 dark:text-surface-300 truncate">{{ tx.category.name }}</span>
</div>
<span class="font-medium text-surface-900 dark:text-surface-100 whitespace-nowrap">{{
formatAmount(tx.amount) }} </span>
</div>
<div v-if="week.transactions.length > 5" class="text-xs text-surface-400 pl-2 pt-1">
+{{ week.transactions.length - 5 }} more
</div>
</div>
</div>
</template>
<template v-else>
<div class="flex flex-col gap-4">
<div v-for="week in weeklyData" :key="week.label" class="flex flex-col gap-2">
<div class="flex items-center justify-between p-2 bg-surface-50 dark:bg-surface-800 rounded-lg">
<span class="font-medium text-surface-700 dark:text-surface-200">{{ week.label }}</span>
<span class="font-semibold text-surface-900 dark:text-surface-0">{{ formatAmount(week.amount) }}
</span>
</div>
<!-- Transactions List -->
<div
class="flex flex-col gap-1 pl-2 border-l-2 border-surface-100 dark:border-surface-700 ml-2 h-fit">
<div v-for="tx in week.transactions.slice(0, 5)" :key="tx.id"
class="flex items-center justify-between py-1 px-2 text-sm hover:bg-surface-50 dark:hover:bg-surface-800 rounded transition-colors">
<div class="flex items-center gap-2 overflow-hidden">
<span class="text-lg">{{ tx.category.icon }}</span>
<span class="text-surface-600 dark:text-surface-300 truncate">{{ tx.category.name }}</span>
</div>
<span class="font-medium text-surface-900 dark:text-surface-100 whitespace-nowrap">{{
formatAmount(tx.amount) }} </span>
</div>
<div v-if="week.transactions.length > 5" class="text-xs text-surface-400 pl-2 pt-1">
+{{ week.transactions.length - 5 }} more
</div>
</div>
</div>
</div>
</template>
</div>
</template>
</div>
</div>
</div>
</div>

View File

@@ -1,42 +1,129 @@
<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useTransactionStore } from '@/stores/transactions-store';
import { computed, onMounted, ref, watch } from 'vue';
import { useSpaceStore } from '@/stores/spaceStore';
import { useUserStore } from '@/stores/userStore';
import { TransactionType } from '@/models/enums';
import { useRecurrentsStore } from '@/stores/recurrent-store';
import { TransactionType, TransactionKind } from '@/models/enums';
import { Transaction, UpdateTransactionDTO } from '@/models/transaction';
import { TransactionFilters, TransactionService } from '@/services/transactions-service';
import { DashboardService } from '@/services/dashboard-service';
import StatsCard from './StatsCard.vue';
import RecentTransactions from './RecentTransactions.vue';
import DashboardCharts from './DashboardCharts.vue';
import UpcomingTransactions from './UpcomingTransactions.vue';
import { useToast, ProgressSpinner } from 'primevue';
import Button from 'primevue/button';
import { DashboardData } from '@/models/dashboard';
const transactionStore = useTransactionStore();
import dayjs from 'dayjs';
const toast = useToast()
const spaceStore = useSpaceStore();
const userStore = useUserStore();
const recurrentsStore = useRecurrentsStore();
const transactionService = TransactionService
const dashboardService = DashboardService
const dashboardData = ref<DashboardData>()
const dashboardTransactions = ref<Transaction[]>([]);
const plannedTransactions = ref<Transaction[]>([]);
const currentBaseDate = ref(dayjs());
const displayMonth = computed(() => {
return currentBaseDate.value.format('MMMM YYYY');
});
const prevMonth = () => {
currentBaseDate.value = currentBaseDate.value.subtract(1, 'month');
fetchDashboardData();
};
const nextMonth = () => {
currentBaseDate.value = currentBaseDate.value.add(1, 'month');
fetchDashboardData();
};
const fetchDashboardData = async () => {
if (!spaceStore.selectedSpaceId) return;
const startDate = currentBaseDate.value.date(10).toDate();
const endDate = currentBaseDate.value.add(1, 'month').date(9).toDate();
try {
dashboardData.value = await dashboardService.fetchDashboardData(spaceStore.selectedSpaceId, startDate, endDate)
dashboardTransactions.value = dashboardData.value.recentTransactions
plannedTransactions.value = dashboardData.value.upcomingTransactions
console.log(plannedTransactions.value)
console.log(dashboardTransactions.value)
// Fetch transactions for charts and stats (Done transactions)
// dashboardTransactions.value = await transactionService.getTransactions(spaceStore.selectedSpaceId, {
// kind: "INSTANT",
// limit: 10,
// sorts: [{ "sortBy": "t.date", "sortDirection": "DESC" }, { "sortBy": "t.id", "sortDirection": "DESC" }]
// } as TransactionFilters);
// // Fetch planned transactions for Upcoming Payments
// plannedTransactions.value = await TransactionService.getTransactions(spaceStore.selectedSpaceId, {
// kind: TransactionKind.PLANNING,
// isDone: false,
// offset: 0,
// limit: 5,
// } as TransactionFilters);
} catch (e) {
console.error("Failed to fetch dashboard data", e);
}
};
const setTransactionDone = async (transaction: Transaction): Promise<void> => {
console.log(transaction)
const updateTransaction = {
type: transaction.type,
kind: transaction.kind,
categoryId: transaction.category.id,
comment: transaction.comment,
amount: transaction.amount,
fees: 0,
isDone: !transaction.isDone,
date: new Date(transaction.date),
} as UpdateTransactionDTO
console.log(updateTransaction)
try {
await transactionService.updateTransaction(spaceStore.selectedSpaceId as number, transaction.id, updateTransaction)
} catch (error) {
toast.add({
severity: 'error',
summary: 'Failed to update transactions.',
detail: String(error),
life: 3000,
})
}
}
onMounted(async () => {
if (spaceStore.selectedSpaceId) {
await Promise.all([
transactionStore.fetchTransactions(spaceStore.selectedSpaceId),
transactionStore.fetchPlannedTransactions(spaceStore.selectedSpaceId)
fetchDashboardData(),
// recurrentsStore.fetchRecurrents(spaceStore.selectedSpaceId)
]);
}
});
const totalIncome = computed(() => {
return transactionStore.transactions
.filter(t => t.type === TransactionType.INCOME)
.reduce((sum, t) => sum + t.amount, 0);
watch(() => spaceStore.selectedSpaceId, async (newId) => {
if (newId) {
await Promise.all([
fetchDashboardData(),
// recurrentsStore.fetchRecurrents(newId)
]);
}
});
const totalExpense = computed(() => {
return transactionStore.transactions
.filter(t => t.type === TransactionType.EXPENSE)
.reduce((sum, t) => sum + t.amount, 0);
});
const totalBalance = computed(() => {
return totalIncome.value - totalExpense.value;
});
const userName = computed(() => {
return userStore.user?.firstName || 'User';
@@ -44,10 +131,17 @@ const userName = computed(() => {
</script>
<template>
<div class="flex flex-col gap-6 w-full pb-20">
<ProgressSpinner v-if="!dashboardData" />
<div v-else class="flex flex-col gap-6 w-full pb-20">
<!-- Header / Greeting -->
<div class="flex flex-col gap-1 px-1">
<h1 class="text-2xl font-bold text-surface-900 dark:text-surface-0">
<div class="flex items-center justify-between mb-4">
<Button icon="pi pi-chevron-left" text rounded @click="prevMonth" />
<span class="text-xl font-semibold capitalize">{{ displayMonth }}</span>
<Button icon="pi pi-chevron-right" text rounded @click="nextMonth" />
</div>
<h1 class="!text-2xl !font-semibold text-surface-900 dark:text-surface-0">
Hello, {{ userName }}! 👋
</h1>
<p class="text-surface-500 dark:text-surface-400">
@@ -56,34 +150,27 @@ const userName = computed(() => {
</div>
<!-- Stats Cards -->
<div class="grid grid-cols-3 md:grid-cols-3 gap-4">
<StatsCard title="Total Balance" :amount="totalBalance" icon="pi pi-wallet" color="blue" />
<StatsCard title="Income" :amount="totalIncome" icon="pi pi-arrow-down-left" color="green" />
<StatsCard title="Expense" :amount="totalExpense" icon="pi pi-arrow-up-right" color="red" />
<div class="grid grid-cols-2 md:grid-cols-2 gap-4">
<StatsCard title="Expense" :amount="dashboardData.totalExpense" icon="pi pi-arrow-up-right" color="red" />
<StatsCard title="Income" :amount="dashboardData.totalIncome" icon="pi pi-arrow-down-left" color="green" />
<div class="col-span-2">
<StatsCard title="Total Balance" :amount="dashboardData.balance" icon="pi pi-wallet" color="blue" />
</div>
</div>
<!-- Charts & Upcoming -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div class="grid grid-cols-1 lg:grid-cols-1 gap-4">
<!-- Charts -->
<div
class="bg-surface-0 dark:bg-surface-900 p-4 rounded-xl shadow-sm border border-surface-200 dark:border-surface-700">
<h2 class="text-lg font-semibold mb-4 text-surface-900 dark:text-surface-0">Expenses by Category</h2>
<DashboardCharts :transactions="transactionStore.transactions" />
</div>
<DashboardCharts :categories="dashboardData.categories" :transactions="dashboardTransactions" />
<!-- Upcoming Transactions -->
<div class=" ">
<div class="flex items-center justify-between mb-4">
<h2 class="text-lg font-semibold text-surface-900 dark:text-surface-0">Upcoming Payments</h2>
<router-link to="/transactions" class="text-sm text-primary-600 dark:text-primary-400 hover:underline">View
all</router-link>
</div>
<UpcomingTransactions :transactions="transactionStore.plannedTransactions" />
<UpcomingTransactions :transactions="plannedTransactions" @set-tx-done="setTransactionDone" />
</div>
</div>
<!-- Recent Transactions -->
<RecentTransactions :transactions="transactionStore.transactions" />
<RecentTransactions :transactions="dashboardTransactions" />
</div>
</template>

View File

@@ -1,16 +1,17 @@
<script setup lang="ts">
import { Transaction } from '@/models/transaction';
import { computed } from 'vue';
import dayjs from 'dayjs';
import { formatAmount } from '@/utils/utils';
import { useRouter } from 'vue-router';
import Divider from 'primevue/divider';
const router = useRouter();
const props = defineProps<{
transactions: Transaction[];
}>();
const recentTransactions = computed(() => {
return props.transactions.slice(0, 5);
});
const formatDate = (date: string | Date) => {
return dayjs(date).format('MMM D');
@@ -29,41 +30,41 @@ const getAmountColor = (type: string) => {
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center justify-between px-1">
<h3 class="text-lg font-semibold text-surface-900 dark:text-surface-0">Recent Transactions</h3>
<router-link to="/transactions" class="text-sm text-primary-600 dark:text-primary-400 hover:underline">
View All
</router-link>
<div class="flex flex-col gap-1">
<div class="flex flex-row justify-between items-end px-2">
<span class="text-xl !font-semibold ">Recent transactions</span>
<router-link to="/transactions" class="text-sm text-primary-600 dark:text-primary-400 hover:underline">View
all</router-link>
</div>
<div v-if="recentTransactions.length === 0" class="text-center py-8 text-surface-500 dark:text-surface-400">
No recent transactions
</div>
<div v-else class="flex flex-col gap-3">
<div v-for="tx in recentTransactions" :key="tx.id"
class="flex items-center justify-between p-3 bg-white dark:bg-surface-900 rounded-xl border border-surface-100 dark:border-surface-800 shadow-sm">
<div class="flex items-center gap-3 w-full">
<div
class="w-10 h-10 rounded-full bg-surface-100 dark:bg-surface-800 flex items-center justify-center text-xl p-4">
{{ tx.category.icon }}
<div class="flex card">
<span v-if="transactions.length == 0">Looks like you haven't record any transaction yet.<router-link
to="/transactions/create" class="!text-blue-400">Try to create some.</router-link></span>
<div v-else v-for="key in transactions.keys()" :key="transactions[key].id"
@click="router.push(`/transactions/${transactions[key].id}/edit`)"
class="flex flex-col w-full gap-0 pl-5 items-start justify-items-center font-bold ">
<div class="flex flex-row w-full items-center justify-between">
<div class="flex flex-row items-center gap-2 ">
<span v-if="transactions[key].category" class="text-3xl"> {{
transactions[key].category.icon
}}</span>
<i v-else class="pi pi-question !text-3xl" />
<div class="flex flex-col !font-bold "> {{ transactions[key].comment }}
<div v-if="transactions[key].category" class="flex flex-row text-sm">
{{ transactions[key].category.name }}
</div>
</div>
</div>
<div class="flex flex-col w-full">
<span class="font-medium text-surface-900 dark:text-surface-0 w-fit">{{ tx.comment }}</span>
<span class="text-xs text-surface-500 dark:text-surface-400">{{ tx.category.name }} | {{ formatDate(tx.date)
}}</span>
<div class="flex flex-row gap-2 items-center">
<div class="flex flex-col justify-between items-end !w-fit whitespace-nowrap shrink-0">
<span class="text-lg !font-bold ">{{ formatAmount(transactions[key].amount) }} </span>
<span class="text-sm !font-extralight"> {{ formatDate(transactions[key].date) }}</span>
</div>
<i class="pi pi-angle-right !font-extralight" />
</div>
</div>
<div class="flex flex-col items-end w-full">
<span :class="['!font-semibold', getAmountColor(tx.type)]">
{{ tx.type === 'EXPENSE' ? '-' : '+' }}{{ formatAmount(tx.amount) }}
</span>
<!-- <span v-if="tx.comment" class="text-xs text-surface-500 dark:text-surface-400 truncate !w-fit">
{{ tx.comment }}
</span> -->
</div>
<Divider v-if="key + 1 !== transactions.length" class="!m-0 !py-3" />
</div>
</div>
</div>
</template>

View File

@@ -19,13 +19,14 @@ const formatCurrency = (value: number, currency = 'RUB') => {
<div
class="bg-white dark:bg-surface-900 rounded-2xl p-4 shadow-sm flex flex-col gap-2 border border-surface-100 dark:border-surface-800">
<div class="flex items-center gap-3">
<div :class="`p-2 rounded-xl bg-${color}-50 dark:bg-${color}-500/10 text-${color}-500`">
<div :class="`p-2 rounded-xl !bg-${color}-50 !dark:bg-${color}-500/10 !text-${color}-500`">
<i :class="icon" class="text-xl"></i>
</div>
<span class="text-surface-500 dark:text-surface-400 font-medium text-sm">{{ title }}</span>
</div>
<div class="flex flex-col">
<span class="text-2xl font-bold text-surface-900 dark:text-surface-0">
<span class="!text-2xl !font-bold text-surface-900 dark:text-surface-0"
:class="amount < 0 ? '!text-red-500' : ''">
{{ formatCurrency(amount, currency) }}
</span>
</div>

View File

@@ -3,67 +3,81 @@ import { Transaction } from '@/models/transaction';
import { computed } from 'vue';
import dayjs from 'dayjs';
import { formatAmount } from '@/utils/utils';
import { Checkbox } from 'primevue';
import { Divider } from 'primevue';
const props = defineProps<{
transactions: Transaction[];
transactions: Transaction[];
}>();
const emits = defineEmits(["set-tx-done"])
const upcomingTransactions = computed(() => {
return props.transactions
.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
.slice(0, 5);
return props.transactions
.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
.slice(0, 5);
});
const formatDate = (date: string | Date) => {
return dayjs(date).format('MMM D');
return dayjs(date).format('MMM D');
};
const getDaysUntilText = (date: string | Date) => {
const days = dayjs(date).diff(dayjs(), 'day');
if (days === 0) return 'Today';
if (days === 1) return 'Tomorrow';
if (days < 0) return 'Overdue';
return `in ${days} days`;
const days = dayjs(date).diff(dayjs(), 'day');
if (days === 0) return 'Today';
if (days === 1) return 'Tomorrow';
if (days < 0) return 'Overdue';
return `in ${days} days`;
};
const getAmountColor = (type: string) => {
return type === 'INCOME' ? '!text-green-600 !dark:text-green-400' : '!text-red-600 !dark:text-red-400';
return type === 'INCOME' ? '!text-green-600 !dark:text-green-400' : '!text-red-600 !dark:text-red-400';
};
const setTxDone = (tx: Transaction) => {
emits("set-tx-done", tx)
}
</script>
<template>
<div class="flex flex-col gap-3">
<div v-if="upcomingTransactions.length === 0" class="text-center py-8 text-surface-500 dark:text-surface-400">
No upcoming planned transactions
</div>
<div v-else class="flex flex-col gap-3">
<div
v-for="tx in upcomingTransactions"
:key="tx.id"
class="flex items-center justify-between p-3 bg-white dark:bg-surface-900 rounded-xl border border-surface-100 dark:border-surface-800 shadow-sm"
>
<div class="flex items-center gap-3 w-full">
<div class="w-10 h-10 rounded-full bg-surface-100 dark:bg-surface-800 flex items-center justify-center text-xl p-4">
{{ tx.category.icon }}
</div>
<div class="flex flex-col w-full">
<span class="font-medium text-surface-900 dark:text-surface-0 w-full">{{ tx.comment }}</span>
<div class="flex items-center gap-1 text-xs">
<span class="text-primary-500 font-medium">{{ getDaysUntilText(tx.date) }}</span>
<span class="text-surface-500 dark:text-surface-400">({{ formatDate(tx.date) }})</span>
<div class="flex flex-col gap-0 ">
<div class="flex flex-row justify-between items-end px-2">
<span class="text-xl !font-semibold ">Upcoming transactions</span>
<router-link to="/transactions" class="text-sm text-primary-600 dark:text-primary-400 hover:underline">View
all</router-link>
</div>
<div class="flex card">
<span v-if="transactions.length == 0">Looks like you haven't plan any transactions yet. <router-link
to="/transactions/create" class="!text-blue-400">Try to create some.</router-link></span>
<div v-else v-for="key in transactions.keys()" :key="transactions[key].id"
class="flex flex-col w-full gap-0 pl-5 items-start justify-items-center font-bold ">
<div class="flex flex-row w-full items-center gap-4">
<Checkbox v-model="transactions[key].isDone" binary class="text-3xl"
@change="setTransactionDone(transactions[key])">
{{ transactions[key].category.icon }}
</Checkbox>
<div class="flex !flex-row !justify-between !w-full"
@click="router.push(`/transactions/${transactions[key].id}/edit`)">
<div class="flex flex-row items-center gap-2">
<div class="flex flex-col !font-bold "> {{ transactions[key].comment }}
<div class="flex flex-row text-sm">{{ transactions[key].category.icon }}
{{ transactions[key].category.name }}
</div>
</div>
</div>
<div class="flex flex-row gap-2 items-center !w-fit">
<div class="flex flex-col justify-between items-end !w-fit whitespace-nowrap shrink-0">
<span class="text-lg !font-bold">{{ formatAmount(transactions[key].amount) }} </span>
<span class="text-sm !font-extralight"> {{ formatDate(transactions[key].date) }} {{
getDaysUntilText(transactions[key].date) }}</span>
</div>
<i class="pi pi-angle-right !font-extralight" />
</div>
</div>
</div>
<Divider v-if="key + 1 !== transactions.length" class="!m-0 !py-3" />
</div>
</div>
</div>
<div class="flex flex-col items-end w-full">
<span :class="['!font-semibold', getAmountColor(tx.type)]">
{{ tx.type === 'EXPENSE' ? '-' : '+' }}{{ formatAmount(tx.amount) }}
</span>
<!-- <span v-if="tx.comment" class="text-xs text-surface-500 dark:text-surface-400 truncate !w-fit">
{{ tx.comment }}
</span> -->
</div>
</div>
</div>
</div>
</template>

19
src/models/dashboard.ts Normal file
View File

@@ -0,0 +1,19 @@
import { Category } from "./category"
import { Transaction } from "./transaction"
export interface DashboardData {
totalExpense: number,
totalIncome: number,
balance: number,
categories: DashboardCategory[],
upcomingTransactions: Transaction[],
recentTransactions: Transaction[],
}
export interface DashboardCategory {
category: Category,
currentPeriodAmount: number,
previousPeriodAmount: number,
changeDiff: number,
changeDiffPercentage: number,
}

View File

@@ -0,0 +1,19 @@
import api from "@/network/axiosSetup"
import { toDateOnly } from "@/utils/utils"
async function fetchDashboardData(spaceId: number, startDate: Date, endDate: Date) {
try {
const result = await api.get(`/spaces/${spaceId}/dashboard?startDate=${toDateOnly(startDate)}&endDate=${toDateOnly(endDate)}`)
return result.data
} catch (error) {
console.error(error)
throw error
}
}
export const DashboardService = {
fetchDashboardData
}

View File

@@ -1,7 +1,7 @@
import {CreateTransactionDTO, Transaction, UpdateTransactionDTO} from "@/models/transaction";
import {TransactionKind, TransactionType} from "@/models/enums";
import {categoriesService} from "@/services/categories-service";
import {User} from "@/models/user";
import { CreateTransactionDTO, Transaction, UpdateTransactionDTO } from "@/models/transaction";
import { TransactionKind, TransactionType } from "@/models/enums";
import { categoriesService } from "@/services/categories-service";
import { User } from "@/models/user";
import api from "@/network/axiosSetup";
// const spaceStore = useSpaceStore();
@@ -12,21 +12,27 @@ function toDateOnly(d: Date): string {
return `${y}-${m}-${day}`;
}
export interface TransactionFilters{
type : TransactionType | null
export interface TransactionFilters {
type: TransactionType | null
kind: TransactionKind | null
dateFrom: string | Date | null
dateTo: string | Date | null
isDone: boolean | null
offset: number | null
limit: number | null
sorts: Map<string, string>[]
}
enum SortDirection {
ASC = "ASC",
DESC = 'DESC'
}
async function getTransactions(spaceId: number, filters: TransactionFilters): Promise<Transaction[]> {
try {
let response = await api.post(`/spaces/${spaceId}/transactions/_search`, filters );
let response = await api.post(`/spaces/${spaceId}/transactions/_search`, filters);
return response.data;
}catch (error) {
} catch (error) {
console.error(error);
throw error;
}
@@ -34,7 +40,7 @@ async function getTransactions(spaceId: number, filters: TransactionFilters): Pr
async function getTransaction(spaceId: number, id: number): Promise<Transaction> {
try {
let response = await api.get(`/spaces/${spaceId}/transactions/${id}`);
let response = await api.get(`/spaces/${spaceId}/transactions/${id}`);
return response.data;
} catch (error) {
console.error(error);

View File

@@ -89,3 +89,9 @@ export const getRandomColor = () => {
}
export const toDateOnly = (d : Date): string => {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}