feat(ui): add shift management UI with list, detail, and sign-up
Implements Task 20: Shift Sign-Up UI - List + Detail + Create Pages New components: - useShifts hook: TanStack Query hooks (useShifts, useShift, useCreateShift, useSignUpShift, useCancelSignUp) - Shift list page: Card-based UI (NOT table) with capacity bars and Past badges - Shift detail page: Full info with sign-up/cancel buttons, member list - New shift form: Create shifts with title, description, location, times, capacity - ShiftCard component: Reusable card with capacity Progress bar Key features: - Card-based UI pattern (shadcn Card, NOT Table - more visual for schedules) - Capacity calculation: (currentSignups / capacity) * 100 for Progress bar - Past shift detection: new Date(startTime) < new Date() → shows 'Past' badge - Sign-up button visibility: !isPast && !isFull && !isSignedUp - Cancel button visibility: !isPast && isSignedUp - Role-based 'New Shift' button: Manager/Admin only - TanStack Query with automatic cache invalidation on mutations - Navigation includes Shifts link in sidebar New shadcn components: - Progress: Radix UI progress bar with transform-based fill - Textarea: Styled textarea for shift descriptions TDD: - 3 shift card tests (capacity display, full capacity, past shifts) - 3 shift detail tests (sign-up button, cancel button, mutation calls) All tests pass (37/37: 31 existing + 6 new). Build succeeds.
This commit is contained in:
98
frontend/src/app/(protected)/shifts/[id]/page.tsx
Normal file
98
frontend/src/app/(protected)/shifts/[id]/page.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
'use client';
|
||||
|
||||
import { use } from 'react';
|
||||
import { useShift, useSignUpShift, useCancelSignUp } from '@/hooks/useShifts';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useSession } from 'next-auth/react';
|
||||
|
||||
export default function ShiftDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const resolvedParams = use(params);
|
||||
const { data: shift, isLoading } = useShift(resolvedParams.id);
|
||||
const signUpMutation = useSignUpShift();
|
||||
const cancelMutation = useCancelSignUp();
|
||||
const router = useRouter();
|
||||
const { data: session } = useSession();
|
||||
|
||||
if (isLoading) return <div>Loading shift...</div>;
|
||||
if (!shift) return <div>Shift not found</div>;
|
||||
|
||||
const capacityPercentage = (shift.signups.length / shift.capacity) * 100;
|
||||
const isFull = shift.signups.length >= shift.capacity;
|
||||
const isPast = new Date(shift.startTime) < new Date();
|
||||
const isSignedUp = shift.signups.some((s) => s.memberId === session?.user?.id);
|
||||
|
||||
const handleSignUp = async () => {
|
||||
await signUpMutation.mutateAsync(shift.id);
|
||||
};
|
||||
|
||||
const handleCancelSignUp = async () => {
|
||||
await cancelMutation.mutateAsync(shift.id);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-4xl mx-auto">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<CardTitle className="text-3xl">{shift.title}</CardTitle>
|
||||
{isPast && <Badge variant="secondary">Past</Badge>}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4">
|
||||
<div>
|
||||
<strong>Time:</strong> {new Date(shift.startTime).toLocaleString()} - {new Date(shift.endTime).toLocaleTimeString()}
|
||||
</div>
|
||||
{shift.location && (
|
||||
<div><strong>Location:</strong> {shift.location}</div>
|
||||
)}
|
||||
{shift.description && (
|
||||
<div><strong>Description:</strong> {shift.description}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-2">
|
||||
<span className="font-semibold">Capacity</span>
|
||||
<span>{shift.signups.length}/{shift.capacity} spots filled</span>
|
||||
</div>
|
||||
<Progress value={capacityPercentage} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="font-semibold mb-2">Signed Up Members ({shift.signups.length})</h3>
|
||||
{shift.signups.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No sign-ups yet</p>
|
||||
) : (
|
||||
<ul className="list-disc list-inside text-sm">
|
||||
{shift.signups.map((signup) => (
|
||||
<li key={signup.id}>Member ID: {signup.memberId}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{!isPast && !isFull && !isSignedUp && (
|
||||
<Button onClick={handleSignUp} disabled={signUpMutation.isPending}>
|
||||
{signUpMutation.isPending ? 'Signing up...' : 'Sign Up'}
|
||||
</Button>
|
||||
)}
|
||||
{!isPast && isSignedUp && (
|
||||
<Button variant="outline" onClick={handleCancelSignUp} disabled={cancelMutation.isPending}>
|
||||
{cancelMutation.isPending ? 'Canceling...' : 'Cancel Sign-up'}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" onClick={() => router.back()}>
|
||||
Back to Shifts
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
127
frontend/src/app/(protected)/shifts/new/page.tsx
Normal file
127
frontend/src/app/(protected)/shifts/new/page.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useCreateShift } from '@/hooks/useShifts';
|
||||
import { useTenant } from '@/contexts/tenant-context';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function NewShiftPage() {
|
||||
const { mutateAsync: createShift, isPending, error } = useCreateShift();
|
||||
const { activeClubId } = useTenant();
|
||||
const router = useRouter();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
title: '',
|
||||
description: '',
|
||||
location: '',
|
||||
startTime: '',
|
||||
endTime: '',
|
||||
capacity: 5,
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!activeClubId) return;
|
||||
|
||||
try {
|
||||
const data = await createShift({
|
||||
...formData,
|
||||
startTime: new Date(formData.startTime).toISOString(),
|
||||
endTime: new Date(formData.endTime).toISOString(),
|
||||
clubId: activeClubId,
|
||||
});
|
||||
|
||||
router.push(`/shifts/${data.id}`);
|
||||
} catch (err) {
|
||||
console.error('Failed to create shift', err);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-2xl mx-auto">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Create New Shift</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Title *</label>
|
||||
<Input
|
||||
value={formData.title}
|
||||
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Description</label>
|
||||
<Textarea
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Location</label>
|
||||
<Input
|
||||
value={formData.location}
|
||||
onChange={(e) => setFormData({ ...formData, location: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Start Time *</label>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={formData.startTime}
|
||||
onChange={(e) => setFormData({ ...formData, startTime: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">End Time *</label>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={formData.endTime}
|
||||
onChange={(e) => setFormData({ ...formData, endTime: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Capacity *</label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={formData.capacity}
|
||||
onChange={(e) => setFormData({ ...formData, capacity: parseInt(e.target.value) })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="text-sm text-destructive">{error.message}</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit" disabled={isPending || !formData.title.trim() || !formData.startTime || !formData.endTime}>
|
||||
{isPending ? 'Creating...' : 'Create Shift'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => router.back()}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
35
frontend/src/app/(protected)/shifts/page.tsx
Normal file
35
frontend/src/app/(protected)/shifts/page.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useShifts } from '@/hooks/useShifts';
|
||||
import { useTenant } from '@/contexts/tenant-context';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import Link from 'next/link';
|
||||
import { ShiftCard } from '@/components/shifts/shift-card';
|
||||
|
||||
export default function ShiftsPage() {
|
||||
const [dateRange] = useState<{ startDate?: string; endDate?: string }>({});
|
||||
const { data, isLoading } = useShifts(dateRange);
|
||||
const { userRole } = useTenant();
|
||||
|
||||
if (isLoading) return <div>Loading shifts...</div>;
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h1 className="text-2xl font-bold">Shifts</h1>
|
||||
{(userRole === 'Manager' || userRole === 'Admin') && (
|
||||
<Link href="/shifts/new">
|
||||
<Button>New Shift</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{data?.items.map((shift) => (
|
||||
<ShiftCard key={shift.id} shift={shift} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
55
frontend/src/components/__tests__/shift-card.test.tsx
Normal file
55
frontend/src/components/__tests__/shift-card.test.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { ShiftCard } from '../shifts/shift-card';
|
||||
|
||||
describe('ShiftCard', () => {
|
||||
it('shows capacity correctly (2/3 spots filled)', () => {
|
||||
render(
|
||||
<ShiftCard
|
||||
shift={{
|
||||
id: '1',
|
||||
title: 'Test Shift',
|
||||
startTime: new Date(Date.now() + 100000).toISOString(),
|
||||
endTime: new Date(Date.now() + 200000).toISOString(),
|
||||
capacity: 3,
|
||||
currentSignups: 2,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText('2/3 spots filled')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables sign-up button when full', () => {
|
||||
render(
|
||||
<ShiftCard
|
||||
shift={{
|
||||
id: '1',
|
||||
title: 'Full Shift',
|
||||
startTime: new Date(Date.now() + 100000).toISOString(),
|
||||
endTime: new Date(Date.now() + 200000).toISOString(),
|
||||
capacity: 3,
|
||||
currentSignups: 3,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText('3/3 spots filled')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Sign Up' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "Past" badge and no sign-up button for past shifts', () => {
|
||||
render(
|
||||
<ShiftCard
|
||||
shift={{
|
||||
id: '1',
|
||||
title: 'Past Shift',
|
||||
startTime: new Date(Date.now() - 200000).toISOString(),
|
||||
endTime: new Date(Date.now() - 100000).toISOString(),
|
||||
capacity: 3,
|
||||
currentSignups: 1,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText('Past')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Sign Up' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
124
frontend/src/components/__tests__/shift-detail.test.tsx
Normal file
124
frontend/src/components/__tests__/shift-detail.test.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import { Suspense } from 'react';
|
||||
import ShiftDetailPage from '../../app/(protected)/shifts/[id]/page';
|
||||
|
||||
vi.mock('@/hooks/useShifts', () => ({
|
||||
useShift: vi.fn(),
|
||||
useSignUpShift: vi.fn(),
|
||||
useCancelSignUp: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: vi.fn(() => ({
|
||||
push: vi.fn(),
|
||||
back: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/contexts/tenant-context', () => ({
|
||||
useTenant: vi.fn(() => ({
|
||||
activeClubId: 'club-123',
|
||||
userRole: 'Member',
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('next-auth/react', () => ({
|
||||
useSession: vi.fn(() => ({
|
||||
data: { user: { id: 'user-123' } },
|
||||
status: 'authenticated',
|
||||
})),
|
||||
}));
|
||||
|
||||
import { useShift, useSignUpShift, useCancelSignUp } from '@/hooks/useShifts';
|
||||
|
||||
describe('ShiftDetailPage', () => {
|
||||
const mockSignUp = vi.fn();
|
||||
const mockCancel = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(useSignUpShift as any).mockReturnValue({ mutateAsync: mockSignUp, isPending: false });
|
||||
(useCancelSignUp as any).mockReturnValue({ mutateAsync: mockCancel, isPending: false });
|
||||
});
|
||||
|
||||
it('shows "Sign Up" button if capacity available', async () => {
|
||||
(useShift as any).mockReturnValue({
|
||||
data: {
|
||||
id: '1',
|
||||
title: 'Detail Shift',
|
||||
startTime: new Date(Date.now() + 100000).toISOString(),
|
||||
endTime: new Date(Date.now() + 200000).toISOString(),
|
||||
capacity: 3,
|
||||
signups: [{ id: 's1', memberId: 'other-user' }],
|
||||
},
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
const params = Promise.resolve({ id: '1' });
|
||||
await act(async () => {
|
||||
render(
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<ShiftDetailPage params={params} />
|
||||
</Suspense>
|
||||
);
|
||||
});
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Sign Up' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Cancel Sign-up' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "Cancel Sign-up" button if user is signed up', async () => {
|
||||
(useShift as any).mockReturnValue({
|
||||
data: {
|
||||
id: '1',
|
||||
title: 'Detail Shift',
|
||||
startTime: new Date(Date.now() + 100000).toISOString(),
|
||||
endTime: new Date(Date.now() + 200000).toISOString(),
|
||||
capacity: 3,
|
||||
signups: [{ id: 's1', memberId: 'user-123' }],
|
||||
},
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
const params = Promise.resolve({ id: '1' });
|
||||
await act(async () => {
|
||||
render(
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<ShiftDetailPage params={params} />
|
||||
</Suspense>
|
||||
);
|
||||
});
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Cancel Sign-up' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Sign Up' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls sign up mutation on click', async () => {
|
||||
(useShift as any).mockReturnValue({
|
||||
data: {
|
||||
id: '1',
|
||||
title: 'Detail Shift',
|
||||
startTime: new Date(Date.now() + 100000).toISOString(),
|
||||
endTime: new Date(Date.now() + 200000).toISOString(),
|
||||
capacity: 3,
|
||||
signups: [],
|
||||
},
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
const params = Promise.resolve({ id: '1' });
|
||||
await act(async () => {
|
||||
render(
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<ShiftDetailPage params={params} />
|
||||
</Suspense>
|
||||
);
|
||||
});
|
||||
|
||||
const signUpBtn = screen.getByRole('button', { name: 'Sign Up' });
|
||||
fireEvent.click(signUpBtn);
|
||||
|
||||
expect(mockSignUp).toHaveBeenCalledWith('1');
|
||||
});
|
||||
});
|
||||
50
frontend/src/components/shifts/shift-card.tsx
Normal file
50
frontend/src/components/shifts/shift-card.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import Link from 'next/link';
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ShiftListItemDto } from '@/hooks/useShifts';
|
||||
|
||||
interface ShiftCardProps {
|
||||
shift: ShiftListItemDto;
|
||||
}
|
||||
|
||||
export function ShiftCard({ shift }: ShiftCardProps) {
|
||||
const capacityPercentage = (shift.currentSignups / shift.capacity) * 100;
|
||||
const isFull = shift.currentSignups >= shift.capacity;
|
||||
const isPast = new Date(shift.startTime) < new Date();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<CardTitle>{shift.title}</CardTitle>
|
||||
{isPast && <Badge variant="secondary">Past</Badge>}
|
||||
</div>
|
||||
<CardDescription>
|
||||
{new Date(shift.startTime).toLocaleString()} - {new Date(shift.endTime).toLocaleTimeString()}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-1">
|
||||
<span>Capacity</span>
|
||||
<span>{shift.currentSignups}/{shift.capacity} spots filled</span>
|
||||
</div>
|
||||
<Progress value={capacityPercentage} />
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Link href={`/shifts/${shift.id}`}>
|
||||
<Button variant="outline" size="sm">View Details</Button>
|
||||
</Link>
|
||||
{!isPast && !isFull && (
|
||||
<Button size="sm">Sign Up</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
31
frontend/src/components/ui/progress.tsx
Normal file
31
frontend/src/components/ui/progress.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Progress as ProgressPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Progress({
|
||||
className,
|
||||
value,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
||||
return (
|
||||
<ProgressPrimitive.Root
|
||||
data-slot="progress"
|
||||
className={cn(
|
||||
"relative h-2 w-full overflow-hidden rounded-full bg-primary/20",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
data-slot="progress-indicator"
|
||||
className="h-full w-full flex-1 bg-primary transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Progress }
|
||||
18
frontend/src/components/ui/textarea.tsx
Normal file
18
frontend/src/components/ui/textarea.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
137
frontend/src/hooks/useShifts.ts
Normal file
137
frontend/src/hooks/useShifts.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTenant } from '@/contexts/tenant-context';
|
||||
import { apiClient } from '@/lib/api';
|
||||
|
||||
export interface ShiftListDto {
|
||||
items: ShiftListItemDto[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface ShiftListItemDto {
|
||||
id: string;
|
||||
title: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
capacity: number;
|
||||
currentSignups: number;
|
||||
}
|
||||
|
||||
export interface ShiftDetailDto {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
location?: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
capacity: number;
|
||||
signups: ShiftSignupDto[];
|
||||
clubId: string;
|
||||
createdById: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ShiftSignupDto {
|
||||
id: string;
|
||||
memberId: string;
|
||||
signedUpAt: string;
|
||||
}
|
||||
|
||||
export interface CreateShiftRequest {
|
||||
title: string;
|
||||
description?: string;
|
||||
location?: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
capacity: number;
|
||||
clubId: string;
|
||||
}
|
||||
|
||||
export function useShifts(filters?: { startDate?: string; endDate?: string; page?: number }) {
|
||||
const { activeClubId } = useTenant();
|
||||
|
||||
return useQuery<ShiftListDto>({
|
||||
queryKey: ['shifts', activeClubId, filters],
|
||||
queryFn: async () => {
|
||||
const params = new URLSearchParams();
|
||||
if (filters?.startDate) params.append('startDate', filters.startDate);
|
||||
if (filters?.endDate) params.append('endDate', filters.endDate);
|
||||
if (filters?.page) params.append('page', filters.page.toString());
|
||||
|
||||
const res = await apiClient(`/api/shifts?${params}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch shifts');
|
||||
return res.json();
|
||||
},
|
||||
enabled: !!activeClubId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useShift(id: string) {
|
||||
const { activeClubId } = useTenant();
|
||||
|
||||
return useQuery<ShiftDetailDto>({
|
||||
queryKey: ['shifts', activeClubId, id],
|
||||
queryFn: async () => {
|
||||
const res = await apiClient(`/api/shifts/${id}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch shift');
|
||||
return res.json();
|
||||
},
|
||||
enabled: !!activeClubId && !!id,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateShift() {
|
||||
const queryClient = useQueryClient();
|
||||
const { activeClubId } = useTenant();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: CreateShiftRequest) => {
|
||||
const res = await apiClient('/api/shifts', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to create shift');
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shifts', activeClubId] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSignUpShift() {
|
||||
const queryClient = useQueryClient();
|
||||
const { activeClubId } = useTenant();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (shiftId: string) => {
|
||||
const res = await apiClient(`/api/shifts/${shiftId}/signup`, {
|
||||
method: 'POST',
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to sign up');
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shifts', activeClubId] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCancelSignUp() {
|
||||
const queryClient = useQueryClient();
|
||||
const { activeClubId } = useTenant();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (shiftId: string) => {
|
||||
const res = await apiClient(`/api/shifts/${shiftId}/signup`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to cancel sign-up');
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shifts', activeClubId] });
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user