diff --git a/app/api/milestones/calendar/route.ts b/app/api/milestones/calendar/route.ts new file mode 100644 index 0000000..b7d5e26 --- /dev/null +++ b/app/api/milestones/calendar/route.ts @@ -0,0 +1,117 @@ +export const dynamic = 'force-dynamic' + +import { NextRequest, NextResponse } from 'next/server' +import { withAuth } from '@/lib/auth/middleware' +import { sql } from '@/lib/db' + +export interface CalendarMilestone { + id: string + title: string + description: string | null + amount: string + currency: string + due_date: string + status: 'pending' | 'in_progress' | 'submitted' | 'approved' | 'rejected' | 'paid' + contract_id: string | null + contract_title: string | null + project_id: string | null + sort_order: number +} + +export const GET = withAuth(async (request: NextRequest, auth) => { + try { + const url = new URL(request.url) + const contractId = url.searchParams.get('contract_id') + const status = url.searchParams.get('status') + const startDate = url.searchParams.get('start_date') + const endDate = url.searchParams.get('end_date') + + // Resolve user id + const userRows = await sql` + SELECT id FROM users WHERE wallet_address = ${auth.walletAddress} LIMIT 1 + ` + if (userRows.length === 0) { + return NextResponse.json({ error: 'User not found', code: 'USER_NOT_FOUND' }, { status: 404 }) + } + const userId = userRows[0].id + + // Build dynamic query — fetch milestones for contracts where the user is client or freelancer. + // We always filter to milestones that have a due_date so they can be placed on the calendar. + const rows = await sql` + SELECT + m.id, + m.title, + m.description, + m.amount, + m.currency, + m.due_date, + m.status, + m.contract_id, + m.project_id, + m.sort_order, + j.title AS contract_title + FROM milestones m + LEFT JOIN contracts c ON c.id = m.contract_id + LEFT JOIN jobs j ON j.id = c.job_id + WHERE m.due_date IS NOT NULL + AND ( + c.client_id = ${userId} + OR c.freelancer_id = ${userId} + OR ( + m.contract_id IS NULL + AND m.project_id IN ( + SELECT id FROM projects WHERE client_id = ${userId} + ) + ) + ) + AND (${contractId}::text IS NULL OR m.contract_id = ${contractId}::integer) + AND (${status}::text IS NULL OR m.status = ${status}::text) + AND (${startDate}::date IS NULL OR m.due_date >= ${startDate}::date) + AND (${endDate}::date IS NULL OR m.due_date <= ${endDate}::date) + ORDER BY m.due_date ASC, m.sort_order ASC + ` + + const milestones: CalendarMilestone[] = rows.map((row: { + id: number | string + title: string + description: string | null + amount: string + currency: string + due_date: string + status: string + contract_id: number | string | null + contract_title: string | null + project_id: number | string | null + sort_order: number + }) => ({ + id: String(row.id), + title: row.title, + description: row.description, + amount: row.amount, + currency: row.currency, + due_date: new Date(row.due_date).toISOString(), + status: row.status as CalendarMilestone['status'], + contract_id: row.contract_id != null ? String(row.contract_id) : null, + contract_title: row.contract_title, + project_id: row.project_id != null ? String(row.project_id) : null, + sort_order: row.sort_order, + })) + + // Also return a list of unique contracts for the filter dropdown + const contractsForFilter = Array.from( + new Map( + milestones + .filter((m) => m.contract_id !== null) + .map((m) => [m.contract_id, { id: m.contract_id!, title: m.contract_title ?? `Contract #${m.contract_id}` }]) + ).values() + ) + + return NextResponse.json({ milestones, contracts: contractsForFilter }) + } catch (err) { + console.error('[GET /api/milestones/calendar]', err) + return NextResponse.json( + { error: 'Failed to fetch calendar milestones', code: 'CALENDAR_FETCH_FAILED' }, + { status: 500 } + ) + } +}) diff --git a/app/dashboard/calendar/page.tsx b/app/dashboard/calendar/page.tsx new file mode 100644 index 0000000..dc2204e --- /dev/null +++ b/app/dashboard/calendar/page.tsx @@ -0,0 +1,26 @@ +"use client"; + +import { Calendar } from "lucide-react"; +import { ContractMilestoneCalendar } from "@/components/dashboard/contract-milestone-calendar"; + +export default function MilestoneCalendarPage() { + return ( +
+
+ {/* Header */} +
+

+ + Milestone Calendar +

+

+ Track project milestones, deadlines, and deliverables across all your contracts. +

+
+ + {/* Calendar */} + +
+
+ ); +} diff --git a/components/dashboard/contract-milestone-calendar.tsx b/components/dashboard/contract-milestone-calendar.tsx new file mode 100644 index 0000000..8a1dc32 --- /dev/null +++ b/components/dashboard/contract-milestone-calendar.tsx @@ -0,0 +1,725 @@ +'use client' + +import * as React from 'react' +import { + format, + startOfMonth, + endOfMonth, + startOfWeek, + endOfWeek, + eachDayOfInterval, + isSameMonth, + isSameDay, + isToday, + isPast, + parseISO, + addMonths, + subMonths, + addWeeks, + subWeeks, + startOfDay, +} from 'date-fns' +import { + ChevronLeft, + ChevronRight, + Calendar, + Clock, + CheckCircle2, + AlertCircle, + XCircle, + DollarSign, + Loader2, + Filter, + X, +} from 'lucide-react' +import Link from 'next/link' + +import { Button } from '@/components/ui/button' +import { Badge } from '@/components/ui/badge' +import { Card } from '@/components/ui/card' +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs' +import { cn } from '@/lib/utils' +import { toast } from 'sonner' + +// ─── Types ────────────────────────────────────────────────────────────────── + +export type MilestoneStatus = + | 'pending' + | 'in_progress' + | 'submitted' + | 'approved' + | 'rejected' + | 'paid' + +export interface CalendarMilestone { + id: string + title: string + description: string | null + amount: string + currency: string + due_date: string + status: MilestoneStatus + contract_id: string | null + contract_title: string | null + project_id: string | null + sort_order: number +} + +interface ContractOption { + id: string + title: string +} + +type CalendarView = 'monthly' | 'weekly' + +// ─── Status Configuration ─────────────────────────────────────────────────── + +const STATUS_CONFIG: Record< + MilestoneStatus, + { + label: string + dotColor: string + badgeClass: string + icon: React.ComponentType> + } +> = { + pending: { + label: 'Pending', + dotColor: 'bg-muted-foreground', + badgeClass: 'bg-muted text-muted-foreground border-muted', + icon: Clock, + }, + in_progress: { + label: 'In Progress', + dotColor: 'bg-blue-500', + badgeClass: 'bg-blue-500/10 text-blue-600 border-blue-500/20', + icon: Clock, + }, + submitted: { + label: 'Submitted', + dotColor: 'bg-amber-500', + badgeClass: 'bg-amber-500/10 text-amber-600 border-amber-500/20', + icon: CheckCircle2, + }, + approved: { + label: 'Approved', + dotColor: 'bg-green-500', + badgeClass: 'bg-green-500/10 text-green-600 border-green-500/20', + icon: CheckCircle2, + }, + rejected: { + label: 'Rejected', + dotColor: 'bg-destructive', + badgeClass: 'bg-destructive/10 text-destructive border-destructive/20', + icon: XCircle, + }, + paid: { + label: 'Paid', + dotColor: 'bg-primary', + badgeClass: 'bg-primary/10 text-primary border-primary/20', + icon: DollarSign, + }, +} + +// ─── Helper ───────────────────────────────────────────────────────────────── + +function getMilestoneCategory( + milestone: CalendarMilestone +): 'overdue' | 'upcoming' | 'completed' { + const due = parseISO(milestone.due_date) + if (['approved', 'paid'].includes(milestone.status)) return 'completed' + if (isPast(startOfDay(due)) && !['approved', 'paid'].includes(milestone.status)) + return 'overdue' + return 'upcoming' +} + +function getMilestonesForDay( + milestones: CalendarMilestone[], + day: Date +): CalendarMilestone[] { + return milestones.filter((m) => isSameDay(parseISO(m.due_date), day)) +} + +// ─── Milestone Detail Dialog ───────────────────────────────────────────────── + +function MilestoneDetailDialog({ + milestone, + open, + onOpenChange, +}: { + milestone: CalendarMilestone | null + open: boolean + onOpenChange: (open: boolean) => void +}) { + if (!milestone) return null + + const cfg = STATUS_CONFIG[milestone.status] + const Icon = cfg.icon + const category = getMilestoneCategory(milestone) + + return ( + + + + + + Milestone Details + + + +
+ {/* Title & Status */} +
+

{milestone.title}

+ + + {cfg.label} + +
+ + {/* Description */} + {milestone.description && ( +

+ {milestone.description} +

+ )} + + {/* Meta grid */} +
+
+

Amount

+

+ ${parseFloat(milestone.amount).toLocaleString()} {milestone.currency} +

+
+
+

Due Date

+

+ {format(parseISO(milestone.due_date), 'MMM d, yyyy')} +

+
+ {milestone.contract_title && ( +
+

Contract

+

{milestone.contract_title}

+
+ )} +
+ + {/* Category banner */} + {category === 'overdue' && ( +
+ + This milestone is overdue. +
+ )} + {category === 'completed' && ( +
+ + This milestone has been completed. +
+ )} + + {/* Action */} +
+ +
+
+
+
+ ) +} + +// ─── Day Cell ──────────────────────────────────────────────────────────────── + +function DayCell({ + day, + currentMonth, + milestones, + onMilestoneClick, +}: { + day: Date + currentMonth: Date + milestones: CalendarMilestone[] + onMilestoneClick: (m: CalendarMilestone) => void +}) { + const isCurrentMonth = isSameMonth(day, currentMonth) + const isCurrentDay = isToday(day) + const dayMilestones = getMilestonesForDay(milestones, day) + + return ( +
+
+ {format(day, 'd')} +
+ +
+ {dayMilestones.slice(0, 3).map((m) => { + const cfg = STATUS_CONFIG[m.status] + const category = getMilestoneCategory(m) + return ( + + ) + })} + {dayMilestones.length > 3 && ( +

+ +{dayMilestones.length - 3} more +

+ )} +
+
+ ) +} + +// ─── Monthly View ──────────────────────────────────────────────────────────── + +function MonthlyView({ + currentDate, + milestones, + onMilestoneClick, +}: { + currentDate: Date + milestones: CalendarMilestone[] + onMilestoneClick: (m: CalendarMilestone) => void +}) { + const monthStart = startOfMonth(currentDate) + const monthEnd = endOfMonth(currentDate) + const calStart = startOfWeek(monthStart, { weekStartsOn: 0 }) + const calEnd = endOfWeek(monthEnd, { weekStartsOn: 0 }) + const days = eachDayOfInterval({ start: calStart, end: calEnd }) + const weekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] + + return ( +
+ {/* Week headers */} +
+ {weekDays.map((d) => ( +
+ {d} +
+ ))} +
+ {/* Day cells */} +
+ {days.map((day) => ( + + ))} +
+
+ ) +} + +// ─── Weekly View ───────────────────────────────────────────────────────────── + +function WeeklyView({ + currentDate, + milestones, + onMilestoneClick, +}: { + currentDate: Date + milestones: CalendarMilestone[] + onMilestoneClick: (m: CalendarMilestone) => void +}) { + const weekStart = startOfWeek(currentDate, { weekStartsOn: 0 }) + const weekEnd = endOfWeek(currentDate, { weekStartsOn: 0 }) + const days = eachDayOfInterval({ start: weekStart, end: weekEnd }) + + return ( +
+
+ {days.map((day) => { + const isCurrentDay = isToday(day) + const dayMilestones = getMilestonesForDay(milestones, day) + + return ( +
+ {/* Day header */} +
+

+ {format(day, 'EEE')} +

+
+ {format(day, 'd')} +
+
+ + {/* Milestones */} +
+ {dayMilestones.map((m) => { + const cfg = STATUS_CONFIG[m.status] + const Icon = cfg.icon + const category = getMilestoneCategory(m) + return ( + + ) + })} + {dayMilestones.length === 0 && ( +

+ No milestones +

+ )} +
+
+ ) + })} +
+
+ ) +} + +// ─── Main Component ────────────────────────────────────────────────────────── + +export function ContractMilestoneCalendar() { + const [view, setView] = React.useState('monthly') + const [currentDate, setCurrentDate] = React.useState(new Date()) + const [milestones, setMilestones] = React.useState([]) + const [contracts, setContracts] = React.useState([]) + const [filterContract, setFilterContract] = React.useState('all') + const [filterStatus, setFilterStatus] = React.useState('all') + const [isLoading, setIsLoading] = React.useState(true) + const [error, setError] = React.useState(null) + const [selectedMilestone, setSelectedMilestone] = + React.useState(null) + const [detailOpen, setDetailOpen] = React.useState(false) + + const fetchMilestones = React.useCallback(async () => { + setIsLoading(true) + setError(null) + try { + const token = + typeof window !== 'undefined' + ? localStorage.getItem('tc_dev_access_token') + : null + const headers: Record = token + ? { Authorization: `Bearer ${token}` } + : {} + + const params = new URLSearchParams() + if (filterContract && filterContract !== 'all') + params.set('contract_id', filterContract) + if (filterStatus && filterStatus !== 'all') + params.set('status', filterStatus) + + const res = await fetch(`/api/milestones/calendar?${params.toString()}`, { + headers, + credentials: 'include', + }) + + if (!res.ok) { + const data = await res.json().catch(() => ({})) + throw new Error(data?.error ?? 'Failed to load calendar data') + } + + const data = await res.json() + setMilestones(data.milestones ?? []) + setContracts(data.contracts ?? []) + } catch (err) { + const msg = + err instanceof Error ? err.message : 'Failed to load calendar data' + setError(msg) + toast.error(msg) + } finally { + setIsLoading(false) + } + }, [filterContract, filterStatus]) + + React.useEffect(() => { + fetchMilestones() + }, [fetchMilestones]) + + const handleMilestoneClick = (m: CalendarMilestone) => { + setSelectedMilestone(m) + setDetailOpen(true) + } + + const navigatePrev = () => { + if (view === 'monthly') setCurrentDate((d) => subMonths(d, 1)) + else setCurrentDate((d) => subWeeks(d, 1)) + } + + const navigateNext = () => { + if (view === 'monthly') setCurrentDate((d) => addMonths(d, 1)) + else setCurrentDate((d) => addWeeks(d, 1)) + } + + const goToToday = () => setCurrentDate(new Date()) + + const clearFilters = () => { + setFilterContract('all') + setFilterStatus('all') + } + + const hasFilters = filterContract !== 'all' || filterStatus !== 'all' + + const headerLabel = + view === 'monthly' + ? format(currentDate, 'MMMM yyyy') + : `Week of ${format(startOfWeek(currentDate, { weekStartsOn: 0 }), 'MMM d')} – ${format(endOfWeek(currentDate, { weekStartsOn: 0 }), 'MMM d, yyyy')}` + + // Summary counts + const overdue = milestones.filter( + (m) => getMilestoneCategory(m) === 'overdue' + ).length + const upcoming = milestones.filter( + (m) => getMilestoneCategory(m) === 'upcoming' + ).length + const completed = milestones.filter( + (m) => getMilestoneCategory(m) === 'completed' + ).length + + return ( +
+ {/* Summary cards */} +
+ +

