фикс календаря на главной. приложение стабильно

This commit is contained in:
Alexander Andreev 2026-01-03 19:46:20 +03:00
parent 6f0b484c90
commit b8640802ae
2 changed files with 69 additions and 31 deletions

View File

@ -1,7 +1,7 @@
<template>
<div class="dashboard">
<div v-if="isAuthenticated && user">
<h2>Today's Habits for {{ user.nickname }}</h2>
<h2>My Habits for {{ user.nickname }}</h2>
<div v-if="loading" class="loading-message">
<p>Loading habits...</p>
@ -11,22 +11,25 @@
<div v-for="habit in processedHabits" :key="habit.id" class="habit-card">
<div class="habit-details">
<div class="habit-header">
<div class="habit-title-area">
<span class="habit-name">{{ habit.name }}</span>
<span class="habit-schedule">{{ formatDaysOfWeek(habit.daysOfWeek) }}</span>
</div>
<button
v-if="!isCompleteToday(habit)"
v-if="isActionableToday(habit) && !isCompleteToday(habit)"
@click="completeHabit(habit.id)"
:disabled="completing === habit.id"
class="complete-btn"
>
{{ completing === habit.id ? '...' : 'Complete' }}
</button>
<span v-else class="completed-text"> Done!</span>
<span v-else-if="isCompleteToday(habit)" class="completed-text"> Done!</span>
</div>
<div class="calendar-grid">
<div
v-for="day in calendarDays"
:key="day.getTime()"
:class="['calendar-cell', getDayStatus(habit, day)]"
:class="['calendar-cell', getDayStatus(habit, day), { 'is-scheduled': isScheduledDay(habit, day) }]"
>
<span class="date-label">{{ formatDate(day) }}</span>
</div>
@ -36,7 +39,7 @@
</div>
<div v-else class="empty-state">
<p>No habits scheduled for today. Great job!</p>
<p>You haven't created any habits yet.</p>
<NuxtLink to="/habits">Manage Habits</NuxtLink>
</div>
@ -54,7 +57,7 @@ import { ref, computed, onMounted, watch } from 'vue';
interface Habit {
id: number;
name: string;
daysOfWeek: number[]; // 0 = Sunday, 6 = Saturday
daysOfWeek: number[]; // Backend: 0 = Monday, 6 = Sunday
completions: { id: number; date: string }[];
createdAt: string;
}
@ -76,29 +79,32 @@ const completing = ref<number | null>(null);
// --- Helpers: Date Normalization & Formatting ---
/**
* Normalizes a date to the start of the day in UTC.
* This is CRITICAL for consistent date comparisons across timezones.
* @param date The date to normalize.
* @returns A new Date object set to 00:00:00 UTC.
*/
const normalizeDateUTC = (date: Date): Date => {
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
};
/**
* Normalizes a JS Date's getDay() result (0=Sun) to the backend's format (0=Mon).
* @param jsDay The result of date.getUTCDay()
* @returns A number where 0 = Monday, ..., 6 = Sunday.
*/
const normalizeJsDay = (jsDay: number): number => {
return jsDay === 0 ? 6 : jsDay - 1;
};
const today = normalizeDateUTC(new Date());
const formatDate = (date: Date): string => {
// Format: "3 янв."
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
};
// --- Computed Properties ---
const processedHabits = computed((): HabitWithCompletionSet[] => {
const todayDayIndex = today.getUTCDay(); // 0 = Sunday, 1 = Monday...
return allHabits.value
.filter(h => h.daysOfWeek.includes(todayDayIndex)) // Only show habits active today
.map(habit => ({
...habit,
// Pre-calculate a Set of completion timestamps for fast O(1) lookups
completionDates: new Set(habit.completions.map(c => normalizeDateUTC(new Date(c.date)).getTime())),
createdAtTimestamp: normalizeDateUTC(new Date(habit.createdAt)).getTime(),
}));
@ -106,13 +112,12 @@ const processedHabits = computed((): HabitWithCompletionSet[] => {
const calendarDays = computed(() => {
const dates = [];
const currentDayOfWeek = today.getUTCDay(); // 0 = Sun, 1 = Mon...
// Adjust so Monday is 0 and Sunday is 6
const adjustedDay = currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1;
// JS day is 0=Sun, so we normalize it to backend's 0=Mon format.
const todayBackendDay = normalizeJsDay(today.getUTCDay());
// Start date is the Monday of the previous week
// Start date is the Monday of the previous week.
const startDate = normalizeDateUTC(new Date(today));
startDate.setUTCDate(startDate.getUTCDate() - adjustedDay - 7);
startDate.setUTCDate(startDate.getUTCDate() - todayBackendDay - 7);
for (let i = 0; i < 14; i++) {
const d = new Date(startDate);
@ -125,35 +130,48 @@ const calendarDays = computed(() => {
// --- Methods: Status and Actions ---
const dayLabels = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
const formatDaysOfWeek = (days: number[]): string => {
if (days.length === 7) {
return 'Каждый день';
}
return [...days]
.sort((a, b) => a - b) // Sort numerically (0=Mon, 1=Tue, etc.)
.map(dayIndex => dayLabels[dayIndex])
.join(', ');
};
const isScheduledDay = (habit: HabitWithCompletionSet, date: Date): boolean => {
const backendDay = normalizeJsDay(normalizeDateUTC(date).getUTCDay());
return habit.daysOfWeek.includes(backendDay);
};
const isActionableToday = (habit: HabitWithCompletionSet): boolean => {
const todayBackendDay = normalizeJsDay(today.getUTCDay());
return habit.daysOfWeek.includes(todayBackendDay);
};
const getDayStatus = (habit: HabitWithCompletionSet, date: Date): string => {
const normalizedDate = normalizeDateUTC(date);
const normalizedTimestamp = normalizedDate.getTime();
const dayIndex = normalizedDate.getUTCDay(); // 0 = Sunday
// Rule a) FUTURE
if (normalizedTimestamp > today.getTime()) {
return 'NEUTRAL';
}
// Rule b) BEFORE_CREATED
if (normalizedTimestamp < habit.createdAtTimestamp) {
return 'NEUTRAL';
}
// Rule c) NOT_SCHEDULED
const isActiveDay = habit.daysOfWeek.includes(dayIndex);
if (!isActiveDay) {
if (!isScheduledDay(habit, date)) {
return 'NEUTRAL';
}
// Rule d) COMPLETED
if (habit.completionDates.has(normalizedTimestamp)) {
return 'COMPLETED';
}
// Rule e) MISSED
// All previous conditions failed, and we know date <= today.
// Therefore, if it's an active day that wasn't completed, it was missed.
return 'MISSED';
};
@ -224,13 +242,24 @@ onMounted(() => {
.habit-header {
display: flex;
justify-content: space-between;
align-items: center;
align-items: flex-start; /* Align items to the top */
margin-bottom: 15px;
gap: 10px; /* Add gap between title area and button */
}
.habit-title-area {
display: flex;
flex-direction: column;
gap: 4px;
}
.habit-name {
font-size: 1.2em;
font-weight: bold;
}
.habit-schedule {
font-size: 0.85em;
color: #666;
font-style: italic;
}
.complete-btn {
padding: 8px 12px;
border: none;
@ -243,6 +272,7 @@ onMounted(() => {
.completed-text {
color: #a3be8c;
font-weight: bold;
flex-shrink: 0;
}
.empty-state {
margin-top: 40px;
@ -266,6 +296,10 @@ onMounted(() => {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid transparent; /* Default transparent border */
}
.calendar-cell.is-scheduled {
border-color: #d8dee9; /* Neutral border for scheduled days */
}
.date-label {
font-size: 0.75em;
@ -280,8 +314,10 @@ onMounted(() => {
}
.calendar-cell.COMPLETED {
background-color: #a3be8c; /* Green */
border-color: #a3be8c;
}
.calendar-cell.MISSED {
background-color: #bf616a; /* Red */
border-color: #bf616a;
}
</style>

View File

@ -10,6 +10,7 @@ interface HabitDto {
id: number;
name: string;
daysOfWeek: number[];
createdAt: Date; // Add createdAt
completions: HabitCompletionDto[];
}
@ -34,7 +35,8 @@ export default defineEventHandler(async (event): Promise<HabitDto[]> => {
return habits.map((habit: any) => ({
id: habit.id,
name: habit.name,
daysOfWeek: habit.daysOfWeek, // Assuming daysOfWeek is already in the correct format
daysOfWeek: habit.daysOfWeek,
createdAt: habit.createdAt, // Add createdAt
completions: habit.completions.map((comp: any) => ({
date: comp.date,
})),