Kanban board, Project Management, Proposals/Quotes, Time Tracking, Custom Fields
Build & Auto-Repair / build (push) Has been cancelled
Build & Auto-Repair / build (push) Has been cancelled
- Kanban board with drag-and-drop per stage, colour-coded cards, score bars - Project Management with milestones, Gantt timeline, inline add milestone/task - Proposal/Quote builder with line items, VAT, terms, e-signature capture - Time Tracking with stopwatch, manual entry, hours-by-project chart - Custom Fields system: admin-defined fields per entity (leads/customers/ projects/opportunities) with drag-and-drop reordering in settings - Reusable CustomFieldsSection component for entity detail pages - Customers API endpoint - All builds pass with zero errors
This commit is contained in:
@@ -0,0 +1,254 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useCallback } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { PageHeader } from "@/components/shared/page-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { GripVertical, Plus, User, Building2, Mail, Phone, Hash } from "lucide-react"
|
||||
|
||||
interface KanbanLead {
|
||||
id: string
|
||||
company_name: string
|
||||
contact_name: string
|
||||
email: string
|
||||
phone: string
|
||||
score: number
|
||||
notes: string
|
||||
assigned_to: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
interface KanbanColumn {
|
||||
id: string
|
||||
name: string
|
||||
status: string
|
||||
sortOrder: number
|
||||
probability: number
|
||||
leads: KanbanLead[]
|
||||
}
|
||||
|
||||
const statusColors: Record<string, { header: string; border: string; dot: string }> = {
|
||||
open: { header: "bg-blue-500/10 border-blue-500/20", border: "border-blue-500/20", dot: "bg-blue-500" },
|
||||
contacted: { header: "bg-amber-500/10 border-amber-500/20", border: "border-amber-500/20", dot: "bg-amber-500" },
|
||||
pending: { header: "bg-purple-500/10 border-purple-500/20", border: "border-purple-500/20", dot: "bg-purple-500" },
|
||||
closed: { header: "bg-emerald-500/10 border-emerald-500/20", border: "border-emerald-500/20", dot: "bg-emerald-500" },
|
||||
ignored: { header: "bg-zinc-500/10 border-zinc-500/20", border: "border-zinc-500/20", dot: "bg-zinc-500" },
|
||||
}
|
||||
|
||||
const columnGradient: Record<string, string> = {
|
||||
open: "from-blue-500/5",
|
||||
contacted: "from-amber-500/5",
|
||||
pending: "from-purple-500/5",
|
||||
closed: "from-emerald-500/5",
|
||||
ignored: "from-zinc-500/5",
|
||||
}
|
||||
|
||||
export default function KanbanPage() {
|
||||
const router = useRouter()
|
||||
const [columns, setColumns] = useState<KanbanColumn[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [draggedLead, setDraggedLead] = useState<{ leadId: string; fromStatus: string } | null>(null)
|
||||
|
||||
const fetchKanban = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/leads/kanban")
|
||||
const data = await res.json()
|
||||
setColumns(data)
|
||||
} catch (e) {
|
||||
console.error("Failed to load kanban", e)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => { fetchKanban() }, [fetchKanban])
|
||||
|
||||
const handleDragStart = (leadId: string, status: string) => {
|
||||
setDraggedLead({ leadId, fromStatus: status })
|
||||
}
|
||||
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
const handleDrop = async (toStatus: string) => {
|
||||
if (!draggedLead || draggedLead.fromStatus === toStatus) {
|
||||
setDraggedLead(null)
|
||||
return
|
||||
}
|
||||
|
||||
setColumns((prev) => {
|
||||
const next = prev.map((col) => ({ ...col, leads: [...col.leads] }))
|
||||
const fromCol = next.find((c) => c.status === draggedLead.fromStatus)
|
||||
const toCol = next.find((c) => c.status === toStatus)
|
||||
if (!fromCol || !toCol) return prev
|
||||
const leadIdx = fromCol.leads.findIndex((l) => l.id === draggedLead.leadId)
|
||||
if (leadIdx === -1) return prev
|
||||
const [moved] = fromCol.leads.splice(leadIdx, 1)
|
||||
toCol.leads.unshift(moved)
|
||||
return next
|
||||
})
|
||||
|
||||
try {
|
||||
await fetch(`/api/leads/${draggedLead.leadId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ status: toStatus }),
|
||||
})
|
||||
} catch (e) {
|
||||
console.error("Failed to update lead status", e)
|
||||
fetchKanban()
|
||||
}
|
||||
setDraggedLead(null)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title="Kanban Board" description="Drag and drop leads to update their stage" />
|
||||
<div className="flex gap-4 overflow-x-auto pb-4">
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<div key={i} className="flex h-96 w-72 shrink-0 animate-pulse rounded-lg bg-muted" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader
|
||||
title="Kanban Board"
|
||||
description="Drag and drop leads between stages to update their status"
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={() => router.push("/leads")}>
|
||||
Table View
|
||||
</Button>
|
||||
<Button size="sm" onClick={() => router.push("/leads/new")}>
|
||||
<Plus className="mr-1.5 h-4 w-4" /> New Lead
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<div className="flex gap-4 overflow-x-auto pb-4" style={{ minHeight: "calc(100vh - 12rem)" }}>
|
||||
{columns.map((col) => {
|
||||
const colors = statusColors[col.status] || statusColors.open
|
||||
return (
|
||||
<div
|
||||
key={col.id}
|
||||
className="flex w-72 shrink-0 flex-col rounded-lg border bg-card"
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={() => handleDrop(col.status)}
|
||||
>
|
||||
<div className={`flex items-center justify-between rounded-t-lg border-b px-3 py-2.5 ${colors.header}`}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`h-2 w-2 rounded-full ${colors.dot}`} />
|
||||
<span className="text-sm font-semibold">{col.name}</span>
|
||||
<span className="text-xs text-muted-foreground">({col.leads.length})</span>
|
||||
</div>
|
||||
{col.probability > 0 && (
|
||||
<span className="text-xs text-muted-foreground">{col.probability}%</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-2 overflow-y-auto p-2">
|
||||
{col.leads.length === 0 && (
|
||||
<div className="flex h-20 items-center justify-center">
|
||||
<p className="text-xs text-muted-foreground">No leads</p>
|
||||
</div>
|
||||
)}
|
||||
{col.leads.map((lead) => (
|
||||
<LeadCard
|
||||
key={lead.id}
|
||||
lead={lead}
|
||||
status={col.status}
|
||||
onDragStart={handleDragStart}
|
||||
onClick={() => router.push(`/leads/${lead.id}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function LeadCard({
|
||||
lead,
|
||||
status,
|
||||
onDragStart,
|
||||
onClick,
|
||||
}: {
|
||||
lead: KanbanLead
|
||||
status: string
|
||||
onDragStart: (id: string, status: string) => void
|
||||
onClick: () => void
|
||||
}) {
|
||||
const initials = lead.contact_name
|
||||
?.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")
|
||||
.toUpperCase()
|
||||
|
||||
return (
|
||||
<Card
|
||||
draggable
|
||||
onDragStart={() => onDragStart(lead.id, status)}
|
||||
onClick={onClick}
|
||||
className="cursor-grab active:cursor-grabbing p-3 space-y-2 transition-shadow hover:shadow-md"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Avatar className="h-7 w-7 shrink-0">
|
||||
<AvatarFallback className="text-[10px]">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium truncate">{lead.contact_name}</p>
|
||||
{lead.company_name && (
|
||||
<p className="flex items-center gap-1 text-xs text-muted-foreground truncate">
|
||||
<Building2 className="h-3 w-3 shrink-0" />
|
||||
{lead.company_name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<GripVertical className="h-4 w-4 shrink-0 text-muted-foreground/40" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
{lead.email && (
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground truncate">
|
||||
<Mail className="h-3 w-3 shrink-0" />
|
||||
{lead.email}
|
||||
</p>
|
||||
)}
|
||||
{lead.phone && (
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground truncate">
|
||||
<Phone className="h-3 w-3 shrink-0" />
|
||||
{lead.phone}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{lead.score > 0 && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Hash className="h-3 w-3 text-muted-foreground/60" />
|
||||
<div className="flex h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="rounded-full transition-all"
|
||||
style={{
|
||||
width: `${lead.score}%`,
|
||||
backgroundColor:
|
||||
lead.score >= 70 ? "#22c55e" : lead.score >= 40 ? "#eab308" : "#ef4444",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-[11px] text-muted-foreground">{lead.score}</span>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import { useRouter } from "next/navigation"
|
||||
import { PageHeader } from "@/components/shared/page-header"
|
||||
import { LeadsTable } from "@/components/leads/leads-table"
|
||||
import { LeadsTableToolbar } from "@/components/leads/leads-table-toolbar"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Columns3 } from "lucide-react"
|
||||
import { Lead } from "@/types"
|
||||
|
||||
export default function LeadsPage() {
|
||||
@@ -36,7 +38,11 @@ export default function LeadsPage() {
|
||||
<PageHeader
|
||||
title="Leads"
|
||||
description="Manage and track your sales leads"
|
||||
/>
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={() => router.push("/leads/kanban")}>
|
||||
<Columns3 className="mr-1.5 h-4 w-4" /> Kanban
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<div className="rounded-lg border bg-card">
|
||||
<div className="p-4">
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useCallback } from "react"
|
||||
import { useParams, useRouter } from "next/navigation"
|
||||
import { PageHeader } from "@/components/shared/page-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
||||
import { CustomFieldsSection } from "@/components/shared/custom-fields-section"
|
||||
import {
|
||||
ArrowLeft, Calendar, User, Building2, DollarSign, Plus, CheckCircle2,
|
||||
Circle, Clock, AlertCircle, ChevronDown, ChevronRight, GripVertical,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
interface Milestone {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
sort_order: number
|
||||
status: string
|
||||
start_date: string
|
||||
due_date: string
|
||||
completed_at: string
|
||||
created_at: string
|
||||
tasks: Task[]
|
||||
}
|
||||
|
||||
interface Task {
|
||||
id: string
|
||||
title: string
|
||||
description: string
|
||||
status: string
|
||||
due_date: string
|
||||
completed_at: string
|
||||
assigned_to: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
const milestoneStatusConfig: Record<string, { icon: any; class: string; label: string }> = {
|
||||
pending: { icon: Circle, class: "text-zinc-400", label: "Pending" },
|
||||
in_progress: { icon: Clock, class: "text-blue-500", label: "In Progress" },
|
||||
completed: { icon: CheckCircle2, class: "text-emerald-500", label: "Completed" },
|
||||
cancelled: { icon: AlertCircle, class: "text-red-500", label: "Cancelled" },
|
||||
}
|
||||
|
||||
const taskStatusColors: Record<string, string> = {
|
||||
pending: "bg-zinc-500",
|
||||
in_progress: "bg-blue-500",
|
||||
completed: "bg-emerald-500",
|
||||
cancelled: "bg-red-500",
|
||||
}
|
||||
|
||||
export default function ProjectDetailPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const router = useRouter()
|
||||
const [project, setProject] = useState<any>(null)
|
||||
const [milestones, setMilestones] = useState<Milestone[]>([])
|
||||
const [statuses, setStatuses] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [expandedMilestones, setExpandedMilestones] = useState<Set<string>>(new Set())
|
||||
const [newMilestoneName, setNewMilestoneName] = useState("")
|
||||
const [addingMilestone, setAddingMilestone] = useState(false)
|
||||
const [newTaskInputs, setNewTaskInputs] = useState<Record<string, string>>({})
|
||||
|
||||
const fetchProject = useCallback(async () => {
|
||||
try {
|
||||
const [pRes, mRes, sRes] = await Promise.all([
|
||||
fetch(`/api/projects/${id}`),
|
||||
fetch(`/api/projects/${id}/milestones`),
|
||||
fetch("/api/project-statuses"),
|
||||
])
|
||||
setProject(await pRes.json())
|
||||
setMilestones(await mRes.json())
|
||||
setStatuses(await sRes.json())
|
||||
} catch (e) {
|
||||
console.error("Failed to load project", e)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [id])
|
||||
|
||||
useEffect(() => { fetchProject() }, [fetchProject])
|
||||
|
||||
const updateProjectStatus = async (statusId: string) => {
|
||||
await fetch(`/api/projects/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ statusId }),
|
||||
})
|
||||
fetchProject()
|
||||
}
|
||||
|
||||
const updateMilestoneStatus = async (milestoneId: string, status: string) => {
|
||||
await fetch(`/api/milestones/${milestoneId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ status }),
|
||||
})
|
||||
fetchProject()
|
||||
}
|
||||
|
||||
const addMilestone = async () => {
|
||||
if (!newMilestoneName.trim()) return
|
||||
setAddingMilestone(true)
|
||||
try {
|
||||
await fetch(`/api/projects/${id}/milestones`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: newMilestoneName.trim() }),
|
||||
})
|
||||
setNewMilestoneName("")
|
||||
fetchProject()
|
||||
} finally {
|
||||
setAddingMilestone(false)
|
||||
}
|
||||
}
|
||||
|
||||
const addTask = async (milestoneId: string) => {
|
||||
const title = newTaskInputs[milestoneId]?.trim()
|
||||
if (!title) return
|
||||
try {
|
||||
await fetch(`/api/tasks`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title,
|
||||
projectId: id,
|
||||
milestoneId,
|
||||
}),
|
||||
})
|
||||
setNewTaskInputs((prev) => ({ ...prev, [milestoneId]: "" }))
|
||||
fetchProject()
|
||||
} catch (e) {
|
||||
console.error("Failed to add task", e)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleMilestone = (msId: string) => {
|
||||
setExpandedMilestones((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(msId)) next.delete(msId)
|
||||
else next.add(msId)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const formatDate = (d: string) => d ? new Date(d).toLocaleDateString() : "—"
|
||||
const formatCurrency = (n: number) => n ? `R${Number(n).toLocaleString()}` : ""
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="h-10 w-48 animate-pulse rounded bg-muted" />
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{[1, 2, 3].map((i) => <div key={i} className="h-24 animate-pulse rounded-lg bg-muted" />)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!project) return <div className="p-8 text-center text-muted-foreground">Project not found</div>
|
||||
|
||||
const now = new Date()
|
||||
const start = project.start_date ? new Date(project.start_date) : now
|
||||
const end = project.target_end_date ? new Date(project.target_end_date) : new Date(start.getTime() + 60 * 86400000)
|
||||
const totalDays = Math.max(1, (end.getTime() - start.getTime()) / 86400000)
|
||||
|
||||
const completedMilestones = milestones.filter((m) => m.status === "completed").length
|
||||
const progress = milestones.length ? Math.round((completedMilestones / milestones.length) * 100) : 0
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader title={project.name} description={`Project · ${project.company_name}`}>
|
||||
<Button variant="outline" size="sm" onClick={() => router.push("/projects")}>
|
||||
<ArrowLeft className="mr-1.5 h-4 w-4" /> Back
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
{/* Overview Cards */}
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Card className="p-4 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Customer</p>
|
||||
<p className="flex items-center gap-1.5 text-sm font-medium"><Building2 className="h-4 w-4 text-muted-foreground" />{project.company_name}</p>
|
||||
</Card>
|
||||
<Card className="p-4 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Owner</p>
|
||||
<p className="flex items-center gap-1.5 text-sm font-medium"><User className="h-4 w-4 text-muted-foreground" />{project.owner_name}</p>
|
||||
</Card>
|
||||
<Card className="p-4 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Timeline</p>
|
||||
<p className="flex items-center gap-1.5 text-sm font-medium"><Calendar className="h-4 w-4 text-muted-foreground" />{formatDate(project.start_date)} — {formatDate(project.target_end_date)}</p>
|
||||
</Card>
|
||||
<Card className="p-4 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Budget</p>
|
||||
<p className="flex items-center gap-1.5 text-sm font-medium"><DollarSign className="h-4 w-4 text-muted-foreground" />{project.budget ? formatCurrency(project.budget) : "—"}</p>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Status & Progress */}
|
||||
<Card className="p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<p className="text-sm font-medium">Status</p>
|
||||
<Select value={project.status_id} onValueChange={updateProjectStatus}>
|
||||
<SelectTrigger className="h-8 w-[160px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{statuses.map((s) => (
|
||||
<SelectItem key={s.id} value={s.id}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full" style={{ backgroundColor: s.color }} />
|
||||
{s.name}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<p className="text-sm text-muted-foreground">{progress}% complete</p>
|
||||
<div className="h-2 w-32 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full rounded-full bg-primary transition-all"
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Gantt Chart */}
|
||||
<Card className="p-4">
|
||||
<p className="text-sm font-medium mb-3">Timeline</p>
|
||||
<div className="relative overflow-x-auto">
|
||||
<div className="min-w-[500px] space-y-2">
|
||||
{milestones.map((ms) => {
|
||||
const msStart = ms.start_date ? new Date(ms.start_date) : start
|
||||
const msEnd = ms.due_date ? new Date(ms.due_date) : end
|
||||
const left = Math.max(0, ((msStart.getTime() - start.getTime()) / 86400000) / totalDays * 100)
|
||||
const width = Math.max(3, ((msEnd.getTime() - msStart.getTime()) / 86400000) / totalDays * 100)
|
||||
const config = milestoneStatusConfig[ms.status] || milestoneStatusConfig.pending
|
||||
return (
|
||||
<div key={ms.id} className="flex items-center gap-3">
|
||||
<span className="w-48 text-xs truncate shrink-0">{ms.name}</span>
|
||||
<div className="relative flex-1 h-6">
|
||||
<div className="absolute inset-0 rounded bg-muted/30" />
|
||||
<div
|
||||
className={`absolute top-1 h-4 rounded transition-all ${config.class.replace("text-", "bg-").replace("500", "500/80")}`}
|
||||
style={{ left: `${left}%`, width: `${width}%`, backgroundColor: ms.status === "completed" ? "#22c55e" : ms.status === "in_progress" ? "#3b82f6" : ms.status === "cancelled" ? "#ef4444" : "#a1a1aa" }}
|
||||
>
|
||||
<span className="px-2 text-[10px] leading-4 text-white block truncate opacity-80">{ms.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Custom Fields */}
|
||||
{project.custom_fields && Object.keys(project.custom_fields).length > 0 && (
|
||||
<CustomFieldsSection
|
||||
entityType="project"
|
||||
customFields={project.custom_fields}
|
||||
entityId={project.id}
|
||||
apiEndpoint={`/api/projects/${project.id}`}
|
||||
title="Custom Fields"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Milestones */}
|
||||
<Card className="divide-y">
|
||||
<div className="flex items-center justify-between px-4 py-3">
|
||||
<p className="text-sm font-medium">Milestones ({milestones.length})</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="New milestone name..."
|
||||
value={newMilestoneName}
|
||||
onChange={(e) => setNewMilestoneName(e.target.value)}
|
||||
className="h-8 w-56 text-sm"
|
||||
onKeyDown={(e) => e.key === "Enter" && addMilestone()}
|
||||
/>
|
||||
<Button size="sm" variant="outline" className="h-8" onClick={addMilestone} disabled={addingMilestone || !newMilestoneName.trim()}>
|
||||
<Plus className="h-3.5 w-3.5" /> Add
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{milestones.length === 0 && (
|
||||
<div className="p-8 text-center text-sm text-muted-foreground">No milestones yet</div>
|
||||
)}
|
||||
|
||||
{milestones.map((ms) => {
|
||||
const config = milestoneStatusConfig[ms.status] || milestoneStatusConfig.pending
|
||||
const isExpanded = expandedMilestones.has(ms.id)
|
||||
|
||||
return (
|
||||
<div key={ms.id}>
|
||||
<div
|
||||
className="flex items-center gap-3 px-4 py-3 hover:bg-muted/50 cursor-pointer transition-colors"
|
||||
onClick={() => toggleMilestone(ms.id)}
|
||||
>
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
{isExpanded ? <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" /> : <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />}
|
||||
<config.icon className={`h-4 w-4 ${config.class}`} />
|
||||
<span className="text-sm font-medium truncate">{ms.name}</span>
|
||||
<Badge variant="outline" className="text-[10px] h-5">{config.label}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground shrink-0">
|
||||
{ms.start_date && <span>{formatDate(ms.start_date)}</span>}
|
||||
{ms.start_date && ms.due_date && <span>→</span>}
|
||||
{ms.due_date && <span>{formatDate(ms.due_date)}</span>}
|
||||
</div>
|
||||
<Select
|
||||
value={ms.status}
|
||||
onValueChange={(v) => updateMilestoneStatus(ms.id, v)}
|
||||
>
|
||||
<SelectTrigger className="h-7 w-[110px] text-xs" onPointerDown={(e) => e.stopPropagation()}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="pending">Pending</SelectItem>
|
||||
<SelectItem value="in_progress">In Progress</SelectItem>
|
||||
<SelectItem value="completed">Completed</SelectItem>
|
||||
<SelectItem value="cancelled">Cancelled</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="border-t bg-muted/20 px-4 py-3 space-y-2">
|
||||
{ms.description && (
|
||||
<p className="text-xs text-muted-foreground">{ms.description}</p>
|
||||
)}
|
||||
{ms.tasks.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground">No tasks yet</p>
|
||||
)}
|
||||
{ms.tasks.map((task) => (
|
||||
<div key={task.id} className="flex items-center gap-2 pl-2">
|
||||
<span className={`h-2 w-2 rounded-full shrink-0 ${taskStatusColors[task.status] || "bg-zinc-400"}`} />
|
||||
<span className="text-xs flex-1">{task.title}</span>
|
||||
<span className="text-[10px] text-muted-foreground capitalize">{task.status.replace("_", " ")}</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<Input
|
||||
placeholder="Add task..."
|
||||
value={newTaskInputs[ms.id] || ""}
|
||||
onChange={(e) => setNewTaskInputs((prev) => ({ ...prev, [ms.id]: e.target.value }))}
|
||||
className="h-7 text-xs flex-1"
|
||||
onKeyDown={(e) => e.key === "Enter" && addTask(ms.id)}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 text-xs"
|
||||
onClick={() => addTask(ms.id)}
|
||||
disabled={!newTaskInputs[ms.id]?.trim()}
|
||||
>
|
||||
<Plus className="h-3 w-3 mr-1" /> Task
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { PageHeader } from "@/components/shared/page-header"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Search, Plus, Calendar, User, Building2, ArrowRight, DollarSign } from "lucide-react"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
interface Project {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
start_date: string
|
||||
target_end_date: string
|
||||
actual_end_date: string
|
||||
budget: number
|
||||
created_at: string
|
||||
status_name: string
|
||||
status_color: string
|
||||
customer_id: string
|
||||
company_name: string
|
||||
owner_id: string
|
||||
owner_name: string
|
||||
owner_avatar: string
|
||||
}
|
||||
|
||||
interface ProjectStatus {
|
||||
id: string
|
||||
name: string
|
||||
color: string
|
||||
sort_order: number
|
||||
}
|
||||
|
||||
export default function ProjectsPage() {
|
||||
const router = useRouter()
|
||||
const [projects, setProjects] = useState<Project[]>([])
|
||||
const [statuses, setStatuses] = useState<ProjectStatus[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
|
||||
const fetchProjects = async () => {
|
||||
try {
|
||||
const params = new URLSearchParams()
|
||||
if (search) params.set("search", search)
|
||||
if (statusFilter !== "all") params.set("status", statusFilter)
|
||||
const res = await fetch(`/api/projects?${params}`)
|
||||
setProjects(await res.json())
|
||||
} catch (e) {
|
||||
console.error("Failed to load projects", e)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { fetchProjects() }, [search, statusFilter])
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/project-statuses").then(r => r.json()).then(setStatuses).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const formatDate = (d: string) => d ? new Date(d).toLocaleDateString() : "—"
|
||||
const formatCurrency = (n: number) => n ? `R${Number(n).toLocaleString()}` : ""
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title="Projects" description="Track post-sale project delivery">
|
||||
<NewProjectDialog statuses={statuses} onCreated={() => fetchProjects()} />
|
||||
</PageHeader>
|
||||
|
||||
<Card>
|
||||
<div className="p-4">
|
||||
<div className="flex flex-1 flex-col gap-4 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search projects or companies..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="h-9 pl-9 w-full sm:max-w-sm"
|
||||
/>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="h-9 w-[160px]">
|
||||
<SelectValue placeholder="All Statuses" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Statuses</SelectItem>
|
||||
{statuses.map((s) => (
|
||||
<SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="divide-y">
|
||||
{loading ? (
|
||||
<div className="p-8 text-center text-muted-foreground">Loading...</div>
|
||||
) : projects.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">No projects yet</div>
|
||||
) : (
|
||||
projects.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="flex items-center gap-4 px-6 py-4 hover:bg-muted/50 cursor-pointer transition-colors"
|
||||
onClick={() => router.push(`/projects/${p.id}`)}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium truncate">{p.name}</span>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
style={{ borderColor: p.status_color + "40", color: p.status_color }}
|
||||
>
|
||||
{p.status_name}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 mt-1 text-sm text-muted-foreground">
|
||||
<span className="flex items-center gap-1"><Building2 className="h-3.5 w-3.5" />{p.company_name}</span>
|
||||
<span className="flex items-center gap-1"><User className="h-3.5 w-3.5" />{p.owner_name}</span>
|
||||
<span className="flex items-center gap-1"><Calendar className="h-3.5 w-3.5" />{formatDate(p.start_date)} — {formatDate(p.target_end_date)}</span>
|
||||
{p.budget > 0 && <span className="flex items-center gap-1"><DollarSign className="h-3.5 w-3.5" />{formatCurrency(p.budget)}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NewProjectDialog({ statuses, onCreated }: { statuses: ProjectStatus[]; onCreated: () => void }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [name, setName] = useState("")
|
||||
const [description, setDescription] = useState("")
|
||||
const [customerId, setCustomerId] = useState("")
|
||||
const [ownerId, setOwnerId] = useState("")
|
||||
const [startDate, setStartDate] = useState("")
|
||||
const [targetEndDate, setTargetEndDate] = useState("")
|
||||
const [budget, setBudget] = useState("")
|
||||
const [customers, setCustomers] = useState<any[]>([])
|
||||
const [users, setUsers] = useState<any[]>([])
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
fetch("/api/customers?limit=100").then(r => r.json()).then(setCustomers).catch(() => {})
|
||||
fetch("/api/users").then(r => r.json()).then(setUsers).catch(() => {})
|
||||
}, [open])
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!name || !customerId) return
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch("/api/projects", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
description,
|
||||
customerId,
|
||||
ownerId: ownerId || undefined,
|
||||
startDate: startDate || null,
|
||||
targetEndDate: targetEndDate || null,
|
||||
budget: budget ? parseFloat(budget) : null,
|
||||
}),
|
||||
})
|
||||
if (res.ok) {
|
||||
setOpen(false)
|
||||
setName(""); setDescription(""); setCustomerId(""); setOwnerId(""); setStartDate(""); setTargetEndDate(""); setBudget("")
|
||||
onCreated()
|
||||
}
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm"><Plus className="mr-1.5 h-4 w-4" />New Project</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create Project</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium">Project Name *</label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Website Redesign" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Customer *</label>
|
||||
<select
|
||||
value={customerId}
|
||||
onChange={(e) => setCustomerId(e.target.value)}
|
||||
className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"
|
||||
>
|
||||
<option value="">Select customer...</option>
|
||||
{customers.map((c: any) => (
|
||||
<option key={c.id} value={c.id}>{c.company_name || `${c.first_name} ${c.last_name}`}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Project Owner</label>
|
||||
<select
|
||||
value={ownerId}
|
||||
onChange={(e) => setOwnerId(e.target.value)}
|
||||
className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"
|
||||
>
|
||||
<option value="">Select owner...</option>
|
||||
{users.map((u: any) => (
|
||||
<option key={u.id} value={u.id}>{u.first_name} {u.last_name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium">Start Date</label>
|
||||
<Input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Target End Date</label>
|
||||
<Input type="date" value={targetEndDate} onChange={(e) => setTargetEndDate(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Budget (ZAR)</label>
|
||||
<Input type="number" value={budget} onChange={(e) => setBudget(e.target.value)} placeholder="e.g. 25000" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Description</label>
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
className="flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm"
|
||||
placeholder="Project scope and notes..."
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
|
||||
<Button onClick={handleSubmit} disabled={saving || !name || !customerId}>
|
||||
{saving ? "Creating..." : "Create Project"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useCallback } from "react"
|
||||
import { useParams, useRouter } from "next/navigation"
|
||||
import { PageHeader } from "@/components/shared/page-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ArrowLeft, FileText, CheckCircle2, Clock, User, Mail, Building2, Calendar } from "lucide-react"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
export default function ProposalDetailPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const router = useRouter()
|
||||
const [proposal, setProposal] = useState<any>(null)
|
||||
const [statuses, setStatuses] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [signName, setSignName] = useState("")
|
||||
const [signEmail, setSignEmail] = useState("")
|
||||
const [signing, setSigning] = useState(false)
|
||||
|
||||
const fetchProposal = useCallback(async () => {
|
||||
try {
|
||||
const [pRes, sRes] = await Promise.all([
|
||||
fetch(`/api/proposals/${id}`),
|
||||
fetch("/api/proposal-statuses"),
|
||||
])
|
||||
setProposal(await pRes.json())
|
||||
setStatuses(await sRes.json())
|
||||
} catch (e) {
|
||||
console.error("Failed to load proposal", e)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [id])
|
||||
|
||||
useEffect(() => { fetchProposal() }, [fetchProposal])
|
||||
|
||||
const updateStatus = async (statusId: string) => {
|
||||
await fetch(`/api/proposals/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ statusId }),
|
||||
})
|
||||
fetchProposal()
|
||||
}
|
||||
|
||||
const handleSign = async () => {
|
||||
if (!signName || !signEmail) return
|
||||
setSigning(true)
|
||||
try {
|
||||
const res = await fetch(`/api/proposals/${id}/sign`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: signName, email: signEmail }),
|
||||
})
|
||||
if (res.ok) fetchProposal()
|
||||
} finally {
|
||||
setSigning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const formatCurrency = (n: number) => n ? `R${Number(n).toLocaleString(undefined, { minimumFractionDigits: 2 })}` : "R0.00"
|
||||
const formatDate = (d: string) => d ? new Date(d).toLocaleDateString() : "—"
|
||||
|
||||
if (loading) return <div className="p-8 text-center text-muted-foreground">Loading...</div>
|
||||
if (!proposal) return <div className="p-8 text-center text-muted-foreground">Proposal not found</div>
|
||||
|
||||
const canSign = proposal.status_name === "Sent" || proposal.status_name === "Viewed"
|
||||
const isAccepted = proposal.status_name === "Accepted"
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-4xl">
|
||||
<PageHeader
|
||||
title={proposal.title}
|
||||
description={`${proposal.proposal_number} · Created by ${proposal.created_by_name}`}
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={() => router.push("/proposals")}>
|
||||
<ArrowLeft className="mr-1.5 h-4 w-4" /> Back
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
{/* Status bar */}
|
||||
<Card className="p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-medium">Status</span>
|
||||
<Select value={proposal.status_id} onValueChange={updateStatus}>
|
||||
<SelectTrigger className="h-8 w-[150px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{statuses.map((s: any) => (
|
||||
<SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Badge variant="outline" style={{ borderColor: proposal.status_color + "40", color: proposal.status_color }}>
|
||||
{proposal.status_name}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-sm text-muted-foreground">
|
||||
<span><Calendar className="h-3.5 w-3.5 inline mr-1" />Created {formatDate(proposal.created_at)}</span>
|
||||
{proposal.valid_until && <span>Valid until {formatDate(proposal.valid_until)}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Client info */}
|
||||
{(proposal.lead_company || proposal.company_name) && (
|
||||
<Card className="p-4">
|
||||
<p className="text-sm text-muted-foreground mb-1">Client</p>
|
||||
<p className="flex items-center gap-2">
|
||||
<Building2 className="h-4 w-4 text-muted-foreground" />
|
||||
{proposal.lead_company || proposal.company_name}
|
||||
</p>
|
||||
{proposal.lead_contact && <p className="text-sm text-muted-foreground ml-6">{proposal.lead_contact}</p>}
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Line Items */}
|
||||
<Card className="divide-y">
|
||||
<div className="px-4 py-3 font-medium text-sm">Services</div>
|
||||
{proposal.items?.length === 0 && (
|
||||
<div className="px-4 py-6 text-sm text-muted-foreground text-center">No items</div>
|
||||
)}
|
||||
{proposal.items?.map((item: any) => (
|
||||
<div key={item.id} className="flex items-center px-4 py-3 text-sm">
|
||||
<div className="flex-1">
|
||||
<p>{item.description}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{item.quantity} × {formatCurrency(item.unit_price)}
|
||||
{item.discount_percent > 0 && ` (${item.discount_percent}% off)`}
|
||||
</p>
|
||||
</div>
|
||||
<p className="font-medium">{formatCurrency(item.total_price)}</p>
|
||||
</div>
|
||||
))}
|
||||
</Card>
|
||||
|
||||
{/* Totals */}
|
||||
<Card className="p-4">
|
||||
<div className="ml-auto w-64 space-y-1 text-sm">
|
||||
<div className="flex justify-between"><span>Subtotal</span><span>{formatCurrency(proposal.subtotal)}</span></div>
|
||||
<div className="flex justify-between"><span>VAT ({proposal.tax_percent}%)</span><span>{formatCurrency(proposal.tax_amount)}</span></div>
|
||||
<div className="flex justify-between text-lg font-bold border-t pt-2"><span>Total</span><span>{formatCurrency(proposal.total_amount)}</span></div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Notes & Terms */}
|
||||
{proposal.notes && (
|
||||
<Card className="p-4">
|
||||
<p className="text-sm font-medium mb-1">Notes</p>
|
||||
<p className="text-sm text-muted-foreground whitespace-pre-wrap">{proposal.notes}</p>
|
||||
</Card>
|
||||
)}
|
||||
{proposal.terms && (
|
||||
<Card className="p-4">
|
||||
<p className="text-sm font-medium mb-1">Terms & Conditions</p>
|
||||
<p className="text-sm text-muted-foreground whitespace-pre-wrap">{proposal.terms}</p>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* E-Signature */}
|
||||
<Card className="p-6">
|
||||
<p className="text-sm font-medium mb-1">Digital Signature</p>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
{isAccepted ? "This proposal has been signed and accepted." : "Sign below to accept this proposal."}
|
||||
</p>
|
||||
|
||||
{proposal.signatures?.length > 0 && (
|
||||
<div className="mb-4 space-y-2">
|
||||
{proposal.signatures.map((sig: any) => (
|
||||
<div key={sig.id} className="flex items-center gap-2 text-sm">
|
||||
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
|
||||
<span className="font-medium">{sig.signatory_name}</span>
|
||||
<span className="text-muted-foreground">({sig.signatory_email})</span>
|
||||
<span className="text-muted-foreground text-xs">— {new Date(sig.signed_at).toLocaleString()}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canSign && (
|
||||
<div className="space-y-3 max-w-sm">
|
||||
<Input placeholder="Full Name" value={signName} onChange={(e) => setSignName(e.target.value)} />
|
||||
<Input placeholder="Email Address" type="email" value={signEmail} onChange={(e) => setSignEmail(e.target.value)} />
|
||||
<Button onClick={handleSign} disabled={signing || !signName || !signEmail}>
|
||||
{signing ? "Signing..." : <><CheckCircle2 className="mr-1.5 h-4 w-4" /> Accept & Sign</>}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { PageHeader } from "@/components/shared/page-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Plus, Trash2, ArrowLeft, FileText } from "lucide-react"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
interface LineItem {
|
||||
id: string
|
||||
description: string
|
||||
quantity: number
|
||||
unitPrice: number
|
||||
discountPercent: number
|
||||
totalPrice: number
|
||||
}
|
||||
|
||||
export default function NewProposalPage() {
|
||||
const router = useRouter()
|
||||
const [title, setTitle] = useState("")
|
||||
const [leadId, setLeadId] = useState("")
|
||||
const [customerId, setCustomerId] = useState("")
|
||||
const [validUntil, setValidUntil] = useState("")
|
||||
const [taxPercent, setTaxPercent] = useState(15)
|
||||
const [notes, setNotes] = useState("")
|
||||
const [terms, setTerms] = useState("Payment due within 30 days. 50% deposit required to commence work.")
|
||||
const [items, setItems] = useState<LineItem[]>([])
|
||||
const [leads, setLeads] = useState<any[]>([])
|
||||
const [customers, setCustomers] = useState<any[]>([])
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/leads?limit=100").then((r) => r.json()).then(setLeads).catch(() => {})
|
||||
fetch("/api/customers?limit=100").then((r) => r.json()).then(setCustomers).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const addItem = () => {
|
||||
setItems((prev) => [
|
||||
...prev,
|
||||
{ id: crypto.randomUUID(), description: "", quantity: 1, unitPrice: 0, discountPercent: 0, totalPrice: 0 },
|
||||
])
|
||||
}
|
||||
|
||||
const updateItem = (id: string, field: keyof LineItem, value: string | number) => {
|
||||
setItems((prev) =>
|
||||
prev.map((item) => {
|
||||
if (item.id !== id) return item
|
||||
const updated = { ...item, [field]: value }
|
||||
updated.totalPrice = updated.quantity * updated.unitPrice * (1 - updated.discountPercent / 100)
|
||||
return updated
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
const removeItem = (id: string) => {
|
||||
setItems((prev) => prev.filter((i) => i.id !== id))
|
||||
}
|
||||
|
||||
const subtotal = items.reduce((sum, i) => sum + i.totalPrice, 0)
|
||||
const taxAmount = subtotal * (taxPercent / 100)
|
||||
const total = subtotal + taxAmount
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!title) return
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch("/api/proposals", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title,
|
||||
leadId: leadId || null,
|
||||
customerId: customerId || null,
|
||||
subtotal,
|
||||
taxPercent,
|
||||
taxAmount,
|
||||
totalAmount: total,
|
||||
validUntil: validUntil || null,
|
||||
notes: notes || null,
|
||||
terms: terms || null,
|
||||
}),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!data.id) throw new Error("No id returned")
|
||||
|
||||
for (const item of items) {
|
||||
await fetch(`/api/proposals/${data.id}/items`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
description: item.description,
|
||||
quantity: item.quantity,
|
||||
unitPrice: item.unitPrice,
|
||||
discountPercent: item.discountPercent,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
router.push(`/proposals/${data.id}`)
|
||||
} catch (e) {
|
||||
console.error("Failed to create proposal", e)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const formatCurrency = (n: number) => `R${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-4xl">
|
||||
<PageHeader title="New Proposal" description="Create a professional quote for your client">
|
||||
<Button variant="outline" size="sm" onClick={() => router.push("/proposals")}>
|
||||
<ArrowLeft className="mr-1.5 h-4 w-4" /> Back
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<Card className="p-6 space-y-6">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label className="text-sm font-medium">Proposal Title *</label>
|
||||
<Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Website Redesign Quote" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Valid Until</label>
|
||||
<Input type="date" value={validUntil} onChange={(e) => setValidUntil(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Lead (optional)</label>
|
||||
<select value={leadId} onChange={(e) => setLeadId(e.target.value)} className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm">
|
||||
<option value="">Select lead...</option>
|
||||
{leads.map((l: any) => (
|
||||
<option key={l.id} value={l.id}>{l.contact_name || l.company_name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Customer (optional)</label>
|
||||
<select value={customerId} onChange={(e) => setCustomerId(e.target.value)} className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm">
|
||||
<option value="">Select customer...</option>
|
||||
{customers.map((c: any) => (
|
||||
<option key={c.id} value={c.id}>{c.company_name || `${c.first_name} ${c.last_name}`}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">VAT %</label>
|
||||
<Input type="number" value={taxPercent} onChange={(e) => setTaxPercent(parseFloat(e.target.value) || 0)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Line Items */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<label className="text-sm font-medium">Line Items</label>
|
||||
<Button size="sm" variant="outline" onClick={addItem}><Plus className="h-3.5 w-3.5 mr-1" /> Add Item</Button>
|
||||
</div>
|
||||
{items.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground py-4 text-center">No items yet. Click "Add Item" to add services or products.</p>
|
||||
)}
|
||||
{items.map((item) => (
|
||||
<div key={item.id} className="flex items-start gap-3 mb-2 p-3 rounded-lg border bg-muted/20">
|
||||
<div className="flex-1 space-y-2">
|
||||
<Input
|
||||
value={item.description}
|
||||
onChange={(e) => updateItem(item.id, "description", e.target.value)}
|
||||
placeholder="Service description..."
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<div className="w-20">
|
||||
<label className="text-[10px] text-muted-foreground">Qty</label>
|
||||
<Input type="number" min="1" value={item.quantity} onChange={(e) => updateItem(item.id, "quantity", parseInt(e.target.value) || 1)} className="h-7 text-xs" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="text-[10px] text-muted-foreground">Unit Price (ZAR)</label>
|
||||
<Input type="number" min="0" value={item.unitPrice} onChange={(e) => updateItem(item.id, "unitPrice", parseFloat(e.target.value) || 0)} className="h-7 text-xs" />
|
||||
</div>
|
||||
<div className="w-20">
|
||||
<label className="text-[10px] text-muted-foreground">Discount %</label>
|
||||
<Input type="number" min="0" max="100" value={item.discountPercent} onChange={(e) => updateItem(item.id, "discountPercent", parseFloat(e.target.value) || 0)} className="h-7 text-xs" />
|
||||
</div>
|
||||
<div className="w-28 text-right">
|
||||
<label className="text-[10px] text-muted-foreground">Total</label>
|
||||
<p className="text-sm font-medium pt-1">{formatCurrency(item.totalPrice)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 mt-5 shrink-0" onClick={() => removeItem(item.id)}>
|
||||
<Trash2 className="h-3.5 w-3.5 text-red-500" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Totals */}
|
||||
<div className="border-t pt-4">
|
||||
<div className="ml-auto w-64 space-y-1 text-sm">
|
||||
<div className="flex justify-between"><span>Subtotal</span><span>{formatCurrency(subtotal)}</span></div>
|
||||
<div className="flex justify-between"><span>VAT ({taxPercent}%)</span><span>{formatCurrency(taxAmount)}</span></div>
|
||||
<div className="flex justify-between text-base font-bold border-t pt-1"><span>Total</span><span>{formatCurrency(total)}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Notes & Terms */}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label className="text-sm font-medium">Notes</label>
|
||||
<textarea value={notes} onChange={(e) => setNotes(e.target.value)} className="flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm" placeholder="Additional notes for the client..." />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Terms & Conditions</label>
|
||||
<textarea value={terms} onChange={(e) => setTerms(e.target.value)} className="flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button variant="outline" onClick={() => router.push("/proposals")}>Cancel</Button>
|
||||
<Button onClick={handleSubmit} disabled={saving || !title}>
|
||||
{saving ? "Creating..." : <><FileText className="mr-1.5 h-4 w-4" /> Create Proposal</>}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { PageHeader } from "@/components/shared/page-header"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Search, Plus, ArrowRight, FileText, Calendar, User } from "lucide-react"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
export default function ProposalsPage() {
|
||||
const router = useRouter()
|
||||
const [proposals, setProposals] = useState<any[]>([])
|
||||
const [statuses, setStatuses] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams()
|
||||
if (search) params.set("search", search)
|
||||
if (statusFilter !== "all") params.set("status", statusFilter)
|
||||
fetch(`/api/proposals?${params}`)
|
||||
.then((r) => r.json())
|
||||
.then(setProposals)
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false))
|
||||
}, [search, statusFilter])
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/proposal-statuses").then((r) => r.json()).then(setStatuses).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const formatCurrency = (n: number) => n ? `R${Number(n).toLocaleString()}` : "R0"
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title="Proposals & Quotes" description="Create and send professional quotes to clients">
|
||||
<Button size="sm" onClick={() => router.push("/proposals/new")}>
|
||||
<Plus className="mr-1.5 h-4 w-4" /> New Proposal
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
<Card>
|
||||
<div className="p-4">
|
||||
<div className="flex flex-1 flex-col gap-4 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search proposals..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="h-9 pl-9 w-full sm:max-w-sm"
|
||||
/>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="h-9 w-[160px]">
|
||||
<SelectValue placeholder="All Statuses" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Statuses</SelectItem>
|
||||
{statuses.map((s: any) => (
|
||||
<SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="divide-y">
|
||||
{loading ? (
|
||||
<div className="p-8 text-center text-muted-foreground">Loading...</div>
|
||||
) : proposals.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">No proposals yet</div>
|
||||
) : (
|
||||
proposals.map((p: any) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="flex items-center gap-4 px-6 py-4 hover:bg-muted/50 cursor-pointer transition-colors"
|
||||
onClick={() => router.push(`/proposals/${p.id}`)}
|
||||
>
|
||||
<FileText className="h-5 w-5 text-muted-foreground shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium truncate">{p.title}</span>
|
||||
<Badge variant="outline" className="shrink-0 text-xs" style={{ borderColor: p.status_color + "40", color: p.status_color }}>
|
||||
{p.status_name}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 mt-1 text-sm text-muted-foreground">
|
||||
<span className="flex items-center gap-1"><User className="h-3.5 w-3.5" />{p.created_by_name}</span>
|
||||
<span>{p.proposal_number}</span>
|
||||
<span className="font-medium">{formatCurrency(p.total_amount)}</span>
|
||||
{p.valid_until && (
|
||||
<span className="flex items-center gap-1"><Calendar className="h-3.5 w-3.5" />Valid until {new Date(p.valid_until).toLocaleDateString()}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,7 +6,8 @@ import { CompanySettingsForm } from "@/components/settings/company-settings-form
|
||||
import { UserPreferencesForm } from "@/components/settings/user-preferences-form"
|
||||
import { ThemeSettings } from "@/components/settings/theme-settings"
|
||||
import { NotificationSettings } from "@/components/settings/notification-settings"
|
||||
import { Building2, User, Palette, Bell } from "lucide-react"
|
||||
import { CustomFieldsManager } from "@/components/settings/custom-fields-manager"
|
||||
import { Building2, User, Palette, Bell, ListChecks } from "lucide-react"
|
||||
|
||||
export default function SettingsPage() {
|
||||
const tabs = [
|
||||
@@ -14,6 +15,7 @@ export default function SettingsPage() {
|
||||
{ value: "preferences", label: "Preferences", icon: User, component: UserPreferencesForm },
|
||||
{ value: "theme", label: "Theme", icon: Palette, component: ThemeSettings },
|
||||
{ value: "notifications", label: "Notifications", icon: Bell, component: NotificationSettings },
|
||||
{ value: "custom-fields", label: "Custom Fields", icon: ListChecks, component: CustomFieldsManager },
|
||||
]
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useRef, useCallback } from "react"
|
||||
import { PageHeader } from "@/components/shared/page-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Play, Square, Plus, Trash2, Clock, Briefcase, User, TrendingUp, DollarSign } from "lucide-react"
|
||||
|
||||
interface TimeEntry {
|
||||
id: string
|
||||
description: string
|
||||
date: string
|
||||
duration_minutes: number
|
||||
billable: boolean
|
||||
hourly_rate: number
|
||||
user_name: string
|
||||
project_name: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export default function TimeTrackingPage() {
|
||||
const [entries, setEntries] = useState<TimeEntry[]>([])
|
||||
const [summary, setSummary] = useState<any>(null)
|
||||
const [projects, setProjects] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showManual, setShowManual] = useState(false)
|
||||
|
||||
// Manual entry form
|
||||
const [manualProject, setManualProject] = useState("")
|
||||
const [manualDesc, setManualDesc] = useState("")
|
||||
const [manualDate, setManualDate] = useState(new Date().toISOString().split("T")[0])
|
||||
const [manualHours, setManualHours] = useState("")
|
||||
const [manualMinutes, setManualMinutes] = useState("")
|
||||
const [manualBillable, setManualBillable] = useState(true)
|
||||
const [manualRate, setManualRate] = useState("")
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// Timer
|
||||
const [timerRunning, setTimerRunning] = useState(false)
|
||||
const [timerSeconds, setTimerSeconds] = useState(0)
|
||||
const [timerProject, setTimerProject] = useState("")
|
||||
const [timerDesc, setTimerDesc] = useState("")
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const startTimeRef = useRef<Date | null>(null)
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const [eRes, sRes, pRes] = await Promise.all([
|
||||
fetch("/api/time-entries"),
|
||||
fetch("/api/time-entries/summary"),
|
||||
fetch("/api/projects"),
|
||||
])
|
||||
setEntries(await eRes.json())
|
||||
setSummary(await sRes.json())
|
||||
setProjects(await pRes.json())
|
||||
} catch (e) {
|
||||
console.error("Failed to load time data", e)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => { fetchData() }, [fetchData])
|
||||
|
||||
const startTimer = () => {
|
||||
if (!timerDesc.trim()) return
|
||||
setTimerRunning(true)
|
||||
setTimerSeconds(0)
|
||||
startTimeRef.current = new Date()
|
||||
timerRef.current = setInterval(() => {
|
||||
setTimerSeconds((prev) => prev + 1)
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
const stopTimer = async () => {
|
||||
if (timerRef.current) clearInterval(timerRef.current)
|
||||
setTimerRunning(false)
|
||||
|
||||
if (timerSeconds < 60) return
|
||||
|
||||
try {
|
||||
await fetch("/api/time-entries", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
projectId: timerProject || null,
|
||||
description: timerDesc,
|
||||
date: new Date().toISOString().split("T")[0],
|
||||
startTime: startTimeRef.current?.toISOString(),
|
||||
endTime: new Date().toISOString(),
|
||||
durationMinutes: Math.round(timerSeconds / 60),
|
||||
billable: true,
|
||||
hourlyRate: null,
|
||||
}),
|
||||
})
|
||||
setTimerDesc("")
|
||||
setTimerProject("")
|
||||
setTimerSeconds(0)
|
||||
fetchData()
|
||||
} catch (e) {
|
||||
console.error("Failed to save time entry", e)
|
||||
}
|
||||
}
|
||||
|
||||
const addManualEntry = async () => {
|
||||
const hours = parseInt(manualHours) || 0
|
||||
const mins = parseInt(manualMinutes) || 0
|
||||
const totalMins = hours * 60 + mins
|
||||
if (totalMins <= 0 || !manualDesc.trim()) return
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
await fetch("/api/time-entries", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
projectId: manualProject || null,
|
||||
description: manualDesc,
|
||||
date: manualDate,
|
||||
durationMinutes: totalMins,
|
||||
billable: manualBillable,
|
||||
hourlyRate: manualRate ? parseFloat(manualRate) : null,
|
||||
}),
|
||||
})
|
||||
setManualDesc("")
|
||||
setManualHours("")
|
||||
setManualMinutes("")
|
||||
setManualRate("")
|
||||
setShowManual(false)
|
||||
fetchData()
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteEntry = async (id: string) => {
|
||||
await fetch(`/api/time-entries?id=${id}`, { method: "DELETE" })
|
||||
fetchData()
|
||||
}
|
||||
|
||||
const formatDuration = (mins: number) => {
|
||||
const h = Math.floor(mins / 60)
|
||||
const m = mins % 60
|
||||
return h > 0 ? `${h}h ${m}m` : `${m}m`
|
||||
}
|
||||
|
||||
const formatTimer = (secs: number) => {
|
||||
const h = Math.floor(secs / 3600)
|
||||
const m = Math.floor((secs % 3600) / 60)
|
||||
const s = secs % 60
|
||||
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`
|
||||
}
|
||||
|
||||
const formatCurrency = (n: number) => `R${Number(n).toLocaleString(undefined, { minimumFractionDigits: 2 })}`
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title="Time Tracking" description="Track billable hours" />
|
||||
<div className="grid gap-4 md:grid-cols-4">{[1, 2, 3, 4].map((i) => <div key={i} className="h-24 animate-pulse rounded-lg bg-muted" />)}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const t = summary?.totals || { total_minutes: 0, billable_minutes: 0, total_revenue: 0, entry_count: 0 }
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader title="Time Tracking" description="Track billable hours per project" />
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Card className="p-4 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Total Hours</p>
|
||||
<p className="text-2xl font-bold">{formatDuration(parseInt(t.total_minutes))}</p>
|
||||
</Card>
|
||||
<Card className="p-4 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Billable Hours</p>
|
||||
<p className="text-2xl font-bold">{formatDuration(parseInt(t.billable_minutes))}</p>
|
||||
</Card>
|
||||
<Card className="p-4 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Revenue</p>
|
||||
<p className="text-2xl font-bold">{formatCurrency(parseFloat(t.total_revenue))}</p>
|
||||
</Card>
|
||||
<Card className="p-4 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Entries</p>
|
||||
<p className="text-2xl font-bold">{t.entry_count}</p>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Timer */}
|
||||
<Card className="p-6">
|
||||
<p className="text-sm font-medium mb-3 flex items-center gap-2"><Clock className="h-4 w-4" /> Stopwatch</p>
|
||||
<div className="flex items-end gap-3">
|
||||
<div className="flex-1 space-y-2">
|
||||
<Input placeholder="What are you working on?" value={timerDesc} onChange={(e) => setTimerDesc(e.target.value)} className="h-9" disabled={timerRunning} />
|
||||
<select value={timerProject} onChange={(e) => setTimerProject(e.target.value)} className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm" disabled={timerRunning}>
|
||||
<option value="">No project</option>
|
||||
{projects.map((p: any) => <option key={p.id} value={p.id}>{p.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="text-3xl font-mono font-bold tabular-nums px-4 py-1">{formatTimer(timerSeconds)}</div>
|
||||
{!timerRunning ? (
|
||||
<Button onClick={startTimer} disabled={!timerDesc.trim()}><Play className="mr-1.5 h-4 w-4" /> Start</Button>
|
||||
) : (
|
||||
<Button variant="destructive" onClick={stopTimer}><Square className="mr-1.5 h-4 w-4" /> Stop</Button>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Manual Entry */}
|
||||
<Card className="p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<p className="text-sm font-medium">Manual Entry</p>
|
||||
<Button size="sm" variant="outline" onClick={() => setShowManual(!showManual)}>
|
||||
<Plus className="h-3.5 w-3.5 mr-1" /> {showManual ? "Cancel" : "Add Entry"}
|
||||
</Button>
|
||||
</div>
|
||||
{showManual && (
|
||||
<div className="space-y-3 p-3 rounded-lg border bg-muted/20">
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<Input placeholder="Description *" value={manualDesc} onChange={(e) => setManualDesc(e.target.value)} className="h-8 text-sm" />
|
||||
<select value={manualProject} onChange={(e) => setManualProject(e.target.value)} className="flex h-8 w-full rounded-md border border-input bg-transparent px-3 text-sm shadow-sm">
|
||||
<option value="">No project</option>
|
||||
{projects.map((p: any) => <option key={p.id} value={p.id}>{p.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex gap-3 flex-wrap">
|
||||
<Input type="date" value={manualDate} onChange={(e) => setManualDate(e.target.value)} className="h-8 w-40 text-sm" />
|
||||
<Input type="number" placeholder="Hours" value={manualHours} onChange={(e) => setManualHours(e.target.value)} className="h-8 w-24 text-sm" min="0" />
|
||||
<Input type="number" placeholder="Minutes" value={manualMinutes} onChange={(e) => setManualMinutes(e.target.value)} className="h-8 w-24 text-sm" min="0" />
|
||||
<Input type="number" placeholder="Rate (ZAR/hr)" value={manualRate} onChange={(e) => setManualRate(e.target.value)} className="h-8 w-32 text-sm" min="0" />
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={manualBillable} onChange={(e) => setManualBillable(e.target.checked)} className="rounded" />
|
||||
Billable
|
||||
</label>
|
||||
</div>
|
||||
<Button size="sm" onClick={addManualEntry} disabled={saving || !manualDesc.trim()}>
|
||||
{saving ? "Saving..." : "Save Entry"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Per-project summary */}
|
||||
{summary?.perProject?.length > 0 && (
|
||||
<Card className="p-4">
|
||||
<p className="text-sm font-medium mb-3 flex items-center gap-2"><Briefcase className="h-4 w-4" /> Hours by Project</p>
|
||||
<div className="space-y-2">
|
||||
{summary.perProject.map((p: any) => (
|
||||
<div key={p.id} className="flex items-center gap-3 text-sm">
|
||||
<span className="w-48 truncate">{p.name}</span>
|
||||
<div className="flex-1 h-2 rounded-full bg-muted overflow-hidden">
|
||||
<div className="h-full rounded-full bg-primary" style={{ width: `${Math.min(100, (parseInt(p.total_minutes) / parseInt(t.total_minutes)) * 100)}%` }} />
|
||||
</div>
|
||||
<span className="w-20 text-right">{formatDuration(parseInt(p.total_minutes))}</span>
|
||||
<span className="w-24 text-right text-muted-foreground">{formatCurrency(parseFloat(p.revenue))}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Recent Entries */}
|
||||
<Card className="divide-y">
|
||||
<div className="flex items-center justify-between px-4 py-3">
|
||||
<p className="text-sm font-medium">Recent Entries</p>
|
||||
</div>
|
||||
{entries.length === 0 && (
|
||||
<div className="p-8 text-center text-sm text-muted-foreground">No entries yet</div>
|
||||
)}
|
||||
{entries.map((entry) => (
|
||||
<div key={entry.id} className="flex items-center gap-3 px-4 py-3 text-sm hover:bg-muted/30">
|
||||
<span className={`h-2 w-2 rounded-full shrink-0 ${entry.billable ? "bg-emerald-500" : "bg-zinc-400"}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="truncate">{entry.description || "No description"}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{entry.project_name && <>{entry.project_name} · </>}
|
||||
{entry.user_name} · {new Date(entry.date).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
<span className="font-medium">{formatDuration(entry.duration_minutes)}</span>
|
||||
{entry.hourly_rate > 0 && <span className="text-muted-foreground w-20 text-right">{formatCurrency(entry.duration_minutes * entry.hourly_rate / 60)}</span>}
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => deleteEntry(entry.id)}>
|
||||
<Trash2 className="h-3.5 w-3.5 text-red-400" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user