Upcoming

+

{isLoading ? '–' : upcoming}

+
+ +

Overdue

+

{isLoading ? '–' : overdue}

+
+ +

Completed

+

{isLoading ? '–' : completed}

+
+
+ + {/* Controls */} +
+ {/* Navigation */} +
+ + + + {headerLabel} +
+ + {/* View toggle */} + setView(v as CalendarView)} + className="shrink-0" + > + + Monthly + Weekly + + +
+ + {/* Filters */} +
+ + + + + + + {hasFilters && ( + + )} +
+ + {/* Legend */} +
+
+ + Upcoming +
+
+ + Overdue +
+
+ + Completed +
+
+ + {/* Calendar body */} + {isLoading ? ( +
+ + Loading calendar… +
+ ) : error ? ( +
+ +

{error}

+ +
+ ) : milestones.length === 0 ? ( +
+ +

+ {hasFilters + ? 'No milestones match the current filters.' + : 'No milestones with due dates found.'} +

+ {hasFilters && ( + + )} +
+ ) : view === 'monthly' ? ( + + ) : ( + + )} + + {/* Milestone detail dialog */} + +
+ ) +} diff --git a/components/dashboard/index.ts b/components/dashboard/index.ts index 6def5cb..f947208 100644 --- a/components/dashboard/index.ts +++ b/components/dashboard/index.ts @@ -22,3 +22,9 @@ export { type MilestoneProgressMetrics, type MilestoneStateTransition, } from '@/lib/milestone-tracker' + +export { + ContractMilestoneCalendar, + type CalendarMilestone, + type MilestoneStatus, +} from './contract-milestone-calendar' diff --git a/components/dashboard/sidebar.tsx b/components/dashboard/sidebar.tsx index dd0e797..05a9368 100644 --- a/components/dashboard/sidebar.tsx +++ b/components/dashboard/sidebar.tsx @@ -14,6 +14,7 @@ import { MessageSquare, Banknote, ShieldCheck, + CalendarDays, } from 'lucide-react' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' @@ -54,6 +55,11 @@ const navItems = [ href: '/dashboard/messages', icon: MessageSquare, }, + { + label: 'Calendar', + href: '/dashboard/calendar', + icon: CalendarDays, + }, { label: 'Profile', href: '/dashboard/profile',