Feat: RBAC, Keys Extension, Invites
feat: org members page — invite users, cancel invites, change roles feat: show pending invitations banner on profile page feat: invite accept flow for existing users (no password needed) feat: departments page updates feat: SSH keys page — dept cert policy UI (expiry + extensions) feat: wire up auth pages to real API (register, verify, reset, OIDC) feat: CLI auth bridge — login page handles CLI token flow feat: admin users — suspend/unsuspend, role badges, role filter feat: add admin OAuth providers management page feat: activity page — org-wide audit log view for admins feat: add my memberships page chore: add isOrgAdmin/isOrgMember to AuthContext, restrict sidebar chore: update app routing and shared layout
This commit is contained in:
@@ -1,14 +1,15 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Shield, Search, Filter, Loader2, User, Clock, AlertTriangle, CheckCircle, Mail, ExternalLink } from "lucide-react";
|
||||
import { Shield, Search, Loader2, User, Clock, AlertTriangle, CheckCircle, Mail, ExternalLink } from "lucide-react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { api, OrgComplianceMember, create403Handler } from "@/lib/api";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useOrganizations } from "@/hooks/useOrganizations";
|
||||
|
||||
const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof Clock }> = {
|
||||
compliant: {
|
||||
@@ -51,18 +52,13 @@ export default function CompliancePage() {
|
||||
const [statusFilter, setStatusFilter] = useState<string>("all");
|
||||
|
||||
// Fetch organizations to get current org
|
||||
const { data: orgsData, isLoading: orgsLoading } = useQuery({
|
||||
queryKey: ['organizations'],
|
||||
queryFn: () => api.users.organizations({
|
||||
on403: create403Handler(toast),
|
||||
}),
|
||||
});
|
||||
const { data: organizations, isLoading: orgsLoading } = useOrganizations();
|
||||
|
||||
useEffect(() => {
|
||||
if (orgsData?.organizations && orgsData.organizations.length > 0) {
|
||||
setCurrentOrgId(orgsData.organizations[0].id);
|
||||
if (organizations && organizations.length > 0) {
|
||||
setCurrentOrgId(organizations[0].id);
|
||||
}
|
||||
}, [orgsData]);
|
||||
}, [organizations]);
|
||||
|
||||
// Fetch compliance data
|
||||
const { data: complianceData, isLoading: complianceLoading } = useQuery({
|
||||
@@ -73,6 +69,18 @@ export default function CompliancePage() {
|
||||
enabled: !!currentOrgId,
|
||||
});
|
||||
|
||||
// Send MFA reminder mutation
|
||||
const { mutate: sendReminder, variables: reminderVars, isPending: isSendingReminder } = useMutation({
|
||||
mutationFn: ({ userId }: { userId: string }) =>
|
||||
api.organizations.sendMfaReminder(currentOrgId!, userId),
|
||||
onSuccess: () => {
|
||||
toast({ title: "Reminder sent", description: "MFA reminder email sent successfully." });
|
||||
},
|
||||
onError: () => {
|
||||
toast({ title: "Failed to send", description: "Could not send the reminder. Please try again.", variant: "destructive" });
|
||||
},
|
||||
});
|
||||
|
||||
// Filter members based on search and status
|
||||
const filteredMembers = complianceData?.members?.filter((member) => {
|
||||
const matchesSearch =
|
||||
@@ -256,10 +264,8 @@ export default function CompliancePage() {
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
title="Send Reminder"
|
||||
onClick={() => {
|
||||
// TODO: Implement send reminder
|
||||
console.log('Send reminder to', member.user_id);
|
||||
}}
|
||||
disabled={isSendingReminder && reminderVars?.userId === member.user_id}
|
||||
onClick={() => sendReminder({ userId: member.user_id })}
|
||||
>
|
||||
<Mail className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Search, Plus, MoreHorizontal, Users, Loader2, Trash2, Edit2, X } from "lucide-react";
|
||||
import { Search, Plus, MoreHorizontal, Users, Loader2, Trash2, Edit2, X, ChevronDown, ChevronUp, ShieldCheck, UserPlus, UserMinus, Link as LinkIcon } from "lucide-react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -21,10 +21,348 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { api, Department, Principal } from "@/lib/api";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { api, Department, Principal, DeptCertPolicy, STANDARD_SSH_EXTENSIONS, DepartmentMember, OrganizationMember } from "@/lib/api";
|
||||
import { useCurrentOrganizationId } from "@/hooks/useCurrentOrganization";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Department Certificate Policy Panel
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function DepartmentCertPolicyPanel({ orgId, deptId }: { orgId: string; deptId: string }) {
|
||||
const { toast } = useToast();
|
||||
const [policy, setPolicy] = useState<DeptCertPolicy | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
// Local editable form state
|
||||
const [allowUserExpiry, setAllowUserExpiry] = useState(false);
|
||||
const [defaultExpiry, setDefaultExpiry] = useState(1);
|
||||
const [maxExpiry, setMaxExpiry] = useState(24);
|
||||
const [allowedExtensions, setAllowedExtensions] = useState<string[]>([...STANDARD_SSH_EXTENSIONS]);
|
||||
const [customExtensions, setCustomExtensions] = useState<string[]>([]);
|
||||
const [newCustomExt, setNewCustomExt] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setIsLoading(true);
|
||||
api.admin.getDeptCertPolicy(orgId, deptId)
|
||||
.then((data) => {
|
||||
const p = data.cert_policy;
|
||||
setPolicy(p);
|
||||
setAllowUserExpiry(p.allow_user_expiry);
|
||||
setDefaultExpiry(p.default_expiry_hours);
|
||||
setMaxExpiry(p.max_expiry_hours);
|
||||
setAllowedExtensions(p.allowed_extensions ?? [...STANDARD_SSH_EXTENSIONS]);
|
||||
setCustomExtensions(p.custom_extensions ?? []);
|
||||
})
|
||||
.catch(() => {/* non-fatal — use defaults */})
|
||||
.finally(() => setIsLoading(false));
|
||||
}, [orgId, deptId]);
|
||||
|
||||
const toggleExtension = (ext: string) => {
|
||||
setAllowedExtensions((prev) =>
|
||||
prev.includes(ext) ? prev.filter((e) => e !== ext) : [...prev, ext]
|
||||
);
|
||||
};
|
||||
|
||||
const addCustomExt = () => {
|
||||
const trimmed = newCustomExt.trim();
|
||||
if (!trimmed || customExtensions.includes(trimmed)) return;
|
||||
setCustomExtensions((prev) => [...prev, trimmed]);
|
||||
setNewCustomExt("");
|
||||
};
|
||||
|
||||
const removeCustomExt = (ext: string) => {
|
||||
setCustomExtensions((prev) => prev.filter((e) => e !== ext));
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
// When members can pick: max_expiry is the cap, default_expiry is also set to max
|
||||
// (the backend uses default when no expiry is provided).
|
||||
// When members can't pick: default_expiry is the fixed value, max is irrelevant.
|
||||
const payload = allowUserExpiry
|
||||
? { allow_user_expiry: true, default_expiry_hours: maxExpiry, max_expiry_hours: maxExpiry }
|
||||
: { allow_user_expiry: false, default_expiry_hours: defaultExpiry, max_expiry_hours: defaultExpiry };
|
||||
|
||||
const data = await api.admin.setDeptCertPolicy(orgId, deptId, {
|
||||
...payload,
|
||||
allowed_extensions: allowedExtensions,
|
||||
custom_extensions: customExtensions,
|
||||
});
|
||||
setPolicy(data.cert_policy);
|
||||
toast({ title: "Policy saved", description: "Certificate policy updated." });
|
||||
} catch (err) {
|
||||
toast({ variant: "destructive", title: "Failed to save policy" });
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="mt-3 p-4 border rounded-lg bg-muted/30 flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />Loading policy…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-3 p-4 border rounded-lg bg-muted/20 space-y-4">
|
||||
<h4 className="text-sm font-semibold flex items-center gap-2">
|
||||
<ShieldCheck className="w-4 h-4 text-primary" />
|
||||
Certificate Policy
|
||||
</h4>
|
||||
|
||||
{/* Allow user to choose expiry */}
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium">Allow members to pick expiry date</p>
|
||||
<p className="text-xs text-muted-foreground">Admins can always pick.</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={allowUserExpiry}
|
||||
onClick={() => setAllowUserExpiry((v) => !v)}
|
||||
className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 ${
|
||||
allowUserExpiry ? "bg-primary" : "bg-zinc-600"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-lg transition-transform ${
|
||||
allowUserExpiry ? "translate-x-5" : "translate-x-0"
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Expiry hours — conditional on toggle */}
|
||||
{allowUserExpiry ? (
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Max expiry members can request (hours)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={maxExpiry}
|
||||
onChange={(e) => setMaxExpiry(Math.max(1, Number(e.target.value)))}
|
||||
className="h-8 text-sm w-40"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Members can choose any duration up to this cap.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Default expiry applied to all members (hours)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={defaultExpiry}
|
||||
onChange={(e) => setDefaultExpiry(Math.max(1, Number(e.target.value)))}
|
||||
className="h-8 text-sm w-40"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Members receive this expiry automatically — no choice shown.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Standard extensions */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Standard SSH extensions</Label>
|
||||
<div className="space-y-1.5">
|
||||
{STANDARD_SSH_EXTENSIONS.map((ext) => (
|
||||
<div key={ext} className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={`ext-${deptId}-${ext}`}
|
||||
checked={allowedExtensions.includes(ext)}
|
||||
onChange={() => toggleExtension(ext)}
|
||||
className="accent-primary"
|
||||
/>
|
||||
<label htmlFor={`ext-${deptId}-${ext}`} className="text-sm font-mono cursor-pointer">{ext}</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom extensions */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">Custom extensions</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="permit-custom-x"
|
||||
value={newCustomExt}
|
||||
onChange={(e) => setNewCustomExt(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && addCustomExt()}
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<Button size="sm" variant="outline" onClick={addCustomExt} disabled={!newCustomExt.trim()}>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{customExtensions.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mt-1">
|
||||
{customExtensions.map((ext) => (
|
||||
<Badge key={ext} variant="secondary" className="text-xs gap-1 pr-1">
|
||||
<span className="font-mono">{ext}</span>
|
||||
<button onClick={() => removeCustomExt(ext)} className="ml-0.5 hover:text-destructive">
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button size="sm" onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Save policy
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Department Members Panel
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function DepartmentMembersPanel({ orgId, deptId }: { orgId: string; deptId: string }) {
|
||||
const { toast } = useToast();
|
||||
const [members, setMembers] = useState<DepartmentMember[]>([]);
|
||||
const [orgMembers, setOrgMembers] = useState<OrganizationMember[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
const [removingId, setRemovingId] = useState<string | null>(null);
|
||||
const [selectedUserId, setSelectedUserId] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setIsLoading(true);
|
||||
Promise.all([
|
||||
api.organizations.getDepartmentMembers(orgId, deptId),
|
||||
api.organizations.getMembers(orgId),
|
||||
])
|
||||
.then(([deptRes, orgRes]) => {
|
||||
setMembers(deptRes.members || []);
|
||||
setOrgMembers(orgRes.members || []);
|
||||
})
|
||||
.catch(() => toast({ variant: "destructive", title: "Failed to load members" }))
|
||||
.finally(() => setIsLoading(false));
|
||||
}, [orgId, deptId, toast]);
|
||||
|
||||
const deptUserIds = new Set(members.map((m) => m.user_id));
|
||||
const available = orgMembers.filter((m) => !deptUserIds.has(m.user_id));
|
||||
|
||||
const handleAdd = async () => {
|
||||
const orgMember = orgMembers.find((m) => m.user_id === selectedUserId);
|
||||
if (!orgMember?.user?.email) return;
|
||||
setIsAdding(true);
|
||||
try {
|
||||
const res = await api.organizations.addDepartmentMember(orgId, deptId, orgMember.user.email);
|
||||
setMembers((prev) => [...prev, res.member]);
|
||||
setSelectedUserId("");
|
||||
toast({ title: "Member added", description: `${orgMember.user.full_name || orgMember.user.email} added to department.` });
|
||||
} catch (err) {
|
||||
toast({ variant: "destructive", title: "Failed to add member" });
|
||||
} finally {
|
||||
setIsAdding(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemove = async (userId: string, displayName: string) => {
|
||||
setRemovingId(userId);
|
||||
try {
|
||||
await api.organizations.removeDepartmentMember(orgId, deptId, userId);
|
||||
setMembers((prev) => prev.filter((m) => m.user_id !== userId));
|
||||
toast({ title: "Member removed", description: `${displayName} removed from department.` });
|
||||
} catch (err) {
|
||||
toast({ variant: "destructive", title: "Failed to remove member" });
|
||||
} finally {
|
||||
setRemovingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="mt-3 p-4 border rounded-lg bg-muted/30 flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="w-4 h-4 animate-spin" /> Loading members…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-3 p-4 border rounded-lg bg-muted/20 space-y-3">
|
||||
<h4 className="text-sm font-semibold flex items-center gap-2">
|
||||
<Users className="w-4 h-4 text-primary" />
|
||||
Department Members
|
||||
<Badge variant="secondary" className="ml-1">{members.length}</Badge>
|
||||
</h4>
|
||||
|
||||
{/* Existing members */}
|
||||
{members.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground italic">No members yet.</p>
|
||||
) : (
|
||||
<ul className="space-y-1.5">
|
||||
{members.map((m) => {
|
||||
const name = m.user?.full_name || m.user?.email || m.user_id;
|
||||
const email = m.user?.email;
|
||||
const busy = removingId === m.user_id;
|
||||
return (
|
||||
<li key={m.user_id} className="flex items-center justify-between gap-2 text-sm">
|
||||
<div className="min-w-0">
|
||||
<span className="font-medium truncate">{name}</span>
|
||||
{email && name !== email && (
|
||||
<span className="ml-2 text-xs text-muted-foreground">{email}</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleRemove(m.user_id, name)}
|
||||
disabled={busy}
|
||||
className="flex items-center gap-1 text-xs text-destructive hover:underline disabled:opacity-50 flex-shrink-0"
|
||||
>
|
||||
{busy ? <Loader2 className="w-3 h-3 animate-spin" /> : <UserMinus className="w-3 h-3" />}
|
||||
Remove
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{/* Add member */}
|
||||
{available.length > 0 && (
|
||||
<div className="flex items-center gap-2 pt-1 border-t">
|
||||
<select
|
||||
value={selectedUserId}
|
||||
onChange={(e) => setSelectedUserId(e.target.value)}
|
||||
className="flex-1 h-8 rounded-md border border-input bg-background px-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
>
|
||||
<option value="">Select org member to add…</option>
|
||||
{available.map((m) => (
|
||||
<option key={m.user_id} value={m.user_id}>
|
||||
{m.user?.full_name || m.user?.email || m.user_id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button size="sm" onClick={handleAdd} disabled={!selectedUserId || isAdding}>
|
||||
{isAdding ? <Loader2 className="w-3 h-3 animate-spin mr-1" /> : <UserPlus className="w-3 h-3 mr-1" />}
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{available.length === 0 && members.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground pt-1 border-t">All org members are already in this department.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DepartmentsPage() {
|
||||
const params = useParams<{ orgId?: string }>();
|
||||
const { orgId: fallbackOrgId } = useCurrentOrganizationId();
|
||||
@@ -33,14 +371,37 @@ export default function DepartmentsPage() {
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [departments, setDepartments] = useState<Department[]>([]);
|
||||
const [principals, setPrincipals] = useState<Principal[]>([]);
|
||||
const [linkedPrincipals, setLinkedPrincipals] = useState<Record<string, Principal[]>>({});
|
||||
const [unlinkingKey, setUnlinkingKey] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
|
||||
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
|
||||
const [isLinkDialogOpen, setIsLinkDialogOpen] = useState(false);
|
||||
const [linkingDept, setLinkingDept] = useState<Department | null>(null);
|
||||
const [selectedPrincipalId, setSelectedPrincipalId] = useState("");
|
||||
const [isLinking, setIsLinking] = useState(false);
|
||||
const [editingDept, setEditingDept] = useState<Department | null>(null);
|
||||
const [formData, setFormData] = useState({ name: "", description: "" });
|
||||
const [expandedPolicies, setExpandedPolicies] = useState<Set<string>>(new Set());
|
||||
const [expandedMembers, setExpandedMembers] = useState<Set<string>>(new Set());
|
||||
|
||||
const togglePolicyPanel = (deptId: string) => {
|
||||
setExpandedPolicies((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(deptId) ? next.delete(deptId) : next.add(deptId);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleMembersPanel = (deptId: string) => {
|
||||
setExpandedMembers((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(deptId) ? next.delete(deptId) : next.add(deptId);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const fetchLinkedPrincipals = useCallback(async (currentOrgId: string, deptList: Department[]) => {
|
||||
if (!deptList.length) return;
|
||||
@@ -61,9 +422,13 @@ export default function DepartmentsPage() {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const response = await api.organizations.getDepartments(currentOrgId);
|
||||
const [response, principalsRes] = await Promise.all([
|
||||
api.organizations.getDepartments(currentOrgId),
|
||||
api.organizations.getPrincipals(currentOrgId),
|
||||
]);
|
||||
const deptList = response.departments || [];
|
||||
setDepartments(deptList);
|
||||
setPrincipals(principalsRes.principals || []);
|
||||
await fetchLinkedPrincipals(currentOrgId, deptList);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch departments:", err);
|
||||
@@ -76,6 +441,7 @@ export default function DepartmentsPage() {
|
||||
useEffect(() => {
|
||||
setError(null);
|
||||
setDepartments([]);
|
||||
setPrincipals([]);
|
||||
setLinkedPrincipals({});
|
||||
if (!orgId) {
|
||||
setIsLoading(false);
|
||||
@@ -103,6 +469,29 @@ export default function DepartmentsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleLinkPrincipal = async () => {
|
||||
if (!orgId || !linkingDept || !selectedPrincipalId) return;
|
||||
setIsLinking(true);
|
||||
try {
|
||||
await api.organizations.linkPrincipalToDepartment(orgId, selectedPrincipalId, linkingDept.id);
|
||||
toast({ title: "Principal linked", description: "Principal linked to department." });
|
||||
setLinkingDept(null);
|
||||
setSelectedPrincipalId("");
|
||||
setIsLinkDialogOpen(false);
|
||||
await fetchDepartments(orgId);
|
||||
} catch {
|
||||
toast({ variant: "destructive", title: "Failed to link principal to department" });
|
||||
} finally {
|
||||
setIsLinking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openLinkDialog = (dept: Department) => {
|
||||
setLinkingDept(dept);
|
||||
setSelectedPrincipalId("");
|
||||
setIsLinkDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleCreateDepartment = async () => {
|
||||
if (!orgId || !formData.name.trim()) return;
|
||||
try {
|
||||
@@ -162,6 +551,11 @@ export default function DepartmentsPage() {
|
||||
);
|
||||
});
|
||||
|
||||
// Principals not yet linked to the dept being linked
|
||||
const availablePrincipalsToLink = linkingDept
|
||||
? principals.filter((p) => !(linkedPrincipals[linkingDept.id] || []).some((lp) => lp.id === p.id))
|
||||
: principals;
|
||||
|
||||
return (
|
||||
<div className="page-container">
|
||||
<div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
@@ -260,6 +654,36 @@ export default function DepartmentsPage() {
|
||||
<div className="mt-2 text-xs text-muted-foreground">
|
||||
Created {new Date(dept.created_at).toLocaleDateString()}
|
||||
</div>
|
||||
|
||||
{/* Members toggle */}
|
||||
<button
|
||||
className="mt-3 flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
onClick={() => toggleMembersPanel(dept.id)}
|
||||
>
|
||||
<Users className="w-3 h-3" />
|
||||
Members
|
||||
{expandedMembers.has(dept.id) ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
|
||||
</button>
|
||||
|
||||
{/* Members panel */}
|
||||
{orgId && expandedMembers.has(dept.id) && (
|
||||
<DepartmentMembersPanel orgId={orgId} deptId={dept.id} />
|
||||
)}
|
||||
|
||||
{/* Certificate policy toggle */}
|
||||
<button
|
||||
className="mt-3 flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
onClick={() => orgId && togglePolicyPanel(dept.id)}
|
||||
>
|
||||
<ShieldCheck className="w-3 h-3" />
|
||||
Certificate Policy
|
||||
{expandedPolicies.has(dept.id) ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
|
||||
</button>
|
||||
|
||||
{/* Certificate policy panel */}
|
||||
{orgId && expandedPolicies.has(dept.id) && (
|
||||
<DepartmentCertPolicyPanel orgId={orgId} deptId={dept.id} />
|
||||
)}
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
@@ -272,6 +696,10 @@ export default function DepartmentsPage() {
|
||||
<Edit2 className="w-4 h-4 mr-2" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => openLinkDialog(dept)}>
|
||||
<LinkIcon className="w-4 h-4 mr-2" />
|
||||
Link Principal
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
@@ -371,6 +799,57 @@ export default function DepartmentsPage() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Link Principal to Department Dialog */}
|
||||
<Dialog
|
||||
open={isLinkDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) { setLinkingDept(null); setSelectedPrincipalId(""); }
|
||||
setIsLinkDialogOpen(open);
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Link Principal to Department</DialogTitle>
|
||||
<DialogDescription>
|
||||
Link a principal to <strong>{linkingDept?.name}</strong>. All department members will gain access to the principal.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="principal-select">Principal</Label>
|
||||
{availablePrincipalsToLink.length === 0 ? (
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{principals.length === 0
|
||||
? "No principals exist yet. Create one on the Principals page."
|
||||
: "All principals are already linked to this department."}
|
||||
</p>
|
||||
) : (
|
||||
<Select value={selectedPrincipalId} onValueChange={setSelectedPrincipalId}>
|
||||
<SelectTrigger id="principal-select" className="mt-1">
|
||||
<SelectValue placeholder="Choose a principal…" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availablePrincipalsToLink.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setIsLinkDialogOpen(false)}>Cancel</Button>
|
||||
<Button
|
||||
onClick={handleLinkPrincipal}
|
||||
disabled={!selectedPrincipalId || isLinking || availablePrincipalsToLink.length === 0}
|
||||
>
|
||||
{isLinking && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Link
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+346
-54
@@ -1,8 +1,9 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Search, Plus, MoreHorizontal, Shield, User, Mail, Clock, Loader2 } from "lucide-react";
|
||||
import { Search, Shield, ShieldCheck, Mail, Loader2, Copy, Check, ExternalLink } from "lucide-react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
@@ -13,9 +14,27 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { api, OrganizationMember } from "@/lib/api";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { api, OrganizationMember, ApiError, OrgInvite } from "@/lib/api";
|
||||
import { useCurrentOrganizationId } from "@/hooks/useCurrentOrganization";
|
||||
import { useAuth } from "@/contexts/AuthContext";
|
||||
import { MoreHorizontal } from "lucide-react";
|
||||
|
||||
const getInitials = (name: string | null | undefined): string => {
|
||||
if (!name) return "?";
|
||||
@@ -27,16 +46,63 @@ const getInitials = (name: string | null | undefined): string => {
|
||||
.slice(0, 2);
|
||||
};
|
||||
|
||||
function RoleBadge({ role }: { role: string }) {
|
||||
const r = (role || "").toLowerCase();
|
||||
if (r === "owner") {
|
||||
return (
|
||||
<Badge className="bg-purple-500/10 text-purple-600 border-purple-200 text-xs">
|
||||
<ShieldCheck className="w-3 h-3 mr-1" />Owner
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (r === "admin") {
|
||||
return (
|
||||
<Badge className="bg-blue-500/10 text-blue-600 border-blue-200 text-xs">
|
||||
<Shield className="w-3 h-3 mr-1" />Admin
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs text-muted-foreground">
|
||||
Member
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MembersPage() {
|
||||
const params = useParams<{ orgId?: string }>();
|
||||
const { orgId: fallbackOrgId } = useCurrentOrganizationId();
|
||||
const orgId = params.orgId || fallbackOrgId;
|
||||
const { toast } = useToast();
|
||||
const { user: currentUser } = useAuth();
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [members, setMembers] = useState<OrganizationMember[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Invite dialog
|
||||
const [showInvite, setShowInvite] = useState(false);
|
||||
const [inviteEmail, setInviteEmail] = useState("");
|
||||
const [inviteRole, setInviteRole] = useState("member");
|
||||
const [isInviting, setIsInviting] = useState(false);
|
||||
const [inviteError, setInviteError] = useState<string | null>(null);
|
||||
|
||||
// Invite link dialog (shown when email is not configured)
|
||||
const [inviteLink, setInviteLink] = useState<string | null>(null);
|
||||
const [inviteLinkEmail, setInviteLinkEmail] = useState("");
|
||||
const [linkCopied, setLinkCopied] = useState(false);
|
||||
|
||||
// Change role dialog
|
||||
const [changeRoleMember, setChangeRoleMember] = useState<OrganizationMember | null>(null);
|
||||
const [newRole, setNewRole] = useState("member");
|
||||
const [isChangingRole, setIsChangingRole] = useState(false);
|
||||
|
||||
// Pending invites
|
||||
const [invites, setInvites] = useState<OrgInvite[]>([]);
|
||||
const [isInvitesLoading, setIsInvitesLoading] = useState(false);
|
||||
const [cancellingInviteId, setCancellingInviteId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setError(null);
|
||||
setMembers([]);
|
||||
@@ -59,7 +125,20 @@ export default function MembersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const fetchInvites = async () => {
|
||||
try {
|
||||
setIsInvitesLoading(true);
|
||||
const res = await api.organizations.getInvites(orgId);
|
||||
setInvites(res.invites || []);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch invites:", err);
|
||||
} finally {
|
||||
setIsInvitesLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchMembers();
|
||||
fetchInvites();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [orgId]);
|
||||
|
||||
@@ -71,19 +150,87 @@ export default function MembersPage() {
|
||||
);
|
||||
});
|
||||
|
||||
const handleInvite = async () => {
|
||||
if (!orgId) return;
|
||||
setInviteError(null);
|
||||
if (!inviteEmail.trim()) {
|
||||
setInviteError("Email is required.");
|
||||
return;
|
||||
}
|
||||
setIsInviting(true);
|
||||
try {
|
||||
const res = await api.organizations.createInvite(orgId, inviteEmail.trim(), inviteRole);
|
||||
const link = res.invite?.invite_link;
|
||||
setShowInvite(false);
|
||||
// Refresh invites list
|
||||
const updated = await api.organizations.getInvites(orgId);
|
||||
setInvites(updated.invites || []);
|
||||
if (link) {
|
||||
// Email delivery not configured — show copyable link as fallback
|
||||
setInviteLink(link);
|
||||
setInviteLinkEmail(inviteEmail.trim());
|
||||
} else {
|
||||
// Email was sent successfully
|
||||
toast({ title: "Invitation sent", description: `Invite email sent to ${inviteEmail.trim()}.` });
|
||||
}
|
||||
setInviteEmail("");
|
||||
setInviteRole("member");
|
||||
} catch (err) {
|
||||
setInviteError(err instanceof ApiError ? err.message : "Failed to send invitation.");
|
||||
} finally {
|
||||
setIsInviting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleChangeRole = async () => {
|
||||
if (!orgId || !changeRoleMember) return;
|
||||
setIsChangingRole(true);
|
||||
try {
|
||||
const updated = await api.organizations.updateMemberRole(orgId, changeRoleMember.user_id, newRole.toUpperCase());
|
||||
setMembers((prev) =>
|
||||
prev.map((m) => (m.id === changeRoleMember.id ? { ...m, role: updated.member.role } : m))
|
||||
);
|
||||
toast({
|
||||
title: "Role updated",
|
||||
description: `${changeRoleMember.user?.full_name || changeRoleMember.user?.email} is now a ${newRole}.`,
|
||||
});
|
||||
setChangeRoleMember(null);
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Failed to update role",
|
||||
description: err instanceof ApiError ? err.message : "Something went wrong.",
|
||||
});
|
||||
} finally {
|
||||
setIsChangingRole(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveMember = async (member: OrganizationMember) => {
|
||||
if (!orgId) return;
|
||||
try {
|
||||
await api.organizations.removeMember(orgId, member.user_id);
|
||||
setMembers((prev) => prev.filter((m) => m.id !== member.id));
|
||||
toast({
|
||||
title: "Member removed",
|
||||
description: `${member.user?.full_name || member.user?.email} has been removed.`,
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Failed to remove member",
|
||||
description: err instanceof ApiError ? err.message : "Something went wrong.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-container">
|
||||
<div className="page-header flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="page-title">Members</h1>
|
||||
<p className="page-description">
|
||||
Manage organization members and invitations
|
||||
</p>
|
||||
</div>
|
||||
<Button>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Invite member
|
||||
</Button>
|
||||
<div className="page-header">
|
||||
<h1 className="page-title">Members</h1>
|
||||
<p className="page-description">
|
||||
Manage organization members and invitations
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="members" className="w-full">
|
||||
@@ -92,7 +239,7 @@ export default function MembersPage() {
|
||||
Members ({members.length})
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="invites">
|
||||
Pending Invites (0)
|
||||
Invitations {invites.length > 0 && <span className="ml-1.5 inline-flex items-center justify-center w-4 h-4 rounded-full bg-primary text-primary-foreground text-[10px] font-bold">{invites.length}</span>}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
@@ -139,44 +286,40 @@ export default function MembersPage() {
|
||||
<p className="font-medium text-foreground truncate">
|
||||
{member.user?.full_name || member.user?.email}
|
||||
</p>
|
||||
{member.role === "admin" && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<Shield className="w-3 h-3 mr-1" />
|
||||
Admin
|
||||
</Badge>
|
||||
)}
|
||||
{member.role === "owner" && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<Shield className="w-3 h-3 mr-1" />
|
||||
Owner
|
||||
</Badge>
|
||||
)}
|
||||
<RoleBadge role={member.role} />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground truncate">
|
||||
{member.user?.email}
|
||||
</p>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<MoreHorizontal className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem>
|
||||
<User className="w-4 h-4 mr-2" />
|
||||
View profile
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Shield className="w-4 h-4 mr-2" />
|
||||
Change role
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive">
|
||||
Remove member
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{/* Actions — hide for self and for owners (can't modify owner here) */}
|
||||
{member.user?.id !== currentUser?.id && (member.role || "").toLowerCase() !== "owner" && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<MoreHorizontal className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setChangeRoleMember(member);
|
||||
setNewRole((member.role || "member").toLowerCase());
|
||||
}}
|
||||
>
|
||||
<Shield className="w-4 h-4 mr-2" />
|
||||
Change role
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() => handleRemoveMember(member)}
|
||||
>
|
||||
Remove member
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -186,15 +329,164 @@ export default function MembersPage() {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="invites">
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="p-8 text-center text-muted-foreground">
|
||||
No pending invitations
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-sm font-semibold">Pending invitations</h3>
|
||||
<span className="text-sm text-muted-foreground">{isInvitesLoading ? 'Loading...' : `${invites.length}`}</span>
|
||||
</div>
|
||||
{isInvitesLoading ? (
|
||||
<div className="p-4 text-center text-muted-foreground">Loading invites...</div>
|
||||
) : invites.length === 0 ? (
|
||||
<div className="p-4 text-center text-muted-foreground">No pending invitations</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{invites.map((inv) => (
|
||||
<div key={inv.id} className="py-3 flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="font-medium">{inv.email}</div>
|
||||
<div className="text-sm text-muted-foreground">Role: {inv.role} • Expires: {new Date(inv.expires_at).toLocaleString()}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button size="sm" variant="ghost" onClick={() => { void (async () => {
|
||||
if (!orgId) return;
|
||||
setCancellingInviteId(inv.id);
|
||||
try {
|
||||
await api.organizations.cancelInvite(orgId, inv.id);
|
||||
setInvites((prev) => prev.filter((i) => i.id !== inv.id));
|
||||
toast({ title: 'Invite cancelled' });
|
||||
} catch (err) {
|
||||
toast({ variant: 'destructive', title: 'Failed to cancel invite' });
|
||||
} finally {
|
||||
setCancellingInviteId(null);
|
||||
}
|
||||
})() }}>
|
||||
{cancellingInviteId === inv.id ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Cancel'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Mail className="w-4 h-4 text-muted-foreground" />
|
||||
<h3 className="text-sm font-semibold">Send an invitation</h3>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label>Email address</Label>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="colleague@example.com"
|
||||
value={inviteEmail}
|
||||
onChange={(e) => setInviteEmail(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Role</Label>
|
||||
<Select value={inviteRole} onValueChange={setInviteRole}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="member">Member</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{inviteError && (
|
||||
<p className="text-sm text-destructive">{inviteError}</p>
|
||||
)}
|
||||
<Button onClick={handleInvite} disabled={isInviting || !inviteEmail.trim()} className="w-full">
|
||||
{isInviting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
<Mail className="w-4 h-4 mr-2" />
|
||||
Send invitation
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* ── Invite link dialog (shown when SMTP not configured) ────────────────── */}
|
||||
<Dialog open={!!inviteLink} onOpenChange={(o) => { if (!o) { setInviteLink(null); setLinkCopied(false); } }}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
Share this invite link
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Email delivery is not configured. Share this link directly with <strong>{inviteLinkEmail}</strong>.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3 py-2">
|
||||
<div className="flex items-center gap-2 rounded-md border bg-muted px-3 py-2">
|
||||
<span className="flex-1 text-xs text-muted-foreground break-all font-mono">{inviteLink}</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0"
|
||||
onClick={() => {
|
||||
if (inviteLink) {
|
||||
navigator.clipboard.writeText(inviteLink);
|
||||
setLinkCopied(true);
|
||||
setTimeout(() => setLinkCopied(false), 2000);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{linkCopied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This link expires in 7 days. The recipient must already have an account or will be prompted to create one.
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button onClick={() => { setInviteLink(null); setLinkCopied(false); }}>Done</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* ── Change role dialog ─────────────────────────────────────────────────── */}
|
||||
<Dialog open={!!changeRoleMember} onOpenChange={(o) => { if (!o) setChangeRoleMember(null); }}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Change role</DialogTitle>
|
||||
<DialogDescription>
|
||||
Update the role for {changeRoleMember?.user?.full_name || changeRoleMember?.user?.email}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-2">
|
||||
<Label className="mb-2 block">New role</Label>
|
||||
<Select value={newRole} onValueChange={setNewRole} disabled={isChangingRole}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="member">Member</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setChangeRoleMember(null)} disabled={isChangingRole}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleChangeRole} disabled={isChangingRole}>
|
||||
{isChangingRole && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Layers, GitBranch, Building2, Loader2, Link } from "lucide-react";
|
||||
import { api, MyOrgMembership } from "@/lib/api";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
function MembershipsSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{[1, 2].map((i) => (
|
||||
<div key={i} className="rounded-xl border border-border bg-card p-5 space-y-4">
|
||||
<Skeleton className="h-5 w-48" />
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Skeleton className="h-24 w-full rounded-lg" />
|
||||
<Skeleton className="h-24 w-full rounded-lg" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MyMembershipsPage() {
|
||||
const [orgs, setOrgs] = useState<MyOrgMembership[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
api.users.getMyMemberships()
|
||||
.then((res) => setOrgs(res.orgs ?? []))
|
||||
.catch(console.error)
|
||||
.finally(() => setIsLoading(false));
|
||||
}, []);
|
||||
|
||||
const totalDepts = orgs.reduce((s, o) => s + o.departments.length, 0);
|
||||
const totalPrincipals = orgs.reduce((s, o) => s + o.principals.length, 0);
|
||||
|
||||
return (
|
||||
<div className="page-container">
|
||||
<div className="page-header">
|
||||
<h1 className="page-title">My Memberships</h1>
|
||||
<p className="page-description">
|
||||
Departments and principals you belong to across your organizations
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<MembershipsSkeleton />
|
||||
) : orgs.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-20 text-center text-muted-foreground">
|
||||
<Building2 className="w-10 h-10 mb-3 opacity-30" />
|
||||
<p className="text-sm">You're not a member of any organizations yet.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{/* Summary chips */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<div className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-1.5 text-sm">
|
||||
<Layers className="w-3.5 h-3.5 text-primary" />
|
||||
<span className="font-medium">{totalDepts}</span>
|
||||
<span className="text-muted-foreground">department{totalDepts !== 1 ? "s" : ""}</span>
|
||||
</div>
|
||||
<div className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-1.5 text-sm">
|
||||
<GitBranch className="w-3.5 h-3.5 text-primary" />
|
||||
<span className="font-medium">{totalPrincipals}</span>
|
||||
<span className="text-muted-foreground">principal{totalPrincipals !== 1 ? "s" : ""}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{orgs.map((org) => (
|
||||
<div
|
||||
key={org.org_id}
|
||||
className="rounded-xl border border-border bg-card overflow-hidden"
|
||||
>
|
||||
{/* Org header */}
|
||||
<div className="flex items-center gap-3 px-5 py-4 border-b border-border bg-muted/30">
|
||||
<div className="w-7 h-7 rounded bg-primary/10 flex items-center justify-center shrink-0">
|
||||
<Building2 className="w-3.5 h-3.5 text-primary" />
|
||||
</div>
|
||||
<span className="font-semibold text-foreground text-sm">{org.org_name}</span>
|
||||
<Badge variant="outline" className="capitalize text-xs ml-auto">
|
||||
{org.role.toLowerCase()}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 divide-y md:divide-y-0 md:divide-x divide-border">
|
||||
{/* Departments */}
|
||||
<div className="p-5 space-y-3">
|
||||
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
<Layers className="w-3.5 h-3.5" />
|
||||
Departments
|
||||
</div>
|
||||
{org.departments.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground py-2">
|
||||
Not assigned to any departments.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{org.departments.map((dept) => (
|
||||
<li
|
||||
key={dept.id}
|
||||
className="flex items-start gap-2.5 rounded-lg border border-border bg-background px-3 py-2.5"
|
||||
>
|
||||
<Layers className="w-3.5 h-3.5 mt-0.5 text-primary shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium text-foreground truncate">{dept.name}</p>
|
||||
{dept.description && (
|
||||
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-1">{dept.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Principals */}
|
||||
<div className="p-5 space-y-3">
|
||||
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
<GitBranch className="w-3.5 h-3.5" />
|
||||
Principals
|
||||
</div>
|
||||
{org.principals.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground py-2">
|
||||
No principals assigned.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{org.principals.map((p) => (
|
||||
<li
|
||||
key={p.id}
|
||||
className="flex items-start gap-2.5 rounded-lg border border-border bg-background px-3 py-2.5"
|
||||
>
|
||||
<GitBranch className="w-3.5 h-3.5 mt-0.5 text-primary shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-foreground truncate">{p.name}</p>
|
||||
{p.description && (
|
||||
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-1">{p.description}</p>
|
||||
)}
|
||||
</div>
|
||||
{p.via_department && (
|
||||
<span className="shrink-0 inline-flex items-center gap-1 text-[10px] text-muted-foreground border border-border rounded px-1.5 py-0.5">
|
||||
<Link className="w-2.5 h-2.5" />
|
||||
via dept
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user