mirror of
https://git.coastit.co.za/caitlin/CRM_ENVR.git
synced 2026-07-10 11:15:43 +02:00
Files Changed
Security Fixes
File Change
.env.local Placeholder JWT secret (rotate to random value: openssl rand -base64 64)
src/middleware.ts Removed /api/auth/me bypass; API routes return JSON 401 (not 302 redirect)
src/lib/auth.ts sameSite: "lax" → "strict" (create + destroy cookie); SVG name chars are pre-computed (no injection)
src/lib/avatar.ts Added sanitizeName() — strips non-alphanumeric/safe chars, max 50 chars
src/app/api/users/route.ts POST restricted to super_admin; validates role against whitelist ["sales","admin","super_admin","dev"]; validates active defaults to true
src/app/api/users/[id]/route.ts DELETE restricted to super_admin; blocks self-deletion
src/app/api/leads/[id]/route.ts GET: non-admin users filtered by assigned_to; PATCH: ownership check + score validated 0-100 range
src/app/api/leads/route.ts DELETE: ownership + admin check; GET: ownership filter for non-admin users
src/app/api/conversations/[id]/messages/route.ts GET/POST: verify user is a conversation_participant before access
rust-ai/src/main.rs CORS: AllowOrigin::list(["localhost:3006", "127.0.0.1:3006"]) (was Any)
Performance Fixes
File Change
src/app/api/leads/route.ts Added limit (default 50), offset query params; ownership filter in SQL
src/app/api/users/route.ts Added limit (default 50), offset query params
src/app/api/conversations/route.ts Added LIMIT 50
src/app/api/leads/[id]/notes/route.ts Added limit (default 50), offset query params
src/app/api/conversations/[id]/messages/route.ts Added limit (default 100), offset, before query params
src/app/(dashboard)/chats/page.tsx Pruned to 5 cached conversations; useMemo wraps messages/conversation/filteredConversations; otherParticipant moved outside component; added 10MB file size limit; recordingChunksRef cleared on discard
src/app/(dashboard)/leads/[id]/page.tsx Optimistic status update rolls back on fetch failure
database/migrations/003_chat.sql Added composite index idx_messages_conversation_created on (conversation_id, created_at DESC)
Code Quality Fixes
File Change
src/lib/ai.ts Removed dead getInstructions()/updateInstructions() (called nonexistent /ai/instructions)
src/lib/auth.ts bcrypt.hash(password, 12) — kept (acceptable, OWASP-recommended)
src/app/login/page.tsx "Forgot password?" button now shows alert to contact admin (was no-op)
src/components/users/user-form-dialog.tsx Password min 6 → 8 chars
26 silent catch {} blocks across 16 files (see below) Added console.warn("...") context messages
This commit is contained in:
@@ -32,11 +32,11 @@ export function AIChat() {
|
||||
.then((r) => r.json())
|
||||
.then((data) => {
|
||||
if (data.jobs?.length) {
|
||||
const jobNames = data.jobs.map((j: { job_title: string }) => j.job_title).join(", ")
|
||||
const names = data.jobs.map((j: { job_title: string }) => j.job_title)
|
||||
setMessages([
|
||||
{
|
||||
role: "assistant",
|
||||
content: `Hi! I'm your Sales AI Assistant. I can help you with tips for targeting: ${jobNames}. What would you like to know?`,
|
||||
content: `Hi! I'm your Sales AI Assistant. I can help with tips for targeting:\n\n${names.map((n: string) => `• ${n}`).join("\n")}\n\nWhat would you like to know?`,
|
||||
},
|
||||
])
|
||||
} else {
|
||||
@@ -56,41 +56,9 @@ export function AIChat() {
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
fetch("/api/ai/jobs")
|
||||
.then((r) => r.json())
|
||||
.then((data) => {
|
||||
if (data.jobs) {
|
||||
const names = data.jobs.map((j: { job_title: string }) => j.job_title)
|
||||
setMessages([
|
||||
{
|
||||
role: "assistant",
|
||||
content: `Hi! I'm your Sales AI Assistant. I can help with tips for targeting:\n\n${names.map((n: string) => `• ${n}`).join("\n")}\n\nWhat would you like to know?`,
|
||||
},
|
||||
])
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/ai/jobs")
|
||||
.then((r) => r.json())
|
||||
.then((data) => {
|
||||
if (data.jobs?.length) {
|
||||
const names = data.jobs.map((j: { job_title: string }) => j.job_title)
|
||||
setMessages((prev) =>
|
||||
prev.length === 1 && prev[0].role === "assistant"
|
||||
? [
|
||||
{
|
||||
role: "assistant",
|
||||
content: `Hi! I'm your Sales AI Assistant. I can help with tips for targeting:\n\n${names.map((n: string) => `• ${n}`).join("\n")}\n\nWhat would you like to know?`,
|
||||
},
|
||||
]
|
||||
: prev,
|
||||
)
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
|
||||
|
||||
@@ -37,7 +37,7 @@ export function LeadsPerMonthChart({ data: initialData }: LeadsPerMonthChartProp
|
||||
setChartData(data.leadsPerMonth || [])
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
console.warn("Failed to fetch year data in leads per month chart")
|
||||
}
|
||||
}
|
||||
const thisYear = new Date().getFullYear()
|
||||
|
||||
@@ -18,7 +18,7 @@ export function SystemMonitor() {
|
||||
setRssMB(data.rssMB)
|
||||
setCpuPct(data.cpuPct)
|
||||
} catch {
|
||||
// ignore
|
||||
console.warn("Failed to fetch system stats")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
} from "@/components/ui/select"
|
||||
import { Lead, LeadStatus, User } from "@/types"
|
||||
import { LEAD_SOURCES, LEAD_STATUSES } from "@/lib/constants"
|
||||
import { users } from "@/data/users"
|
||||
import { useNotifications } from "@/providers/notification-provider"
|
||||
|
||||
const leadFormSchema = z.object({
|
||||
@@ -52,11 +51,21 @@ interface LeadFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
lead?: Lead | null
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function LeadFormDialog({ open, onOpenChange, lead }: LeadFormDialogProps) {
|
||||
export function LeadFormDialog({ open, onOpenChange, lead, onSuccess }: LeadFormDialogProps) {
|
||||
const isEditing = !!lead
|
||||
const { addNotification } = useNotifications()
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/users")
|
||||
.then((r) => r.json())
|
||||
.then((data) => setUsers(data.users || []))
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
const form = useForm<LeadFormValues>({
|
||||
resolver: zodResolver(leadFormSchema),
|
||||
@@ -98,22 +107,37 @@ export function LeadFormDialog({ open, onOpenChange, lead }: LeadFormDialogProps
|
||||
}
|
||||
}, [lead, form])
|
||||
|
||||
function onSubmit(values: LeadFormValues) {
|
||||
const payload = {
|
||||
...values,
|
||||
assignedUserId: values.assignedUserId === "none" ? null : values.assignedUserId,
|
||||
async function onSubmit(values: LeadFormValues) {
|
||||
setSaving(true)
|
||||
try {
|
||||
const payload = {
|
||||
...values,
|
||||
assignedUserId: values.assignedUserId === "none" ? null : values.assignedUserId,
|
||||
}
|
||||
if (isEditing && lead) {
|
||||
const res = await fetch(`/api/leads/${lead.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
if (!res.ok) throw new Error("Failed to update")
|
||||
addNotification("lead_status_changed", "Lead Updated", `${values.companyName}`, "#")
|
||||
} else {
|
||||
const res = await fetch("/api/leads", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
if (!res.ok) throw new Error("Failed to create")
|
||||
addNotification("lead_created", "New Lead Created", `${values.companyName} — ${values.contactName}`, "#")
|
||||
}
|
||||
onOpenChange(false)
|
||||
onSuccess?.()
|
||||
} catch (e) {
|
||||
console.error("Lead save error:", e)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
if (!isEditing) {
|
||||
const now = new Date().toISOString()
|
||||
addNotification(
|
||||
"lead_created",
|
||||
"New Lead Created",
|
||||
`${values.companyName} — ${values.contactName}`,
|
||||
"#"
|
||||
)
|
||||
}
|
||||
console.log(payload)
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -277,7 +301,7 @@ export function LeadFormDialog({ open, onOpenChange, lead }: LeadFormDialogProps
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit">{isEditing ? "Save Changes" : "Create Lead"}</Button>
|
||||
<Button type="submit" disabled={saving}>{saving ? "Saving..." : isEditing ? "Save Changes" : "Create Lead"}</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -6,12 +6,15 @@ import { Button } from "@/components/ui/button"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
import { Send } from "lucide-react"
|
||||
import { useUser } from "@/providers/user-provider"
|
||||
|
||||
interface NoteFormProps {
|
||||
leadId: string
|
||||
onNoteAdded?: () => void
|
||||
}
|
||||
|
||||
export function NoteForm({ leadId }: NoteFormProps) {
|
||||
export function NoteForm({ leadId, onNoteAdded }: NoteFormProps) {
|
||||
const { user } = useUser()
|
||||
const [note, setNote] = useState("")
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
@@ -25,43 +28,53 @@ export function NoteForm({ leadId }: NoteFormProps) {
|
||||
body: JSON.stringify({ content: note }),
|
||||
})
|
||||
setNote("")
|
||||
window.location.reload()
|
||||
onNoteAdded?.()
|
||||
} catch {
|
||||
// ignore
|
||||
console.warn("Failed to add note")
|
||||
}
|
||||
setSubmitting(false)
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Add Note</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex gap-4">
|
||||
<Avatar className="h-10 w-10 shrink-0">
|
||||
<AvatarImage src="https://ui-avatars.com/api/?name=Sarah+Chen&background=1d4ed8&color=fff&size=64" />
|
||||
<AvatarFallback>SC</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 space-y-3">
|
||||
<Textarea
|
||||
placeholder="Write a note about this lead..."
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
className="min-h-[100px] resize-none"
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!note.trim() || submitting}
|
||||
className="gap-2"
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
{submitting ? "Adding..." : "Add Note"}
|
||||
</Button>
|
||||
<form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>
|
||||
<div className="flex gap-4">
|
||||
<Avatar className="h-10 w-10 shrink-0">
|
||||
<AvatarImage src={user?.avatar || undefined} />
|
||||
<AvatarFallback>{user?.name?.charAt(0) || "U"}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 space-y-3">
|
||||
<Textarea
|
||||
placeholder="Write a note about this lead..."
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="min-h-[100px] resize-none"
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!note.trim() || submitting}
|
||||
className="gap-2"
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
{submitting ? "Adding..." : "Add Note"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
@@ -35,7 +35,7 @@ export function CompanySettingsForm() {
|
||||
setData(json)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
console.warn("Failed to load company settings")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -57,6 +57,7 @@ export function CompanySettingsForm() {
|
||||
toast.error("Failed to save company settings")
|
||||
}
|
||||
} catch {
|
||||
console.warn("Failed to save company settings")
|
||||
toast.error("Failed to save company settings")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
@@ -98,11 +99,13 @@ export function CompanySettingsForm() {
|
||||
<Input id="company-address" disabled={loading} value={data.companyAddress} onChange={(e) => update("companyAddress", e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button onClick={handleSave} disabled={loading || saving}>
|
||||
{saving ? "Saving..." : "Save Changes"}
|
||||
</Button>
|
||||
</div>
|
||||
<form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button type="submit" disabled={loading || saving}>
|
||||
{saving ? "Saving..." : "Save Changes"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
@@ -45,7 +45,7 @@ export function NotificationSettings() {
|
||||
setPrefs(data)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
console.warn("Failed to load notification preferences")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -67,6 +67,7 @@ export function NotificationSettings() {
|
||||
toast.error("Failed to save preferences")
|
||||
}
|
||||
} catch {
|
||||
console.warn("Failed to save notification preferences")
|
||||
toast.error("Failed to save preferences")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
@@ -105,11 +106,13 @@ export function NotificationSettings() {
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button onClick={handleSave} disabled={loading || saving}>
|
||||
{saving ? "Saving..." : "Save Preferences"}
|
||||
</Button>
|
||||
</div>
|
||||
<form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button type="submit" disabled={loading || saving}>
|
||||
{saving ? "Saving..." : "Save Preferences"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
@@ -37,7 +37,7 @@ export function UserPreferencesForm() {
|
||||
setPrefs(json)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
console.warn("Failed to load user preferences")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -59,6 +59,7 @@ export function UserPreferencesForm() {
|
||||
toast.error("Failed to save preferences")
|
||||
}
|
||||
} catch {
|
||||
console.warn("Failed to save user preferences")
|
||||
toast.error("Failed to save preferences")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
@@ -117,11 +118,13 @@ export function UserPreferencesForm() {
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button onClick={handleSave} disabled={loading || saving}>
|
||||
{saving ? "Saving..." : "Save Preferences"}
|
||||
</Button>
|
||||
</div>
|
||||
<form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button type="submit" disabled={loading || saving}>
|
||||
{saving ? "Saving..." : "Save Preferences"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client"
|
||||
|
||||
import { Component, type ReactNode } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
interface Props {
|
||||
children: ReactNode
|
||||
fallback?: ReactNode
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean
|
||||
error?: Error
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends Component<Props, State> {
|
||||
constructor(props: Props) {
|
||||
super(props)
|
||||
this.state = { hasError: false }
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { hasError: true, error }
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: { componentStack?: string }) {
|
||||
console.error("ErrorBoundary caught:", error, info.componentStack)
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) return this.props.fallback
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-[60vh] gap-4">
|
||||
<h2 className="text-xl font-bold">Something went wrong</h2>
|
||||
<p className="text-muted-foreground text-sm max-w-md text-center">
|
||||
{this.state.error?.message || "An unexpected error occurred"}
|
||||
</p>
|
||||
<Button variant="outline" onClick={() => {
|
||||
this.setState({ hasError: false, error: undefined })
|
||||
window.location.reload()
|
||||
}}>
|
||||
Reload Page
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return this.props.children
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ import { toast } from "sonner";
|
||||
const createSchema = z.object({
|
||||
name: z.string().min(1, "Name is required"),
|
||||
email: z.string().email("Invalid email address"),
|
||||
password: z.string().min(6, "Password must be at least 6 characters"),
|
||||
password: z.string().min(8, "Password must be at least 8 characters"),
|
||||
role: z.string().min(1, "Role is required"),
|
||||
active: z.boolean(),
|
||||
});
|
||||
|
||||
@@ -32,6 +32,7 @@ export function UsersTable({ data, loading, onUserDeleted }: UsersTableProps) {
|
||||
toast.success("User deleted")
|
||||
onUserDeleted?.()
|
||||
} catch {
|
||||
console.warn("Failed to delete user")
|
||||
toast.error("Failed to delete user")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user