759 lines
22 KiB
TypeScript
759 lines
22 KiB
TypeScript
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||
import { api } from './client';
|
||
import { API_BASE } from '../config';
|
||
import type {
|
||
ActiveSession,
|
||
Availability,
|
||
CalendarDay,
|
||
Conversation,
|
||
ConversationThread,
|
||
Dashboard,
|
||
Equipment,
|
||
ExerciseComment,
|
||
ExerciseProgress,
|
||
FocusArea,
|
||
FocusChain,
|
||
HistorySession,
|
||
Gym,
|
||
GymDetailResponse,
|
||
GymException,
|
||
GymRole,
|
||
Message,
|
||
Plan,
|
||
Exercise,
|
||
Session,
|
||
User,
|
||
GymMembership,
|
||
WeightPoint,
|
||
CircumferenceSeries,
|
||
Invitation,
|
||
GymClaim,
|
||
GymInvitation,
|
||
GymKind,
|
||
VirtualGym,
|
||
Trainee,
|
||
TraineeDetail,
|
||
TraineeReport,
|
||
DayMoveEntry,
|
||
UserSearchResult,
|
||
LatestExerciseResult,
|
||
} from './types';
|
||
|
||
/** Pełny adres URL zdjęcia siłowni (url = `/gyms/:id/photos/:photoId`). */
|
||
export const gymPhotoSrc = (url: string): string => `${API_BASE}${url}`;
|
||
|
||
// ---------- me / profile ----------
|
||
export function useMe() {
|
||
return useQuery({
|
||
queryKey: ['me'],
|
||
queryFn: () => api<{ user: User; memberships: GymMembership[] }>('/me'),
|
||
});
|
||
}
|
||
|
||
export function useBodyParameters() {
|
||
return useQuery({
|
||
queryKey: ['me', 'body-parameters'],
|
||
queryFn: () =>
|
||
api<{ weight: WeightPoint[]; circumferences: CircumferenceSeries[] }>('/me/body-parameters'),
|
||
});
|
||
}
|
||
|
||
export function updateProfile(body: Record<string, unknown>) {
|
||
return api<{ user: User }>('/me', { method: 'PATCH', body });
|
||
}
|
||
|
||
/** `YYYY-MM-DD` (z pola date) → ISO; puste = API używa bieżącej daty. */
|
||
function toIsoDate(date: string | undefined): string | undefined {
|
||
return date ? new Date(`${date}T00:00:00Z`).toISOString() : undefined;
|
||
}
|
||
|
||
export function addWeight(value: number, date?: string) {
|
||
const iso = toIsoDate(date);
|
||
return api('/me/body-parameters/weight', {
|
||
method: 'POST',
|
||
body: { value, ...(iso ? { date: iso } : {}) },
|
||
});
|
||
}
|
||
|
||
export function addCircumference(name: string, value: number, date?: string) {
|
||
const iso = toIsoDate(date);
|
||
return api('/me/body-parameters/circumference', {
|
||
method: 'POST',
|
||
body: { name, value, ...(iso ? { date: iso } : {}) },
|
||
});
|
||
}
|
||
|
||
export function removeWeightPoint(id: string) {
|
||
return api(`/me/body-parameters/weight/${id}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function removeCircumferencePoint(id: string) {
|
||
return api(`/me/body-parameters/circumference/${id}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function useHistory() {
|
||
return useQuery({
|
||
queryKey: ['me', 'history'],
|
||
queryFn: () => api<{ sessions: HistorySession[] }>('/me/history'),
|
||
});
|
||
}
|
||
|
||
// ---------- gyms ----------
|
||
export interface UserGym extends Gym {
|
||
roles: GymRole[];
|
||
}
|
||
|
||
export function useGyms() {
|
||
return useQuery({
|
||
queryKey: ['gyms'],
|
||
queryFn: () => api<{ gyms: UserGym[] }>('/gyms'),
|
||
});
|
||
}
|
||
|
||
export function useAllGyms() {
|
||
return useQuery({
|
||
queryKey: ['gyms', 'all'],
|
||
queryFn: () => api<{ gyms: Gym[] }>('/gyms/all'),
|
||
});
|
||
}
|
||
|
||
/** Publiczny detal siłowni (REAL widoczny dla każdego; VIRTUAL tylko dla menedżerów). */
|
||
export function useGymDetail(id: string | undefined) {
|
||
return useQuery({
|
||
queryKey: ['gym', id],
|
||
queryFn: () => api<GymDetailResponse>(`/gyms/${id}`),
|
||
enabled: !!id,
|
||
});
|
||
}
|
||
|
||
/** Dodaje zdjęcia do galerii siłowni REAL (multipart, pole `photos`). */
|
||
export function addGymPhotos(gymId: string, files: File[]) {
|
||
const form = new FormData();
|
||
for (const f of files) form.append('photos', f);
|
||
return api<{
|
||
gym: Gym & { photos: { id: string; url: string; order: number; createdAt: string }[] };
|
||
}>(`/gyms/${gymId}/photos`, { method: 'POST', body: form });
|
||
}
|
||
|
||
export function deleteGymPhoto(gymId: string, photoId: string) {
|
||
return api(`/gyms/${gymId}/photos/${encodeURIComponent(photoId)}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function setGymPhotoCover(gymId: string, photoId: string) {
|
||
return api(`/gyms/${gymId}/photos/${encodeURIComponent(photoId)}/cover`, { method: 'PATCH' });
|
||
}
|
||
|
||
export function joinGym(gymId: string) {
|
||
return api<{ membership: { gymId: string; name: string; roles: GymRole[] } }>(
|
||
`/gyms/${gymId}/join`,
|
||
{ method: 'POST' },
|
||
);
|
||
}
|
||
|
||
export function createGym(body: {
|
||
name: string;
|
||
location?: string | null;
|
||
availability?: Availability | null;
|
||
capacity?: number | null;
|
||
kind?: GymKind;
|
||
isPrivate?: boolean;
|
||
}) {
|
||
return api<{ gym: UserGym }>('/gyms', { method: 'POST', body });
|
||
}
|
||
|
||
/** Public virtual gyms (+ the caller's own private ones) with rating counts and claim status. */
|
||
export function useVirtualGyms() {
|
||
return useQuery({
|
||
queryKey: ['gyms', 'virtual'],
|
||
queryFn: () => api<{ gyms: VirtualGym[] }>('/gyms/virtual'),
|
||
});
|
||
}
|
||
|
||
/** Thumb vote on a public virtual gym (same vote again removes it). */
|
||
export function rateGym(gymId: string, vote: 'UP' | 'DOWN') {
|
||
return api<{ vote: 'UP' | 'DOWN' | null; up: number; down: number }>(`/gyms/${gymId}/rate`, {
|
||
method: 'POST',
|
||
body: { vote },
|
||
});
|
||
}
|
||
|
||
export function addGymEquipment(gymId: string, equipmentId: string, quantity = 1) {
|
||
return api<{ gym: Gym }>(`/gyms/${gymId}/equipment`, {
|
||
method: 'POST',
|
||
body: { equipmentId, quantity },
|
||
});
|
||
}
|
||
|
||
export function updateGymEquipmentQuantity(gymId: string, equipmentId: string, quantity: number) {
|
||
return api<{ gym: Gym }>(`/gyms/${gymId}/equipment/${encodeURIComponent(equipmentId)}`, {
|
||
method: 'PATCH',
|
||
body: { quantity },
|
||
});
|
||
}
|
||
|
||
export function removeGymEquipment(gymId: string, equipmentId: string) {
|
||
return api(`/gyms/${gymId}/equipment/${encodeURIComponent(equipmentId)}`, { method: 'DELETE' });
|
||
}
|
||
|
||
/** The user's gyms where they hold the OWNER role (for gym management). */
|
||
export function useOwnedGyms() {
|
||
const { data, ...rest } = useGyms();
|
||
const owned = (data?.gyms ?? []).filter((g) => g.roles.includes('OWNER'));
|
||
return { ...rest, data: { gyms: owned } };
|
||
}
|
||
|
||
export function updateGym(
|
||
gymId: string,
|
||
body: {
|
||
name?: string;
|
||
location?: string | null;
|
||
availability?: Availability | null;
|
||
capacity?: number | null;
|
||
isPrivate?: boolean;
|
||
},
|
||
) {
|
||
return api<{ gym: Gym }>(`/gyms/${gymId}`, { method: 'PATCH', body });
|
||
}
|
||
|
||
export function deleteGym(gymId: string) {
|
||
return api(`/gyms/${gymId}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function useGymExceptions(gymId: string) {
|
||
return useQuery({
|
||
queryKey: ['gym-exceptions', gymId],
|
||
queryFn: () => api<{ exceptions: GymException[] }>(`/gyms/${gymId}/exceptions`),
|
||
enabled: !!gymId,
|
||
});
|
||
}
|
||
|
||
export function createGymException(
|
||
gymId: string,
|
||
body: { date: string; availability: { start: string; end: string } | null },
|
||
) {
|
||
return api<{ exception: GymException }>(`/gyms/${gymId}/exceptions`, {
|
||
method: 'POST',
|
||
body,
|
||
});
|
||
}
|
||
|
||
export function deleteGymException(gymId: string, exceptionId: string) {
|
||
return api(`/gyms/${gymId}/exceptions/${encodeURIComponent(exceptionId)}`, { method: 'DELETE' });
|
||
}
|
||
|
||
// ---------- gym claims (verification / new real gym) ----------
|
||
export interface GymClaimInput {
|
||
/** Set = verification of that virtual gym; omit = claim for a NEW real gym. */
|
||
gymId?: string;
|
||
description: string;
|
||
companyName?: string;
|
||
nip?: string;
|
||
phone?: string;
|
||
email?: string;
|
||
/** Verification only: overrides gym.location on approval. */
|
||
address?: string;
|
||
/** New-real only: */
|
||
gymName?: string;
|
||
gymLocation?: string;
|
||
gymAvailability?: Availability | null;
|
||
gymCapacity?: number | null;
|
||
}
|
||
|
||
/** Create a gym claim (multipart). `files` optional (jpg/png/pdf, ≤5×5 MB). */
|
||
export function createGymClaim(data: GymClaimInput, files: File[] = []) {
|
||
const form = new FormData();
|
||
if (data.gymId) form.append('gymId', data.gymId);
|
||
form.append('description', data.description);
|
||
if (data.companyName) form.append('companyName', data.companyName);
|
||
if (data.nip) form.append('nip', data.nip);
|
||
if (data.phone) form.append('phone', data.phone);
|
||
if (data.email) form.append('email', data.email);
|
||
if (data.address) form.append('address', data.address);
|
||
if (data.gymName) form.append('gymName', data.gymName);
|
||
if (data.gymLocation) form.append('gymLocation', data.gymLocation);
|
||
if (data.gymAvailability) form.append('gymAvailability', JSON.stringify(data.gymAvailability));
|
||
if (data.gymCapacity != null) form.append('gymCapacity', String(data.gymCapacity));
|
||
for (const f of files) form.append('files', f);
|
||
return api<{ claim: GymClaim }>('/gyms/claims', { method: 'POST', body: form });
|
||
}
|
||
|
||
export function useMyGymClaims() {
|
||
return useQuery({
|
||
queryKey: ['gyms', 'claims'],
|
||
queryFn: () => api<{ claims: GymClaim[] }>('/gyms/claims'),
|
||
});
|
||
}
|
||
|
||
export function withdrawGymClaim(claimId: string) {
|
||
return api(`/gyms/claims/${encodeURIComponent(claimId)}`, { method: 'DELETE' });
|
||
}
|
||
|
||
// ---------- gym invitations (private virtual gyms) ----------
|
||
export function useGymInvitations() {
|
||
return useQuery({
|
||
queryKey: ['gym-invitations'],
|
||
queryFn: () => api<{ invitations: GymInvitation[] }>('/gyms/invitations'),
|
||
});
|
||
}
|
||
|
||
export function sendGymInvitation(gymId: string, userId: string) {
|
||
return api<{ invitation: GymInvitation }>('/gyms/invitations', {
|
||
method: 'POST',
|
||
body: { gymId, userId },
|
||
});
|
||
}
|
||
|
||
export function acceptGymInvitation(id: string) {
|
||
return api(`/gyms/invitations/${encodeURIComponent(id)}/accept`, { method: 'POST' });
|
||
}
|
||
|
||
export function declineGymInvitation(id: string) {
|
||
return api(`/gyms/invitations/${encodeURIComponent(id)}/decline`, { method: 'POST' });
|
||
}
|
||
|
||
export function withdrawGymInvitation(id: string) {
|
||
return api(`/gyms/invitations/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||
}
|
||
|
||
/** Search users to invite to a private virtual gym (owner only). */
|
||
export function useGymInviteeSearch(gymId: string, firstName: string, lastName: string) {
|
||
return useQuery({
|
||
queryKey: ['gym-invitee-search', gymId, firstName, lastName],
|
||
queryFn: () =>
|
||
api<{ users: UserSearchResult[] }>(
|
||
`/gyms/invitations/search?gymId=${encodeURIComponent(gymId)}&firstName=${encodeURIComponent(firstName)}&lastName=${encodeURIComponent(lastName)}`,
|
||
),
|
||
enabled: !!gymId && firstName.trim().length > 0 && lastName.trim().length > 0,
|
||
});
|
||
}
|
||
|
||
/** List the equipment (machine/device) catalog. */
|
||
export function useEquipment() {
|
||
return useQuery({
|
||
queryKey: ['equipment'],
|
||
queryFn: () => api<{ equipment: Equipment[] }>('/equipment'),
|
||
});
|
||
}
|
||
|
||
// ---------- exercises ----------
|
||
export function useExercises() {
|
||
return useQuery({
|
||
queryKey: ['exercises'],
|
||
queryFn: () => api<{ exercises: Exercise[] }>('/exercises'),
|
||
});
|
||
}
|
||
|
||
// ---------- focus areas (priorities/exclusions) ----------
|
||
export function useFocusAreas() {
|
||
return useQuery({
|
||
queryKey: ['focus-areas'],
|
||
queryFn: () => api<{ focusAreas: FocusArea[] }>('/focus-areas'),
|
||
});
|
||
}
|
||
|
||
export function useFocusChain() {
|
||
return useQuery({ queryKey: ['focus-chain'], queryFn: () => api<FocusChain>('/me/focus-chain') });
|
||
}
|
||
|
||
// ---------- plans ----------
|
||
export function usePlans() {
|
||
return useQuery({ queryKey: ['plans'], queryFn: () => api<{ plans: Plan[] }>('/plans') });
|
||
}
|
||
|
||
export function usePlan(id: string) {
|
||
return useQuery({
|
||
queryKey: ['plans', id],
|
||
queryFn: () => api<{ plan: Plan }>(`/plans/${id}`),
|
||
enabled: !!id,
|
||
});
|
||
}
|
||
|
||
export interface PlanSetInput {
|
||
index: number;
|
||
reps?: number | null;
|
||
loadKg?: number | null;
|
||
restSec?: number | null;
|
||
rir?: number | null;
|
||
difficulty?: number | null;
|
||
cardioBpm?: number | null;
|
||
timeSec?: number | null;
|
||
speed?: number | null;
|
||
}
|
||
|
||
export interface PlanExerciseInput {
|
||
exerciseId: string;
|
||
order: number;
|
||
sets: PlanSetInput[];
|
||
}
|
||
|
||
export interface PlanDayInput {
|
||
dayOfWeek: number;
|
||
exercises: PlanExerciseInput[];
|
||
}
|
||
|
||
export interface PlanWeekInput {
|
||
index: number;
|
||
/** Opcjonalny alias tygodnia (np. „Deload"); null = bez aliasu. */
|
||
customName?: string | null;
|
||
days: PlanDayInput[];
|
||
}
|
||
|
||
export interface PlanBody {
|
||
title: string;
|
||
weeksCount: number;
|
||
/** Informacyjna — siłownia planu; null/brak = bez siłowni. */
|
||
gymId?: string | null;
|
||
weeks: PlanWeekInput[];
|
||
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
|
||
startDate?: string;
|
||
}
|
||
|
||
export function createPlan(body: PlanBody) {
|
||
return api<{ plan: { id: string } }>('/plans', { method: 'POST', body });
|
||
}
|
||
|
||
export function updatePlan(id: string, body: Omit<PlanBody, 'startDate'>) {
|
||
return api(`/plans/${id}`, { method: 'PATCH', body });
|
||
}
|
||
|
||
export function deletePlan(id: string) {
|
||
return api(`/plans/${id}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function activatePlan(id: string, startDate: string) {
|
||
return api(`/plans/${id}/activate`, { method: 'POST', body: { startDate } });
|
||
}
|
||
|
||
export function abandonPlan(id: string) {
|
||
return api(`/plans/${id}/abandon`, { method: 'POST' });
|
||
}
|
||
|
||
export function completePlan(id: string) {
|
||
return api(`/plans/${id}/complete`, { method: 'POST' });
|
||
}
|
||
|
||
// ---------- sessions ----------
|
||
export function useSession(id: string) {
|
||
return useQuery({
|
||
queryKey: ['sessions', id],
|
||
queryFn: () => api<{ session: Session }>(`/sessions/${id}`),
|
||
enabled: !!id,
|
||
});
|
||
}
|
||
|
||
/** Aktywna (IN_PROGRESS) sesja użytkownika — null, gdy żadna nie trwa. */
|
||
export function useActiveSession() {
|
||
return useQuery({
|
||
queryKey: ['active-session'],
|
||
queryFn: () => api<{ session: ActiveSession | null }>('/me/active-session'),
|
||
});
|
||
}
|
||
|
||
export function startSession(dayId: string) {
|
||
return api<{ sessionId: string }>(`/days/${dayId}/sessions`, { method: 'POST' });
|
||
}
|
||
|
||
export function addSessionExercise(sessionId: string, exerciseId: string) {
|
||
return api<{ exerciseId: string }>(`/sessions/${sessionId}/exercises`, {
|
||
method: 'POST',
|
||
body: { exerciseId },
|
||
});
|
||
}
|
||
|
||
export function setSessionExerciseState(
|
||
exerciseId: string,
|
||
data: { hidden?: boolean; removed?: boolean },
|
||
) {
|
||
return api(`/sessions/exercises/${exerciseId}`, { method: 'PATCH', body: data });
|
||
}
|
||
|
||
export function addSessionSet(exerciseId: string) {
|
||
return api<{ setId: string }>(`/sessions/exercises/${exerciseId}/sets`, { method: 'POST' });
|
||
}
|
||
|
||
export function updateSessionSet(
|
||
setId: string,
|
||
data: {
|
||
reps?: number | null;
|
||
rir?: number | null;
|
||
difficulty?: number | null;
|
||
note?: string | null;
|
||
},
|
||
) {
|
||
return api(`/sessions/sets/${setId}`, { method: 'PATCH', body: data });
|
||
}
|
||
|
||
export function deleteSessionSet(setId: string) {
|
||
return api(`/sessions/sets/${setId}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function completeSession(sessionId: string) {
|
||
return api(`/sessions/${sessionId}/complete`, { method: 'POST' });
|
||
}
|
||
|
||
export function abandonSession(sessionId: string) {
|
||
return api(`/sessions/${sessionId}/abandon`, { method: 'POST' });
|
||
}
|
||
|
||
// ---------- dashboard / calendar ----------
|
||
export function useDashboard() {
|
||
return useQuery({ queryKey: ['dashboard'], queryFn: () => api<Dashboard>('/dashboard') });
|
||
}
|
||
|
||
// ---------- trainer / trainees ----------
|
||
/** True when the user holds the TRAINER role in at least one gym. */
|
||
export function useIsTrainer() {
|
||
const { data } = useMe();
|
||
return (data?.memberships ?? []).some((m) => m.roles.includes('TRAINER'));
|
||
}
|
||
|
||
export function useTrainees(gymId?: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', gymId ?? 'all'],
|
||
queryFn: () =>
|
||
api<{ trainees: Trainee[] }>(`/trainer/trainees${gymId ? `?gymId=${gymId}` : ''}`),
|
||
});
|
||
}
|
||
|
||
export function useTrainee(userId: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId],
|
||
queryFn: () => api<TraineeDetail>(`/trainer/trainees/${userId}`),
|
||
enabled: !!userId,
|
||
});
|
||
}
|
||
|
||
export function useTraineeHistory(userId: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId, 'history'],
|
||
queryFn: () => api<{ sessions: HistorySession[] }>(`/trainer/trainees/${userId}/history`),
|
||
enabled: !!userId,
|
||
});
|
||
}
|
||
|
||
export function useTraineeReport(userId: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId, 'report'],
|
||
queryFn: () => api<TraineeReport>(`/trainer/trainees/${userId}/report`),
|
||
enabled: !!userId,
|
||
});
|
||
}
|
||
|
||
export function useTraineeMoves(userId: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId, 'moves'],
|
||
queryFn: () => api<{ moves: DayMoveEntry[] }>(`/trainer/trainees/${userId}/moves`),
|
||
enabled: !!userId,
|
||
});
|
||
}
|
||
|
||
/** Kalendarz podopiecznego (dni aktywnego planu w miesiącu YYYY-MM). */
|
||
export function useTraineeCalendar(userId: string, month?: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId, 'calendar', month],
|
||
queryFn: () =>
|
||
api<{ month: string; days: CalendarDay[] }>(
|
||
`/trainer/trainees/${userId}/calendar${month ? `?month=${month}` : ''}`,
|
||
),
|
||
enabled: !!userId,
|
||
});
|
||
}
|
||
|
||
export function useTraineeSearch(firstName: string, lastName: string) {
|
||
return useQuery({
|
||
queryKey: ['trainee-search', firstName, lastName],
|
||
queryFn: () =>
|
||
api<{ users: UserSearchResult[] }>(
|
||
`/trainer/search?firstName=${encodeURIComponent(firstName)}&lastName=${encodeURIComponent(lastName)}`,
|
||
),
|
||
enabled: firstName.trim().length > 0 && lastName.trim().length > 0,
|
||
});
|
||
}
|
||
|
||
export function sendInvitation(userId: string) {
|
||
return api<{ coaching: { id: string } }>('/trainer/invitations', {
|
||
method: 'POST',
|
||
body: { userId },
|
||
});
|
||
}
|
||
|
||
export function archiveTrainee(userId: string) {
|
||
return api(`/trainer/trainees/${encodeURIComponent(userId)}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function useInvitations() {
|
||
return useQuery({
|
||
queryKey: ['invitations'],
|
||
queryFn: () => api<{ invitations: Invitation[] }>('/trainer/invitations'),
|
||
});
|
||
}
|
||
|
||
export function acceptInvitation(id: string) {
|
||
return api(`/trainer/invitations/${encodeURIComponent(id)}/accept`, { method: 'POST' });
|
||
}
|
||
|
||
export function declineInvitation(id: string) {
|
||
return api(`/trainer/invitations/${encodeURIComponent(id)}/decline`, { method: 'POST' });
|
||
}
|
||
|
||
export function withdrawInvitation(id: string) {
|
||
return api(`/trainer/invitations/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function useCalendar(month?: string) {
|
||
return useQuery({
|
||
queryKey: ['calendar', month],
|
||
queryFn: () =>
|
||
api<{ month: string; days: CalendarDay[] }>(`/calendar${month ? `?month=${month}` : ''}`),
|
||
});
|
||
}
|
||
|
||
// ---------- komunikator (messages) ----------
|
||
export function useConversations() {
|
||
return useQuery({
|
||
queryKey: ['conversations'],
|
||
queryFn: () => api<{ conversations: Conversation[] }>('/messages/conversations'),
|
||
refetchInterval: 30_000,
|
||
});
|
||
}
|
||
|
||
export function useMessages(coachingId: string) {
|
||
return useQuery({
|
||
queryKey: ['messages', coachingId],
|
||
queryFn: () => api<ConversationThread>(`/messages/conversations/${coachingId}`),
|
||
enabled: !!coachingId,
|
||
refetchInterval: 30_000,
|
||
});
|
||
}
|
||
|
||
export function sendMessage(
|
||
coachingId: string,
|
||
body: string,
|
||
attachment?: { sessionId?: string; sessionExerciseId?: string },
|
||
) {
|
||
return api<{ message: Message }>('/messages/conversations/' + coachingId, {
|
||
method: 'POST',
|
||
body: {
|
||
body,
|
||
...(attachment?.sessionId ? { sessionId: attachment.sessionId } : {}),
|
||
...(attachment?.sessionExerciseId ? { sessionExerciseId: attachment.sessionExerciseId } : {}),
|
||
},
|
||
});
|
||
}
|
||
|
||
export function deleteMessage(id: string) {
|
||
return api(`/messages/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||
}
|
||
|
||
// ---------- komentarze pod ćwiczeniami ----------
|
||
export function addTraineeComment(
|
||
userId: string,
|
||
data: { body: string; sessionId?: string; sessionExerciseId?: string },
|
||
) {
|
||
return api<{ comment: ExerciseComment }>(
|
||
`/trainer/trainees/${encodeURIComponent(userId)}/comments`,
|
||
{
|
||
method: 'POST',
|
||
body: data,
|
||
},
|
||
);
|
||
}
|
||
|
||
export function addMyComment(data: {
|
||
body: string;
|
||
sessionId: string;
|
||
sessionExerciseId?: string;
|
||
}) {
|
||
return api<{ comment: ExerciseComment }>('/me/comments', { method: 'POST', body: data });
|
||
}
|
||
|
||
/** Usuwa komentarz: scope 'me' → /me/comments/:id, { userId } → /trainer/trainees/:userId/comments/:id. */
|
||
export function deleteComment(commentId: string, scope: 'me' | { userId: string }) {
|
||
const path =
|
||
scope === 'me'
|
||
? `/me/comments/${encodeURIComponent(commentId)}`
|
||
: `/trainer/trainees/${encodeURIComponent(scope.userId)}/comments/${encodeURIComponent(commentId)}`;
|
||
return api(path, { method: 'DELETE' });
|
||
}
|
||
|
||
// ---------- postępy per ćwiczenie ----------
|
||
export function useExerciseProgress() {
|
||
return useQuery({
|
||
queryKey: ['me', 'exercise-progress'],
|
||
queryFn: () => api<{ exercises: ExerciseProgress[] }>('/me/exercise-progress'),
|
||
});
|
||
}
|
||
|
||
export function useTraineeExerciseProgress(userId: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId, 'exercise-progress'],
|
||
queryFn: () =>
|
||
api<{ exercises: ExerciseProgress[] }>(`/trainer/trainees/${userId}/exercise-progress`),
|
||
enabled: !!userId,
|
||
});
|
||
}
|
||
|
||
export function useTraineeLatestResults(userId: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId, 'exercise-latest'],
|
||
queryFn: () =>
|
||
api<{ results: LatestExerciseResult[] }>(`/trainer/trainees/${userId}/exercise-latest`),
|
||
enabled: !!userId,
|
||
});
|
||
}
|
||
|
||
// ---------- plany podopiecznego (trener) ----------
|
||
export function useTraineePlans(userId: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId, 'plans'],
|
||
queryFn: () => api<{ plans: Plan[] }>(`/trainer/trainees/${userId}/plans`),
|
||
enabled: !!userId,
|
||
});
|
||
}
|
||
|
||
export function useTraineePlan(userId: string, planId: string) {
|
||
return useQuery({
|
||
queryKey: ['trainees', userId, 'plans', planId],
|
||
queryFn: () => api<{ plan: Plan }>(`/trainer/trainees/${userId}/plans/${planId}`),
|
||
enabled: !!userId && !!planId,
|
||
});
|
||
}
|
||
|
||
export function createTraineePlan(userId: string, body: PlanBody) {
|
||
return api<{ plan: { id: string } }>(`/trainer/trainees/${userId}/plans`, {
|
||
method: 'POST',
|
||
body,
|
||
});
|
||
}
|
||
|
||
export function updateTraineePlan(
|
||
userId: string,
|
||
planId: string,
|
||
body: Omit<PlanBody, 'startDate'>,
|
||
) {
|
||
return api(`/trainer/trainees/${userId}/plans/${planId}`, { method: 'PATCH', body });
|
||
}
|
||
|
||
export function deleteTraineePlan(userId: string, planId: string) {
|
||
return api(`/trainer/trainees/${userId}/plans/${planId}`, { method: 'DELETE' });
|
||
}
|
||
|
||
export function activateTraineePlan(userId: string, planId: string, startDate: string) {
|
||
return api(`/trainer/trainees/${userId}/plans/${planId}/activate`, {
|
||
method: 'POST',
|
||
body: { startDate },
|
||
});
|
||
}
|
||
|
||
export function abandonTraineePlan(userId: string, planId: string) {
|
||
return api(`/trainer/trainees/${userId}/plans/${planId}/abandon`, { method: 'POST' });
|
||
}
|
||
|
||
export function completeTraineePlan(userId: string, planId: string) {
|
||
return api(`/trainer/trainees/${userId}/plans/${planId}/complete`, { method: 'POST' });
|
||
}
|
||
|
||
export function invalidateAll() {
|
||
return useQueryClient().invalidateQueries();
|
||
}
|