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

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> <template>
<div class="dashboard"> <div class="dashboard">
<div v-if="isAuthenticated && user"> <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"> <div v-if="loading" class="loading-message">
<p>Loading habits...</p> <p>Loading habits...</p>
@ -11,22 +11,25 @@
<div v-for="habit in processedHabits" :key="habit.id" class="habit-card"> <div v-for="habit in processedHabits" :key="habit.id" class="habit-card">
<div class="habit-details"> <div class="habit-details">
<div class="habit-header"> <div class="habit-header">
<span class="habit-name">{{ habit.name }}</span> <div class="habit-title-area">
<span class="habit-name">{{ habit.name }}</span>
<span class="habit-schedule">{{ formatDaysOfWeek(habit.daysOfWeek) }}</span>
</div>
<button <button
v-if="!isCompleteToday(habit)" v-if="isActionableToday(habit) && !isCompleteToday(habit)"
@click="completeHabit(habit.id)" @click="completeHabit(habit.id)"
:disabled="completing === habit.id" :disabled="completing === habit.id"
class="complete-btn" class="complete-btn"
> >
{{ completing === habit.id ? '...' : 'Complete' }} {{ completing === habit.id ? '...' : 'Complete' }}
</button> </button>
<span v-else class="completed-text"> Done!</span> <span v-else-if="isCompleteToday(habit)" class="completed-text"> Done!</span>
</div> </div>
<div class="calendar-grid"> <div class="calendar-grid">
<div <div
v-for="day in calendarDays" v-for="day in calendarDays"
:key="day.getTime()" :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> <span class="date-label">{{ formatDate(day) }}</span>
</div> </div>
@ -36,7 +39,7 @@
</div> </div>
<div v-else class="empty-state"> <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> <NuxtLink to="/habits">Manage Habits</NuxtLink>
</div> </div>
@ -54,7 +57,7 @@ import { ref, computed, onMounted, watch } from 'vue';
interface Habit { interface Habit {
id: number; id: number;
name: string; name: string;
daysOfWeek: number[]; // 0 = Sunday, 6 = Saturday daysOfWeek: number[]; // Backend: 0 = Monday, 6 = Sunday
completions: { id: number; date: string }[]; completions: { id: number; date: string }[];
createdAt: string; createdAt: string;
} }
@ -76,29 +79,32 @@ const completing = ref<number | null>(null);
// --- Helpers: Date Normalization & Formatting --- // --- Helpers: Date Normalization & Formatting ---
/** /**
* Normalizes a date to the start of the day in UTC. * 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 => { const normalizeDateUTC = (date: Date): Date => {
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())); 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 today = normalizeDateUTC(new Date());
const formatDate = (date: Date): string => { const formatDate = (date: Date): string => {
// Format: "3 янв."
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' }); return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
}; };
// --- Computed Properties --- // --- Computed Properties ---
const processedHabits = computed((): HabitWithCompletionSet[] => { const processedHabits = computed((): HabitWithCompletionSet[] => {
const todayDayIndex = today.getUTCDay(); // 0 = Sunday, 1 = Monday...
return allHabits.value return allHabits.value
.filter(h => h.daysOfWeek.includes(todayDayIndex)) // Only show habits active today
.map(habit => ({ .map(habit => ({
...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())), completionDates: new Set(habit.completions.map(c => normalizeDateUTC(new Date(c.date)).getTime())),
createdAtTimestamp: normalizeDateUTC(new Date(habit.createdAt)).getTime(), createdAtTimestamp: normalizeDateUTC(new Date(habit.createdAt)).getTime(),
})); }));
@ -106,13 +112,12 @@ const processedHabits = computed((): HabitWithCompletionSet[] => {
const calendarDays = computed(() => { const calendarDays = computed(() => {
const dates = []; const dates = [];
const currentDayOfWeek = today.getUTCDay(); // 0 = Sun, 1 = Mon... // JS day is 0=Sun, so we normalize it to backend's 0=Mon format.
// Adjust so Monday is 0 and Sunday is 6 const todayBackendDay = normalizeJsDay(today.getUTCDay());
const adjustedDay = currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1;
// Start date is the Monday of the previous week // Start date is the Monday of the previous week.
const startDate = normalizeDateUTC(new Date(today)); 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++) { for (let i = 0; i < 14; i++) {
const d = new Date(startDate); const d = new Date(startDate);
@ -125,35 +130,48 @@ const calendarDays = computed(() => {
// --- Methods: Status and Actions --- // --- 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 getDayStatus = (habit: HabitWithCompletionSet, date: Date): string => {
const normalizedDate = normalizeDateUTC(date); const normalizedDate = normalizeDateUTC(date);
const normalizedTimestamp = normalizedDate.getTime(); const normalizedTimestamp = normalizedDate.getTime();
const dayIndex = normalizedDate.getUTCDay(); // 0 = Sunday
// Rule a) FUTURE
if (normalizedTimestamp > today.getTime()) { if (normalizedTimestamp > today.getTime()) {
return 'NEUTRAL'; return 'NEUTRAL';
} }
// Rule b) BEFORE_CREATED
if (normalizedTimestamp < habit.createdAtTimestamp) { if (normalizedTimestamp < habit.createdAtTimestamp) {
return 'NEUTRAL'; return 'NEUTRAL';
} }
// Rule c) NOT_SCHEDULED if (!isScheduledDay(habit, date)) {
const isActiveDay = habit.daysOfWeek.includes(dayIndex);
if (!isActiveDay) {
return 'NEUTRAL'; return 'NEUTRAL';
} }
// Rule d) COMPLETED
if (habit.completionDates.has(normalizedTimestamp)) { if (habit.completionDates.has(normalizedTimestamp)) {
return 'COMPLETED'; 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'; return 'MISSED';
}; };
@ -224,13 +242,24 @@ onMounted(() => {
.habit-header { .habit-header {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: flex-start; /* Align items to the top */
margin-bottom: 15px; margin-bottom: 15px;
gap: 10px; /* Add gap between title area and button */
}
.habit-title-area {
display: flex;
flex-direction: column;
gap: 4px;
} }
.habit-name { .habit-name {
font-size: 1.2em; font-size: 1.2em;
font-weight: bold; font-weight: bold;
} }
.habit-schedule {
font-size: 0.85em;
color: #666;
font-style: italic;
}
.complete-btn { .complete-btn {
padding: 8px 12px; padding: 8px 12px;
border: none; border: none;
@ -243,6 +272,7 @@ onMounted(() => {
.completed-text { .completed-text {
color: #a3be8c; color: #a3be8c;
font-weight: bold; font-weight: bold;
flex-shrink: 0;
} }
.empty-state { .empty-state {
margin-top: 40px; margin-top: 40px;
@ -266,6 +296,10 @@ onMounted(() => {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: 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 { .date-label {
font-size: 0.75em; font-size: 0.75em;
@ -280,8 +314,10 @@ onMounted(() => {
} }
.calendar-cell.COMPLETED { .calendar-cell.COMPLETED {
background-color: #a3be8c; /* Green */ background-color: #a3be8c; /* Green */
border-color: #a3be8c;
} }
.calendar-cell.MISSED { .calendar-cell.MISSED {
background-color: #bf616a; /* Red */ background-color: #bf616a; /* Red */
border-color: #bf616a;
} }
</style> </style>

View File

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