Dashboard: wykres kropek killstreaka (30 dni) + pole API killstreakDays (GET /dashboard); bez etykiety Historia

This commit is contained in:
tisachi
2026-10-17 05:09:59 +02:00
parent 3160d9fa2e
commit 7483d5017e
10 changed files with 123 additions and 15 deletions

View File

@@ -19,10 +19,18 @@ export async function getDashboard(prisma: PrismaClient, userId: string) {
where: { userId, status: 'COMPLETED' },
select: { id: true },
}));
// Okno kropek killstreaka: 30 ostatnich dni (włącznie z dziś).
const streakNow = new Date();
const streakWindowStart = new Date(
streakNow.getFullYear(),
streakNow.getMonth(),
streakNow.getDate() - 29,
);
const streakStats = planHistory
? await getKillstreakStats(prisma, userId)
: { current: 0, best: 0 };
? await getKillstreakStats(prisma, userId, streakWindowStart)
: { current: 0, best: 0, effectiveDates: [] as Date[] };
const killstreak = streakStats.current;
const killstreakDays = streakStats.effectiveDates.map((d) => d.toISOString());
const now = new Date();
const completedSessionWhere = {
@@ -194,6 +202,7 @@ export async function getDashboard(prisma: PrismaClient, userId: string) {
return {
killstreak,
killstreakBest: streakStats.best,
killstreakDays,
history,
week,
lastSessionAt: lastSessionAt ? lastSessionAt.toISOString() : null,

View File

@@ -49,12 +49,15 @@ export async function getKillstreak(prisma: PrismaClient, userId: string): Promi
/**
* Jak getKillstreak, ale z jednym przebiegiem historii liczy też
* `best` — najlepszą passę z całej dotychczasowej historii (te same
* zasady skuteczności i resetów).
* zasady skuteczności i resetów). Gdy podano `effectiveSince`, dodatkowo
* zwraca `effectiveDates` — daty (PlanDay.date) dni ze skutecznym treningiem
* od tej chwili włącznie (np. okno 30 dni na wykres kropek).
*/
export async function getKillstreakStats(
prisma: PrismaClient,
userId: string,
): Promise<{ current: number; best: number }> {
effectiveSince?: Date,
): Promise<{ current: number; best: number; effectiveDates: Date[] }> {
const days = await prisma.planDay.findMany({
where: {
week: { plan: { userId, status: { in: ['ACTIVE', 'COMPLETED'] } } },
@@ -82,6 +85,7 @@ export async function getKillstreakStats(
const startOfTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
let streak = 0;
let best = 0;
const effectiveDates: Date[] = [];
for (const day of days) {
if (day.date! >= startOfTomorrow) break; // future day — not yet relevant
@@ -90,6 +94,7 @@ export async function getKillstreakStats(
if (session && isSessionEffective(session)) {
streak++; // effective training
if (streak > best) best = streak;
if (effectiveSince && day.date! >= effectiveSince) effectiveDates.push(day.date!);
} else {
streak = 0; // partially completed day resets the streak
}
@@ -98,5 +103,5 @@ export async function getKillstreakStats(
}
// PLANNED days (today, not yet done) do not change the streak
}
return { current: streak, best };
return { current: streak, best, effectiveDates };
}

View File

@@ -1095,7 +1095,7 @@ export const openapi: Record<string, unknown> = {
get: {
tags: ['Dashboard'],
summary:
'Dashboard — killstreak (+ rekord), globalna historia (plany/sesje/serie, pierwsza/ostatnia sesja, serie wg tygodni), tempo tygodnia i postęp aktywnego planu',
'Dashboard — killstreak (+ rekord, daty skutecznych dni z 30 ostatnich), globalna historia (plany/sesje/serie, pierwsza/ostatnia sesja, serie wg tygodni), tempo tygodnia i postęp aktywnego planu',
security: [{ bearerAuth: [] }],
},
},

View File

@@ -18,6 +18,7 @@ describe('dashboard routes', () => {
expect(rest).toEqual({
killstreak: 0,
killstreakBest: 0,
killstreakDays: [],
history: { completedPlans: 0, sessions: 0, sets: 0 },
week: null,
lastSessionAt: null,
@@ -154,6 +155,13 @@ describe('dashboard routes', () => {
expect(res.status).toBe(200);
expect(res.body.killstreak).toBe(1);
expect(res.body.killstreakBest).toBe(4);
// Kropki: skuteczne dni z okna 30 dni (-60 wypada poza oknem), posortowane rosnąco.
expect(res.body.killstreakDays.map((d: string) => new Date(d).getTime())).toEqual([
dBefore(12).getTime(),
dBefore(11).getTime(),
dBefore(5).getTime(),
monday.getTime(),
]);
expect(res.body.week).toEqual({ planned: 2, completed: 1 });
expect(new Date(res.body.firstSessionAt).getTime()).toBe(dBefore(60).getTime());
expect(new Date(res.body.lastSessionAt).getTime()).toBe(monday.getTime());

View File

@@ -229,17 +229,42 @@ describe('getKillstreakStats', () => {
day(-27, 'SKIPPED'),
day(-1, 'COMPLETED', eff),
]);
expect(await getKillstreakStats(prisma, 'u1')).toEqual({ current: 1, best: 3 });
expect(await getKillstreakStats(prisma, 'u1')).toEqual({
current: 1,
best: 3,
effectiveDates: [],
});
});
it('bez dni zwraca zera', async () => {
findMany.mockResolvedValue([]);
expect(await getKillstreakStats(prisma, 'u1')).toEqual({ current: 0, best: 0 });
expect(await getKillstreakStats(prisma, 'u1')).toEqual({
current: 0,
best: 0,
effectiveDates: [],
});
});
it('best rośnie razem z bieżącą passą, gdy historia jest jedna', async () => {
const eff = [[plannedExercise(['ps1'], [10])]];
findMany.mockResolvedValue([day(-2, 'COMPLETED', eff), day(-1, 'COMPLETED', eff)]);
expect(await getKillstreakStats(prisma, 'u1')).toEqual({ current: 2, best: 2 });
expect(await getKillstreakStats(prisma, 'u1')).toEqual({
current: 2,
best: 2,
effectiveDates: [],
});
});
it('effectiveSince: daty skutecznych dni od progu (rosnąco), częściowe dni pomijane', async () => {
const eff = [[plannedExercise(['ps1'], [10])]];
const partial = [[plannedExercise(['ps1'], [null])]];
findMany.mockResolvedValue([
day(-40, 'COMPLETED', eff),
day(-10, 'COMPLETED', eff),
day(-5, 'COMPLETED', partial),
day(-2, 'COMPLETED', eff),
]);
const res = await getKillstreakStats(prisma, 'u1', new Date(2026, 7, 22 - 29));
expect(res.effectiveDates.map((d) => d.getDate())).toEqual([12, 20]);
});
});

View File

@@ -356,6 +356,8 @@ export interface Dashboard {
killstreak: number;
/** Najlepsza passa z całej historii (planów ACTIVE/COMPLETED). */
killstreakBest: number;
/** Daty skutecznych treningów z ostatnich 30 dni (ISO) — kropki w kafelku Killstreak. */
killstreakDays?: string[];
/** Statystyki globalne (ponad wszystkimi planami) — w kontrze do progress/extra/missing. */
history: { completedPlans: number; sessions: number; sets: number };
/** Tempo tygodnia: ukończone vs zaplanowane dni aktywnego planu w bieżącym tygodniu (pon–nd). */

View File

@@ -76,6 +76,27 @@ function WeekBars({ values }: { values: number[] }) {
);
}
/* Kropki (aria-hidden): okno 30 dni — pełna kropka to dzień ze skutecznym treningiem. */
function StreakDots({ days }: { days: string[] }) {
const done = new Set(days.map((d) => d.slice(0, 10)));
const now = new Date();
const cells: boolean[] = [];
for (let i = 29; i >= 0; i--) {
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i);
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
d.getDate(),
).padStart(2, '0')}`;
cells.push(done.has(key));
}
return (
<div aria-hidden="true" data-testid="streak-dots" className="mt-1.5 flex flex-wrap gap-[3px]">
{cells.map((on, i) => (
<span key={i} className={`h-1.5 w-1.5 rounded-full ${on ? 'bg-accent' : 'bg-dim/20'}`} />
))}
</div>
);
}
/* Pierścień postępu (SVG, gradient akcentu). */
function ProgressRing({ percent }: { percent: number }) {
const r = 26;
@@ -411,7 +432,6 @@ export default function Dashboard() {
{/* Historia — statystyki ponad wszystkimi planami (ukryta, gdy brak dorobku) */}
{historyVisible && (
<>
<GroupLabel className="mb-2">Historia</GroupLabel>
{/* Jedna linia: Serie + Killstreak (razem 4/5) i Ukończone plany (1/5). */}
<div className="mb-4 grid grid-cols-1 gap-4 sm:grid-cols-5">
{/* Kafelek: łączna liczba serii + prawdziwy trend tygodniowy. */}
@@ -423,9 +443,7 @@ export default function Dashboard() {
<div className="font-display text-[1.9rem] font-bold leading-tight tracking-[-0.02em] tabular-nums">
{history.sets}
</div>
<div className="text-dim text-[0.8125rem]">
łącznie · kreski: serie w 8 ostatnich tygodniach
</div>
<div className="text-dim text-[0.8125rem]">serie w ostatnich tygodniach</div>
</div>
<WeekBars values={(data.weeklySets ?? []).map((w) => w.sets)} />
</Card>
@@ -433,7 +451,12 @@ export default function Dashboard() {
className="sm:col-span-2"
label="Killstreak"
value={data.killstreak > 0 ? data.killstreak : '—'}
sub={`rekord: ${daysPlural(killstreakBest)}`}
sub={
<>
{`rekord: ${daysPlural(killstreakBest)}`}
{data.killstreakDays != null && <StreakDots days={data.killstreakDays} />}
</>
}
/>
<StatCard
className="sm:col-span-1"

View File

@@ -29,12 +29,24 @@ const USER: User = {
const DAY = 86_400_000;
const ago = (days: number) => new Date(Date.now() - days * DAY).toISOString();
/** Key dnia względnego (jak StreakDots: ISO.slice(0,10) vs klucz lokalny). */
const dayKey = (daysAgo: number) => {
const d = new Date();
d.setDate(d.getDate() - daysAgo);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
d.getDate(),
).padStart(2, '0')}`;
};
/** Dzień skutecznej sesji n dni temu w formacie kontraktu (ISO — frontend tnie do daty). */
const effDay = (daysAgo: number) => `${dayKey(daysAgo)}T07:00:00.000Z`;
/** Ciało GET /dashboard z pełnymi polami motywacyjnymi; `overrides` nadpisuje pola. */
function dashBody(overrides: Record<string, unknown> = {}) {
return {
killstreak: 3,
killstreakBest: 5,
killstreakDays: [effDay(2), effDay(1), effDay(0)],
history: { completedPlans: 1, sessions: 12, sets: 96 },
week: { planned: 3, completed: 1 },
lastSessionAt: ago(1),
@@ -163,11 +175,27 @@ describe('Dashboard — statystyki motywacyjne', () => {
).toHaveLength(8);
});
it('kropki killstreaka: 30 dni, wypełnione = skuteczne sesje', async () => {
mockApi(dashBody());
const user = userEvent.setup();
const { container } = renderApp();
await login(user);
await screen.findByText('rekord: 5 dni');
const dots = container.querySelectorAll('[data-testid="streak-dots"] span');
expect(dots).toHaveLength(30);
const on = [...dots].filter((el) => (el.getAttribute('class') ?? '').includes('bg-accent'));
expect(on).toHaveLength(3);
// Ostatnie trzy kropki (wczoraj, przedwczoraj, dziś) — zgodne z mockiem.
expect([...dots].slice(-3).every((el) => (el.getAttribute('class') ?? '').includes('bg-accent'))).toBe(true);
});
it('bez dorobku (same zera, brak sesji): sekcja „Historia” ukryta', async () => {
mockApi(
dashBody({
killstreak: 0,
killstreakBest: 0,
killstreakDays: [],
history: { completedPlans: 0, sessions: 0, sets: 0 },
lastSessionAt: null,
firstSessionAt: null,

View File

@@ -20,7 +20,7 @@ test('udane logowanie przekierowuje na dashboard', async ({ page }) => {
await expect(page.getByText('Plan testowy')).toBeVisible();
await expect(page.getByText('Tempo w tym tygodniu', { exact: true })).toBeVisible();
await expect(page.getByText('1/3', { exact: true })).toBeVisible();
await expect(page.getByText('Historia', { exact: true })).toBeVisible();
await expect(page.getByText('Killstreak', { exact: true })).toBeVisible();
await expect(page.getByText('rekord: 5 dni')).toBeVisible();
await expect(page.getByText('Ukończone plany', { exact: true })).toBeVisible();
});

View File

@@ -45,6 +45,14 @@ export const TEST_FOCUS_CHAIN = {
export const TEST_DASHBOARD = {
killstreak: 3,
killstreakBest: 5,
// Kropki killstreaka względne do „dziś" — widoczne w oknie 30 dni.
killstreakDays: [2, 1, 0].map((d) => {
const day = new Date();
day.setDate(day.getDate() - d);
return `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(
day.getDate(),
).padStart(2, '0')}T07:00:00.000Z`;
}),
history: { completedPlans: 2, sessions: 18, sets: 143 },
week: { planned: 3, completed: 1 },
lastSessionAt: '2026-10-13T07:00:00.000Z',