Kanban board, Project Management, Proposals/Quotes, Time Tracking, Custom Fields
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:
2026-07-01 11:18:59 +02:00
parent 5d971dc749
commit 545065b527
38 changed files with 3770 additions and 4 deletions
+203
View File
@@ -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>
)
}
+234
View File
@@ -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>
)
}
+115
View File
@@ -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>
)
}