feat: enhance platform dashboard UX and add security controls

- Move Add Company button to Companies card header for better context
- Add smart Save Changes button that only appears when data is modified
- Implement navigation protection with unsaved changes warnings
- Add company status checks to prevent suspended companies from processing data
- Fix platform dashboard showing incorrect user counts
- Add dark mode toggle to platform interface
- Add copy-to-clipboard for generated credentials
- Fix cookie conflicts between regular and platform auth
- Add invitedBy and invitedAt tracking fields to User model
- Improve overall platform management workflow and security
This commit is contained in:
2025-06-28 18:19:25 +02:00
parent 2f2c358e67
commit 36ed8259b1
12 changed files with 524 additions and 137 deletions

View File

@ -44,6 +44,17 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: "Company not found" }, { status: 404 }); return NextResponse.json({ error: "Company not found" }, { status: 404 });
} }
// Check if company is active and can process data
if (company.status !== "ACTIVE") {
return NextResponse.json(
{
error: `Data processing is disabled for ${company.status.toLowerCase()} companies`,
companyStatus: company.status
},
{ status: 403 }
);
}
const rawSessionData = await fetchAndParseCsv( const rawSessionData = await fetchAndParseCsv(
company.csvUrl, company.csvUrl,
company.csvUsername as string | undefined, company.csvUsername as string | undefined,

View File

@ -66,7 +66,7 @@ export async function POST(
data: { data: {
name, name,
email, email,
hashedPassword, password: hashedPassword,
role, role,
companyId, companyId,
invitedBy: session.user.email, invitedBy: session.user.email,

View File

@ -40,6 +40,7 @@ export async function GET(request: NextRequest) {
select: { select: {
sessions: true, sessions: true,
imports: true, imports: true,
users: true,
}, },
}, },
}, },
@ -75,23 +76,72 @@ export async function POST(request: NextRequest) {
} }
const body = await request.json(); const body = await request.json();
const { name, csvUrl, csvUsername, csvPassword, status = "TRIAL" } = body; const {
name,
csvUrl,
csvUsername,
csvPassword,
adminEmail,
adminName,
adminPassword,
maxUsers = 10,
status = "TRIAL"
} = body;
if (!name || !csvUrl) { if (!name || !csvUrl) {
return NextResponse.json({ error: "Name and CSV URL required" }, { status: 400 }); return NextResponse.json({ error: "Name and CSV URL required" }, { status: 400 });
} }
const company = await prisma.company.create({ if (!adminEmail || !adminName) {
return NextResponse.json({ error: "Admin email and name required" }, { status: 400 });
}
// Generate password if not provided
const finalAdminPassword = adminPassword || `Temp${Math.random().toString(36).slice(2, 8)}!`;
// Hash the admin password
const bcrypt = await import("bcryptjs");
const hashedPassword = await bcrypt.hash(finalAdminPassword, 12);
// Create company and admin user in a transaction
const result = await prisma.$transaction(async (tx) => {
// Create the company
const company = await tx.company.create({
data: { data: {
name, name,
csvUrl, csvUrl,
csvUsername: csvUsername || null, csvUsername: csvUsername || null,
csvPassword: csvPassword || null, csvPassword: csvPassword || null,
maxUsers,
status, status,
}, },
}); });
return NextResponse.json({ company }, { status: 201 }); // Create the admin user
const adminUser = await tx.user.create({
data: {
email: adminEmail,
password: hashedPassword,
name: adminName,
role: "ADMIN",
companyId: company.id,
invitedBy: session.user.email || "platform",
invitedAt: new Date(),
},
});
return { company, adminUser, generatedPassword: adminPassword ? null : finalAdminPassword };
});
return NextResponse.json({
company: result.company,
adminUser: {
email: result.adminUser.email,
name: result.adminUser.name,
role: result.adminUser.role,
},
generatedPassword: result.generatedPassword,
}, { status: 201 });
} catch (error) { } catch (error) {
console.error("Platform company creation error:", error); console.error("Platform company creation error:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 }); return NextResponse.json({ error: "Internal server error" }, { status: 500 });

View File

@ -1,7 +1,7 @@
"use client"; "use client";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import { useEffect, useState } from "react"; import { useEffect, useState, useCallback } from "react";
import { useRouter, useParams } from "next/navigation"; import { useRouter, useParams } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@ -73,8 +73,55 @@ export default function CompanyManagement() {
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false); const [isSaving, setIsSaving] = useState(false);
const [editData, setEditData] = useState<Partial<Company>>({}); const [editData, setEditData] = useState<Partial<Company>>({});
const [originalData, setOriginalData] = useState<Partial<Company>>({});
const [showInviteUser, setShowInviteUser] = useState(false); const [showInviteUser, setShowInviteUser] = useState(false);
const [inviteData, setInviteData] = useState({ name: "", email: "", role: "USER" }); const [inviteData, setInviteData] = useState({ name: "", email: "", role: "USER" });
const [showUnsavedChangesDialog, setShowUnsavedChangesDialog] = useState(false);
const [pendingNavigation, setPendingNavigation] = useState<string | null>(null);
// Function to check if data has been modified
const hasUnsavedChanges = useCallback(() => {
// Normalize data for comparison (handle null/undefined/empty string equivalence)
const normalizeValue = (value: any) => {
if (value === null || value === undefined || value === "") {
return "";
}
return value;
};
const normalizedEditData = {
name: normalizeValue(editData.name),
email: normalizeValue(editData.email),
status: normalizeValue(editData.status),
maxUsers: editData.maxUsers || 0,
};
const normalizedOriginalData = {
name: normalizeValue(originalData.name),
email: normalizeValue(originalData.email),
status: normalizeValue(originalData.status),
maxUsers: originalData.maxUsers || 0,
};
return JSON.stringify(normalizedEditData) !== JSON.stringify(normalizedOriginalData);
}, [editData, originalData]);
// Handle navigation protection - must be at top level
const handleNavigation = useCallback((url: string) => {
// Allow navigation within the same company (different tabs, etc.)
if (url.includes(`/platform/companies/${params.id}`)) {
router.push(url);
return;
}
// If there are unsaved changes, show confirmation dialog
if (hasUnsavedChanges()) {
setPendingNavigation(url);
setShowUnsavedChangesDialog(true);
} else {
router.push(url);
}
}, [router, params.id, hasUnsavedChanges]);
useEffect(() => { useEffect(() => {
if (status === "loading") return; if (status === "loading") return;
@ -93,12 +140,14 @@ export default function CompanyManagement() {
if (response.ok) { if (response.ok) {
const data = await response.json(); const data = await response.json();
setCompany(data); setCompany(data);
setEditData({ const companyData = {
name: data.name, name: data.name,
email: data.email, email: data.email,
status: data.status, status: data.status,
maxUsers: data.maxUsers, maxUsers: data.maxUsers,
}); };
setEditData(companyData);
setOriginalData(companyData);
} else { } else {
toast({ toast({
title: "Error", title: "Error",
@ -130,6 +179,13 @@ export default function CompanyManagement() {
if (response.ok) { if (response.ok) {
const updatedCompany = await response.json(); const updatedCompany = await response.json();
setCompany(updatedCompany); setCompany(updatedCompany);
const companyData = {
name: updatedCompany.name,
email: updatedCompany.email,
status: updatedCompany.status,
maxUsers: updatedCompany.maxUsers,
};
setOriginalData(companyData);
toast({ toast({
title: "Success", title: "Success",
description: "Company updated successfully", description: "Company updated successfully",
@ -177,6 +233,50 @@ export default function CompanyManagement() {
} }
}; };
const confirmNavigation = () => {
if (pendingNavigation) {
router.push(pendingNavigation);
setPendingNavigation(null);
}
setShowUnsavedChangesDialog(false);
};
const cancelNavigation = () => {
setPendingNavigation(null);
setShowUnsavedChangesDialog(false);
};
// Protect against browser back/forward and other navigation
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (hasUnsavedChanges()) {
e.preventDefault();
e.returnValue = '';
}
};
const handlePopState = (e: PopStateEvent) => {
if (hasUnsavedChanges()) {
const confirmLeave = window.confirm(
'You have unsaved changes. Are you sure you want to leave this page?'
);
if (!confirmLeave) {
// Push the current state back to prevent navigation
window.history.pushState(null, '', window.location.href);
e.preventDefault();
}
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
window.addEventListener('popstate', handlePopState);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
window.removeEventListener('popstate', handlePopState);
};
}, [hasUnsavedChanges]);
const handleInviteUser = async () => { const handleInviteUser = async () => {
try { try {
const response = await fetch(`/api/platform/companies/${params.id}/users`, { const response = await fetch(`/api/platform/companies/${params.id}/users`, {
@ -205,6 +305,16 @@ export default function CompanyManagement() {
} }
}; };
const getStatusBadgeVariant = (status: string) => {
switch (status) {
case "ACTIVE": return "default";
case "TRIAL": return "secondary";
case "SUSPENDED": return "destructive";
case "ARCHIVED": return "outline";
default: return "default";
}
};
if (status === "loading" || isLoading) { if (status === "loading" || isLoading) {
return ( return (
<div className="flex items-center justify-center min-h-screen"> <div className="flex items-center justify-center min-h-screen">
@ -217,16 +327,6 @@ export default function CompanyManagement() {
return null; return null;
} }
const getStatusBadgeVariant = (status: string) => {
switch (status) {
case "ACTIVE": return "default";
case "TRIAL": return "secondary";
case "SUSPENDED": return "destructive";
case "ARCHIVED": return "outline";
default: return "default";
}
};
const canEdit = session.user.platformRole === "SUPER_ADMIN"; const canEdit = session.user.platformRole === "SUPER_ADMIN";
return ( return (
@ -238,7 +338,7 @@ export default function CompanyManagement() {
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => router.push("/platform/dashboard")} onClick={() => handleNavigation("/platform/dashboard")}
> >
<ArrowLeft className="w-4 h-4 mr-2" /> <ArrowLeft className="w-4 h-4 mr-2" />
Back to Dashboard Back to Dashboard
@ -259,7 +359,6 @@ export default function CompanyManagement() {
</div> </div>
<div className="flex gap-2"> <div className="flex gap-2">
{canEdit && ( {canEdit && (
<>
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
@ -268,15 +367,6 @@ export default function CompanyManagement() {
<UserPlus className="w-4 h-4 mr-2" /> <UserPlus className="w-4 h-4 mr-2" />
Invite User Invite User
</Button> </Button>
<Button
size="sm"
onClick={handleSave}
disabled={isSaving}
>
<Save className="w-4 h-4 mr-2" />
{isSaving ? "Saving..." : "Save Changes"}
</Button>
</>
)} )}
</div> </div>
</div> </div>
@ -396,6 +486,25 @@ export default function CompanyManagement() {
</Select> </Select>
</div> </div>
</div> </div>
{canEdit && hasUnsavedChanges() && (
<div className="flex gap-2 pt-4 border-t">
<Button
variant="outline"
onClick={() => {
setEditData(originalData);
}}
>
Cancel Changes
</Button>
<Button
onClick={handleSave}
disabled={isSaving}
>
<Save className="w-4 h-4 mr-2" />
{isSaving ? "Saving..." : "Save Changes"}
</Button>
</div>
)}
</CardContent> </CardContent>
</Card> </Card>
</TabsContent> </TabsContent>
@ -587,6 +696,26 @@ export default function CompanyManagement() {
</Card> </Card>
</div> </div>
)} )}
{/* Unsaved Changes Dialog */}
<AlertDialog open={showUnsavedChangesDialog} onOpenChange={setShowUnsavedChangesDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Unsaved Changes</AlertDialogTitle>
<AlertDialogDescription>
You have unsaved changes that will be lost if you leave this page. Are you sure you want to continue?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={cancelNavigation}>
Stay on Page
</AlertDialogCancel>
<AlertDialogAction onClick={confirmNavigation}>
Leave Without Saving
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div> </div>
); );
} }

View File

@ -23,9 +23,12 @@ import {
Activity, Activity,
Plus, Plus,
Settings, Settings,
BarChart3 BarChart3,
Search
} from "lucide-react"; } from "lucide-react";
import { ThemeToggle } from "@/components/ui/theme-toggle";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { Copy, Check } from "lucide-react";
interface Company { interface Company {
id: string; id: string;
@ -86,8 +89,14 @@ export default function PlatformDashboard() {
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [showAddCompany, setShowAddCompany] = useState(false); const [showAddCompany, setShowAddCompany] = useState(false);
const [isCreating, setIsCreating] = useState(false); const [isCreating, setIsCreating] = useState(false);
const [copiedEmail, setCopiedEmail] = useState(false);
const [copiedPassword, setCopiedPassword] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [newCompanyData, setNewCompanyData] = useState({ const [newCompanyData, setNewCompanyData] = useState({
name: "", name: "",
csvUrl: "",
csvUsername: "",
csvPassword: "",
adminEmail: "", adminEmail: "",
adminName: "", adminName: "",
adminPassword: "", adminPassword: "",
@ -105,6 +114,29 @@ export default function PlatformDashboard() {
fetchDashboardData(); fetchDashboardData();
}, [session, status, router]); }, [session, status, router]);
const copyToClipboard = async (text: string, type: 'email' | 'password') => {
try {
await navigator.clipboard.writeText(text);
if (type === 'email') {
setCopiedEmail(true);
setTimeout(() => setCopiedEmail(false), 2000);
} else {
setCopiedPassword(true);
setTimeout(() => setCopiedPassword(false), 2000);
}
} catch (err) {
console.error('Failed to copy: ', err);
}
};
const getFilteredCompanies = () => {
if (!dashboardData?.companies) return [];
return dashboardData.companies.filter(company =>
company.name.toLowerCase().includes(searchTerm.toLowerCase())
);
};
const fetchDashboardData = async () => { const fetchDashboardData = async () => {
try { try {
const response = await fetch("/api/platform/companies"); const response = await fetch("/api/platform/companies");
@ -120,7 +152,7 @@ export default function PlatformDashboard() {
}; };
const handleCreateCompany = async () => { const handleCreateCompany = async () => {
if (!newCompanyData.name || !newCompanyData.adminEmail || !newCompanyData.adminName) { if (!newCompanyData.name || !newCompanyData.csvUrl || !newCompanyData.adminEmail || !newCompanyData.adminName) {
toast({ toast({
title: "Error", title: "Error",
description: "Please fill in all required fields", description: "Please fill in all required fields",
@ -140,18 +172,68 @@ export default function PlatformDashboard() {
if (response.ok) { if (response.ok) {
const result = await response.json(); const result = await response.json();
setShowAddCompany(false); setShowAddCompany(false);
const companyName = newCompanyData.name;
setNewCompanyData({ setNewCompanyData({
name: "", name: "",
csvUrl: "",
csvUsername: "",
csvPassword: "",
adminEmail: "", adminEmail: "",
adminName: "", adminName: "",
adminPassword: "", adminPassword: "",
maxUsers: 10, maxUsers: 10,
}); });
fetchDashboardData(); // Refresh the list fetchDashboardData(); // Refresh the list
// Show success message with copyable credentials
if (result.generatedPassword) {
toast({
title: "Company Created Successfully!",
description: (
<div className="space-y-3">
<p className="font-medium">Company "{companyName}" has been created.</p>
<div className="space-y-2">
<div className="flex items-center justify-between bg-muted p-2 rounded">
<div className="flex-1">
<p className="text-xs text-muted-foreground">Admin Email:</p>
<p className="font-mono text-sm">{result.adminUser.email}</p>
</div>
<Button
size="sm"
variant="ghost"
onClick={() => copyToClipboard(result.adminUser.email, 'email')}
className="h-8 w-8 p-0"
>
{copiedEmail ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
</Button>
</div>
<div className="flex items-center justify-between bg-muted p-2 rounded">
<div className="flex-1">
<p className="text-xs text-muted-foreground">Admin Password:</p>
<p className="font-mono text-sm">{result.generatedPassword}</p>
</div>
<Button
size="sm"
variant="ghost"
onClick={() => copyToClipboard(result.generatedPassword, 'password')}
className="h-8 w-8 p-0"
>
{copiedPassword ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
</Button>
</div>
</div>
</div>
),
duration: 15000, // Longer duration for credentials
});
} else {
toast({ toast({
title: "Success", title: "Success",
description: `Company "${newCompanyData.name}" created successfully`, description: `Company "${companyName}" created successfully`,
}); });
}
} else { } else {
const error = await response.json(); const error = await response.json();
throw new Error(error.error || "Failed to create company"); throw new Error(error.error || "Failed to create company");
@ -189,6 +271,7 @@ export default function PlatformDashboard() {
return null; return null;
} }
const filteredCompanies = getFilteredCompanies();
const totalCompanies = dashboardData?.pagination?.total || 0; const totalCompanies = dashboardData?.pagination?.total || 0;
const totalUsers = dashboardData?.companies?.reduce((sum, company) => sum + company._count.users, 0) || 0; const totalUsers = dashboardData?.companies?.reduce((sum, company) => sum + company._count.users, 0) || 0;
const totalSessions = dashboardData?.companies?.reduce((sum, company) => sum + company._count.sessions, 0) || 0; const totalSessions = dashboardData?.companies?.reduce((sum, company) => sum + company._count.sessions, 0) || 0;
@ -206,86 +289,23 @@ export default function PlatformDashboard() {
Welcome back, {session.user.name || session.user.email} Welcome back, {session.user.name || session.user.email}
</p> </p>
</div> </div>
<div className="flex gap-4"> <div className="flex gap-4 items-center">
<ThemeToggle />
{/* Search Filter */}
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input
placeholder="Search companies..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10 w-64"
/>
</div>
<Button variant="outline" size="sm"> <Button variant="outline" size="sm">
<Settings className="w-4 h-4 mr-2" /> <Settings className="w-4 h-4 mr-2" />
Settings Settings
</Button> </Button>
<Dialog open={showAddCompany} onOpenChange={setShowAddCompany}>
<DialogTrigger asChild>
<Button size="sm">
<Plus className="w-4 h-4 mr-2" />
Add Company
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Add New Company</DialogTitle>
<DialogDescription>
Create a new company and invite the first administrator.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="space-y-2">
<Label htmlFor="companyName">Company Name *</Label>
<Input
id="companyName"
value={newCompanyData.name}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, name: e.target.value }))}
placeholder="Acme Corporation"
/>
</div>
<div className="space-y-2">
<Label htmlFor="adminName">Admin Name *</Label>
<Input
id="adminName"
value={newCompanyData.adminName}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, adminName: e.target.value }))}
placeholder="John Doe"
/>
</div>
<div className="space-y-2">
<Label htmlFor="adminEmail">Admin Email *</Label>
<Input
id="adminEmail"
type="email"
value={newCompanyData.adminEmail}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, adminEmail: e.target.value }))}
placeholder="admin@acme.com"
/>
</div>
<div className="space-y-2">
<Label htmlFor="adminPassword">Admin Password</Label>
<Input
id="adminPassword"
type="password"
value={newCompanyData.adminPassword}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, adminPassword: e.target.value }))}
placeholder="Leave empty to auto-generate"
/>
</div>
<div className="space-y-2">
<Label htmlFor="maxUsers">Max Users</Label>
<Input
id="maxUsers"
type="number"
value={newCompanyData.maxUsers}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, maxUsers: parseInt(e.target.value) || 10 }))}
min="1"
max="1000"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowAddCompany(false)}>
Cancel
</Button>
<Button onClick={handleCreateCompany} disabled={isCreating}>
{isCreating ? "Creating..." : "Create Company"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
</div> </div>
</div> </div>
@ -340,14 +360,131 @@ export default function PlatformDashboard() {
{/* Companies List */} {/* Companies List */}
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Building2 className="w-5 h-5" /> <Building2 className="w-5 h-5" />
Companies Companies
{searchTerm && (
<Badge variant="secondary" className="ml-2">
{filteredCompanies.length} of {totalCompanies} shown
</Badge>
)}
</div>
<div className="flex items-center gap-2">
{searchTerm && (
<Badge variant="outline" className="text-xs">
Search: "{searchTerm}"
</Badge>
)}
<Dialog open={showAddCompany} onOpenChange={setShowAddCompany}>
<DialogTrigger asChild>
<Button size="sm">
<Plus className="w-4 h-4 mr-2" />
Add Company
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Add New Company</DialogTitle>
<DialogDescription>
Create a new company and invite the first administrator.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="space-y-2">
<Label htmlFor="companyName">Company Name *</Label>
<Input
id="companyName"
value={newCompanyData.name}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, name: e.target.value }))}
placeholder="Acme Corporation"
/>
</div>
<div className="space-y-2">
<Label htmlFor="csvUrl">CSV Data URL *</Label>
<Input
id="csvUrl"
value={newCompanyData.csvUrl}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, csvUrl: e.target.value }))}
placeholder="https://api.company.com/sessions.csv"
/>
</div>
<div className="space-y-2">
<Label htmlFor="csvUsername">CSV Auth Username</Label>
<Input
id="csvUsername"
value={newCompanyData.csvUsername}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, csvUsername: e.target.value }))}
placeholder="Optional HTTP auth username"
/>
</div>
<div className="space-y-2">
<Label htmlFor="csvPassword">CSV Auth Password</Label>
<Input
id="csvPassword"
type="password"
value={newCompanyData.csvPassword}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, csvPassword: e.target.value }))}
placeholder="Optional HTTP auth password"
/>
</div>
<div className="space-y-2">
<Label htmlFor="adminName">Admin Name *</Label>
<Input
id="adminName"
value={newCompanyData.adminName}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, adminName: e.target.value }))}
placeholder="John Doe"
/>
</div>
<div className="space-y-2">
<Label htmlFor="adminEmail">Admin Email *</Label>
<Input
id="adminEmail"
type="email"
value={newCompanyData.adminEmail}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, adminEmail: e.target.value }))}
placeholder="admin@acme.com"
/>
</div>
<div className="space-y-2">
<Label htmlFor="adminPassword">Admin Password</Label>
<Input
id="adminPassword"
type="password"
value={newCompanyData.adminPassword}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, adminPassword: e.target.value }))}
placeholder="Leave empty to auto-generate"
/>
</div>
<div className="space-y-2">
<Label htmlFor="maxUsers">Max Users</Label>
<Input
id="maxUsers"
type="number"
value={newCompanyData.maxUsers}
onChange={(e) => setNewCompanyData(prev => ({ ...prev, maxUsers: parseInt(e.target.value) || 10 }))}
min="1"
max="1000"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowAddCompany(false)}>
Cancel
</Button>
<Button onClick={handleCreateCompany} disabled={isCreating}>
{isCreating ? "Creating..." : "Create Company"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="space-y-4"> <div className="space-y-4">
{dashboardData?.companies?.map((company) => ( {filteredCompanies.map((company) => (
<div <div
key={company.id} key={company.id}
className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors" className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
@ -383,9 +520,18 @@ export default function PlatformDashboard() {
</div> </div>
))} ))}
{!dashboardData?.companies?.length && ( {!filteredCompanies.length && (
<div className="text-center py-8 text-muted-foreground"> <div className="text-center py-8 text-muted-foreground">
No companies found. Create your first company to get started. {searchTerm ? (
<div className="space-y-2">
<p>No companies match "{searchTerm}".</p>
<Button variant="link" onClick={() => setSearchTerm("")} className="text-sm">
Clear search to see all companies
</Button>
</div>
) : (
"No companies found. Create your first company to get started."
)}
</div> </div>
)} )}
</div> </div>

View File

@ -2,6 +2,7 @@
import { SessionProvider } from "next-auth/react"; import { SessionProvider } from "next-auth/react";
import { Toaster } from "@/components/ui/toaster"; import { Toaster } from "@/components/ui/toaster";
import { ThemeProvider } from "@/components/theme-provider";
export default function PlatformLayout({ export default function PlatformLayout({
children, children,
@ -9,9 +10,16 @@ export default function PlatformLayout({
children: React.ReactNode; children: React.ReactNode;
}) { }) {
return ( return (
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<SessionProvider basePath="/api/platform/auth"> <SessionProvider basePath="/api/platform/auth">
{children} {children}
<Toaster /> <Toaster />
</SessionProvider> </SessionProvider>
</ThemeProvider>
); );
} }

View File

@ -8,6 +8,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert"; import { Alert, AlertDescription } from "@/components/ui/alert";
import { ThemeToggle } from "@/components/ui/theme-toggle";
export default function PlatformLoginPage() { export default function PlatformLoginPage() {
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
@ -43,7 +44,10 @@ export default function PlatformLoginPage() {
}; };
return ( return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900"> <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900 relative">
<div className="absolute top-4 right-4">
<ThemeToggle />
</div>
<Card className="w-full max-w-md"> <Card className="w-full max-w-md">
<CardHeader className="text-center"> <CardHeader className="text-center">
<CardTitle className="text-2xl font-bold">Platform Login</CardTitle> <CardTitle className="text-2xl font-bold">Platform Login</CardTitle>

21
app/platform/page.tsx Normal file
View File

@ -0,0 +1,21 @@
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
export default function PlatformIndexPage() {
const router = useRouter();
useEffect(() => {
// Redirect to platform dashboard
router.replace("/platform/dashboard");
}, [router]);
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">Redirecting to platform dashboard...</p>
</div>
</div>
);
}

View File

@ -366,6 +366,9 @@ export async function processQueuedImports(
const unprocessedImports = await prisma.sessionImport.findMany({ const unprocessedImports = await prisma.sessionImport.findMany({
where: { where: {
session: null, // No session created yet session: null, // No session created yet
company: {
status: "ACTIVE" // Only process imports from active companies
}
}, },
take: batchSize, take: batchSize,
orderBy: { orderBy: {

View File

@ -172,6 +172,11 @@ export class ProcessingStatusManager {
where: { where: {
stage, stage,
status: ProcessingStatus.PENDING, status: ProcessingStatus.PENDING,
session: {
company: {
status: "ACTIVE" // Only process sessions from active companies
}
}
}, },
include: { include: {
session: { session: {

View File

@ -17,7 +17,9 @@ export function startCsvImportScheduler() {
); );
cron.schedule(config.csvImport.interval, async () => { cron.schedule(config.csvImport.interval, async () => {
const companies = await prisma.company.findMany(); const companies = await prisma.company.findMany({
where: { status: "ACTIVE" } // Only process active companies
});
for (const company of companies) { for (const company of companies) {
try { try {
const rawSessionData = await fetchAndParseCsv( const rawSessionData = await fetchAndParseCsv(

View File

@ -49,6 +49,8 @@ model Company {
dashboardOpts Json? dashboardOpts Json?
createdAt DateTime @default(now()) @db.Timestamptz(6) createdAt DateTime @default(now()) @db.Timestamptz(6)
updatedAt DateTime @updatedAt @db.Timestamptz(6) updatedAt DateTime @updatedAt @db.Timestamptz(6)
/// Maximum number of users allowed for this company
maxUsers Int @default(10)
companyAiModels CompanyAIModel[] companyAiModels CompanyAIModel[]
sessions Session[] sessions Session[]
imports SessionImport[] imports SessionImport[]
@ -78,6 +80,12 @@ model User {
resetTokenExpiry DateTime? @db.Timestamptz(6) resetTokenExpiry DateTime? @db.Timestamptz(6)
createdAt DateTime @default(now()) @db.Timestamptz(6) createdAt DateTime @default(now()) @db.Timestamptz(6)
updatedAt DateTime @updatedAt @db.Timestamptz(6) updatedAt DateTime @updatedAt @db.Timestamptz(6)
/// Display name for the user
name String? @db.VarChar(255)
/// When this user was invited
invitedAt DateTime? @db.Timestamptz(6)
/// Email of the user who invited this user (for audit trail)
invitedBy String? @db.VarChar(255)
company Company @relation("CompanyUsers", fields: [companyId], references: [id], onDelete: Cascade) company Company @relation("CompanyUsers", fields: [companyId], references: [id], onDelete: Cascade)
@@index([companyId]) @@index([companyId])