Plany: PATCH z startDate (aktywacja przy zapisie) i udostepnianie planow trener-podopieczny (PlanShare, sekcja Udostepnione mi, widok read-only)

This commit is contained in:
tisachi
2026-09-13 02:28:29 +02:00
parent 8049c4bc47
commit 1f29ce7003
19 changed files with 1791 additions and 76 deletions

View File

@@ -13,7 +13,16 @@ const EDGE: Record<Plan['status'], string> = {
};
/** Karta planu: tytuł + meta (tygodnie/dni/start/twórca), pasek postępu dla aktywnego, „Otwórz ›”. */
export function PlanCard({ plan, creatorLabel }: { plan: Plan; creatorLabel: string | null }) {
export function PlanCard({
plan,
creatorLabel,
creatorPrefix = 'utworzył',
}: {
plan: Plan;
creatorLabel: string | null;
/** Przedrostek etykiety twórcy (np. „udostępnił” w sekcji „Udostępnione mi”). */
creatorPrefix?: string;
}) {
// Postęp z API (lista); fallback na tygodnie, gdy dostępne (np. mocki bez `progress`).
const fromWeeks = (plan.weeks ?? []).flatMap((w) => w.days);
const progress =
@@ -36,13 +45,20 @@ export function PlanCard({ plan, creatorLabel }: { plan: Plan; creatorLabel: str
to={`/plans/${plan.id}`}
className="group relative flex flex-col gap-3 overflow-hidden rounded-xl border border-line bg-(image:--card-grad) p-4 pl-5 shadow-card transition-all duration-150 hover:border-accent/55 sm:flex-row sm:items-center sm:gap-4"
>
<span aria-hidden="true" className={`absolute inset-y-0 left-0 w-[3px] ${EDGE[plan.status]}`} />
<span
aria-hidden="true"
className={`absolute inset-y-0 left-0 w-[3px] ${EDGE[plan.status]}`}
/>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
<span className="min-w-0 truncate font-semibold transition-colors group-hover:text-accent-text">
{plan.title}
</span>
{creatorLabel && <span className="text-dim text-[0.8125rem]">utworzył: {creatorLabel}</span>}
{creatorLabel && (
<span className="text-dim text-[0.8125rem]">
{creatorPrefix}: {creatorLabel}
</span>
)}
</div>
<div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-dim text-[0.8125rem]">
<MetaItem icon={CalendarDays}>{plan.weeksCount} tyg.</MetaItem>
@@ -51,7 +67,9 @@ export function PlanCard({ plan, creatorLabel }: { plan: Plan; creatorLabel: str
{completed}/{total} dni
</span>
)}
{plan.startDate && <MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>}
{plan.startDate && (
<MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>
)}
</div>
{isActive && total > 0 && (
<div className="mt-2.5 flex items-center gap-2.5">
@@ -61,7 +79,9 @@ export function PlanCard({ plan, creatorLabel }: { plan: Plan; creatorLabel: str
style={{ width: `${percent}%` }}
/>
</div>
<span className="font-display text-[0.8125rem] font-bold tabular-nums text-dim">{percent}%</span>
<span className="font-display text-[0.8125rem] font-bold tabular-nums text-dim">
{percent}%
</span>
</div>
)}
</div>

View File

@@ -0,0 +1,133 @@
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import {
sharePlan,
unsharePlan,
useIsTrainer,
useMyTrainers,
useTrainees,
} from '../../api/queries';
import { useToast } from '../toast';
import { Button, ErrorText, Modal } from '../ui';
import type { Plan } from '../../api/types';
/** Imię i nazwisko (fallback: pseudonim, potem „użytkownik”). */
function userName(u: {
firstName: string | null;
lastName: string | null;
nickname?: string | null;
}): string {
return [u.firstName, u.lastName].filter(Boolean).join(' ') || u.nickname || 'użytkownik';
}
/**
* Udostępnianie planu (właściciel): lista odbiorców z AKTYWNYM coachingiem —
* podopieczni (gdy rola TRAINER) i trenerzy. Checkbox = share/unshare natychmiast.
* Odbiorca dostaje plan w trybie read-only.
*/
export function SharePlanDialog({
open,
onClose,
plan,
}: {
open: boolean;
onClose: () => void;
plan: Plan;
}) {
const queryClient = useQueryClient();
const { push } = useToast();
const isTrainer = useIsTrainer();
const { data: traineesData } = useTrainees();
const { data: trainersData } = useMyTrainers();
const [busyId, setBusyId] = useState<string | null>(null);
const [error, setError] = useState('');
const sharedIds = new Set((plan.shares ?? []).map((s) => s.userId));
const trainees = (traineesData?.trainees ?? []).map((t) => t.user);
const trainers = trainersData?.trainers ?? [];
const hasSections = isTrainer || trainers.length > 0;
const toggle = async (userId: string, name: string) => {
setBusyId(userId);
setError('');
try {
if (sharedIds.has(userId)) {
await unsharePlan(plan.id, userId);
push(`Cofnięto udostępnienie: ${name}`, 'success');
} else {
await sharePlan(plan.id, userId);
push(`Udostępniono: ${name}`, 'success');
}
await queryClient.invalidateQueries({ queryKey: ['plans', plan.id] });
await queryClient.invalidateQueries({ queryKey: ['plans', 'shared-with-me'] });
} catch (e) {
setError(e instanceof Error ? e.message : 'Błąd');
} finally {
setBusyId(null);
}
};
const section = (
title: string,
users: {
id: string;
firstName: string | null;
lastName: string | null;
nickname?: string | null;
}[],
) => (
<div>
<p className="mb-2 text-[0.875rem] font-semibold">{title}</p>
<div className="flex flex-col gap-1.5">
{users.map((u) => {
const checked = sharedIds.has(u.id);
return (
<label
key={u.id}
className="flex cursor-pointer items-center gap-2.5 rounded-[10px] border border-line bg-input px-3 py-2.5 transition-colors hover:border-accent/55"
>
<input
type="checkbox"
checked={checked}
disabled={busyId === u.id}
onChange={() => void toggle(u.id, userName(u))}
className="h-4 w-4 accent-accent cursor-pointer disabled:opacity-50"
/>
<span className="text-[0.9rem]">{userName(u)}</span>
{busyId === u.id && <span className="ml-auto text-dim text-[0.8rem]">…</span>}
</label>
);
})}
</div>
</div>
);
return (
<Modal open={open} onClose={onClose} title="Udostępnij plan">
<p className="mb-4 text-dim text-[0.9rem]">
Udostępnij plan osobom, z którymi masz aktywną relację coaching — odbiorca widzi plan w
trybie tylko do odczytu.
</p>
{error && <ErrorText>{error}</ErrorText>}
{!hasSections ? (
<p className="text-dim text-[0.9rem]">
Nie masz aktywnych relacji coaching (ani podopiecznych, ani trenerów) — nie ma komu
udostępnić planu.
</p>
) : (
<div className="flex flex-col gap-4">
{isTrainer && trainees.length > 0 && section('Moje podopieczne', trainees)}
{trainers.length > 0 && section('Moje trenerki/trenerzy', trainers)}
{isTrainer && trainees.length === 0 && trainers.length === 0 && (
<p className="text-dim text-[0.9rem]">Brak aktywnych relacji coaching.</p>
)}
</div>
)}
<div className="mt-5 flex justify-end">
<Button variant="secondary" onClick={onClose}>
Zamknij
</Button>
</div>
</Modal>
);
}