Spaces:
Paused

miracle / frontend /apps /internal /src /components /WorkspaceSettings.tsx
dushyantsingh0
backend stabilisation
a22dc86
Raw History Blame Contribute Delete
21.9 kB
import React, { useState, useRef, useEffect } from 'react';
import { useUsers, useWorkspaces, type User, api, useWorkspace } from '@nexus/shared';
import { MoreHorizontal, Edit3, Trash2, AlertCircle, RefreshCcw, Shield, Palette, Image } from 'lucide-react';
import styles from './WorkspaceSettings.module.css';
interface WorkspaceSettingsProps {
workspaceId?: string;
}
export const WorkspaceSettings: React.FC<WorkspaceSettingsProps> = ({ workspaceId }) => {
const { users, loading: usersLoading, addUser, updateUser, deleteUser, refresh } = useUsers(workspaceId);
const { workspaces, refresh: refreshWorkspaces } = useWorkspaces();
const { workspace: freshWorkspace, refresh: refreshActiveWs } = useWorkspace(workspaceId);
const [isModalOpen, setIsModalOpen] = useState(false);
const [formData, setFormData] = useState({
email: '',
fullName: '',
role: '3sc_agent',
team: 'SUCCESS',
password: 'TemporaryPassword123!'
});
const [formError, setFormError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [activeMenuId, setActiveMenuId] = useState<string | null>(null);
const [editingUser, setEditingUser] = useState<User | null>(null);
const [deletingUser, setDeletingUser] = useState<User | null>(null);
const menuRef = useRef<HTMLDivElement>(null);
// Branding State
const [brandingLogo, setBrandingLogo] = useState('');
const [brandingColor, setBrandingColor] = useState('#7c3aed');
const [isBrandingSubmitting, setIsBrandingSubmitting] = useState(false);
const currentWorkspace = (freshWorkspace?.id === workspaceId) ? freshWorkspace : (workspaces.find(w => w.id === workspaceId) || workspaces[0]);
useEffect(() => {
if (currentWorkspace?.branding) {
setBrandingLogo(currentWorkspace.branding.logo_url || '');
setBrandingColor(currentWorkspace.branding.colors?.primary || '#7c3aed');
}
}, [currentWorkspace]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
setActiveMenuId(null);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const handleUpdateBranding = async () => {
if (!currentWorkspace) return;
setIsBrandingSubmitting(true);
// OPTIMISTIC UI: Inject CSS variables immediately for "Instant" feel
document.documentElement.style.setProperty('--primary', brandingColor);
// Auto-calculate hover/accent colors based on primary
document.documentElement.style.setProperty('--primary-hover', brandingColor + 'ee');
try {
await api.patch('/workspace/', {
workspace_id: workspaceId,
branding: {
...currentWorkspace.branding,
logo_url: brandingLogo,
colors: {
...currentWorkspace.branding?.colors,
primary: brandingColor
}
}
});
// Invalidate caches
sessionStorage.removeItem('nexus_active_ws_v1');
await refreshActiveWs(workspaceId);
await refreshWorkspaces();
} catch (err) {
console.error("Failed to update branding:", err);
} finally {
setIsBrandingSubmitting(false);
}
};
const handleAddMember = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
setFormError(null);
try {
await addUser({
email: formData.email,
full_name: formData.fullName,
role: formData.role,
team: formData.team,
password: formData.password,
workspace_id: workspaceId // Force explicit targeting
});
setIsModalOpen(false);
setFormData({
email: '',
fullName: '',
role: '3sc_agent',
team: 'SUCCESS',
password: 'TemporaryPassword123!'
});
} catch (err: any) {
setFormError(err.message);
} finally {
setIsSubmitting(false);
}
};
const handleUpdateMember = async (e: React.FormEvent) => {
e.preventDefault();
if (!editingUser) return;
setIsSubmitting(true);
setFormError(null);
try {
await updateUser(editingUser.id, {
full_name: editingUser.full_name,
role: editingUser.role,
team: editingUser.team
});
setEditingUser(null);
} catch (err: any) {
setFormError(err.message);
} finally {
setIsSubmitting(false);
}
};
const handleDeleteMember = async () => {
if (!deletingUser) return;
setIsSubmitting(true);
try {
await deleteUser(deletingUser.id);
setDeletingUser(null);
} catch (err: any) {
alert("Failed to remove member: " + err.message);
} finally {
setIsSubmitting(false);
}
};
const THEME_PRESETS = [
{ name: 'Nexus Violet', color: '#7c3aed' },
{ name: 'Royal Indigo', color: '#4338ca' },
{ name: 'Ocean Blue', color: '#3b82f6' },
{ name: 'Emerald Green', color: '#10b981' },
{ name: 'Slate Steel', color: '#475569' },
{ name: 'Crimson Red', color: '#ef4444' },
{ name: 'Amber Glow', color: '#f59e0b' },
{ name: 'Deep Rose', color: '#e11d48' },
];
return (
<div className={styles.container}>
<header className={styles.header}>
<h1 className={styles.workspaceName}>
{workspaceId === 'all' ? 'System-Wide Directory' : (currentWorkspace?.name || 'Workspace Settings')}
</h1>
<p className={styles.description}>
{workspaceId === 'all'
? 'Unified view of all internal staff and cross-workspace members. Manage global access and system-level permissions.'
: "Manage your organization's identity, team, and security settings. Use this panel to control access and oversee your dedicated support environment."}
</p>
</header>
{workspaceId !== 'all' && currentWorkspace && (
<section className={styles.brandingSection}>
<div className={styles.sectionHeader}>
<h2 className={styles.sectionTitle}>Identity & Branding</h2>
</div>
<div className={styles.brandingGrid}>
<div className={styles.brandingItem}>
<label className={styles.label}>
<Image size={14} style={{ marginRight: 8, verticalAlign: 'middle' }} />
Workspace Logo URL
</label>
<div style={{ display: 'flex', gap: 12 }}>
<input
className={styles.input}
value={brandingLogo}
onChange={e => setBrandingLogo(e.target.value)}
placeholder="https://example.com/logo.png"
/>
<div className={styles.logoPreview}>
{brandingLogo ? (
<img src={brandingLogo} alt="Logo" />
) : (
<Image size={20} style={{ opacity: 0.2 }} />
)}
</div>
</div>
</div>
<div className={styles.brandingItem}>
<label className={styles.label}>
<Palette size={14} style={{ marginRight: 8, verticalAlign: 'middle' }} />
Workspace Theme Colors
</label>
<div className={styles.themePickerContainer}>
<div className={styles.colorPresets}>
{THEME_PRESETS.map(preset => (
<button
key={preset.color}
className={`${styles.presetBtn} ${brandingColor === preset.color ? styles.activePreset : ''}`}
style={{ backgroundColor: preset.color }}
title={preset.name}
onClick={() => {
setBrandingColor(preset.color);
// Instant visual preview
document.documentElement.style.setProperty('--primary', preset.color);
}}
/>
))}
</div>
<div className={styles.colorPicker}>
<input
type="color"
className={styles.colorInput}
value={brandingColor}
onChange={e => {
setBrandingColor(e.target.value);
document.documentElement.style.setProperty('--primary', e.target.value);
}}
/>
<input
className={styles.colorValue}
value={brandingColor}
onChange={e => {
setBrandingColor(e.target.value);
if (e.target.value.startsWith('#') && e.target.value.length === 7) {
document.documentElement.style.setProperty('--primary', e.target.value);
}
}}
/>
</div>
</div>
</div>
</div>
<div className={styles.brandingActions}>
<button
className={styles.saveBrandingBtn}
onClick={handleUpdateBranding}
disabled={isBrandingSubmitting}
>
{isBrandingSubmitting ? (
<>
<RefreshCcw size={16} className={styles.spinning} style={{ marginRight: 8 }} />
Saving Branding...
</>
) : (
'Save Branding Changes'
)}
</button>
</div>
<div className={styles.brandingFooter}>
<Shield size={16} />
Changes propagate across customer and internal portals immediately.
</div>
</section>
)}
<section className={styles.teamSection}>
<div className={styles.sectionHeader}>
<h2 className={styles.sectionTitle}>Workspace Team</h2>
<div className={styles.headerActions}>
<button
className={styles.refreshBtn}
onClick={() => refresh()}
disabled={usersLoading}
title="Force Refresh (Bypass Cache)"
>
<RefreshCcw size={16} className={usersLoading ? styles.spinning : ''} />
</button>
<button className={styles.addBtn} onClick={() => setIsModalOpen(true)}>
<span>+</span> Add Member
</button>
</div>
</div>
<div className={styles.tableCard}>
<table className={styles.table}>
<thead>
<tr>
<th className={styles.th}>Member</th>
<th className={styles.th}>Role</th>
<th className={styles.th}>Team</th>
<th className={styles.th}>Status</th>
<th className={styles.th}></th>
</tr>
</thead>
<tbody>
{usersLoading && users.length === 0 ? (
<tr><td colSpan={5} className={styles.td}>Synchronizing team data...</td></tr>
) : users.length === 0 ? (
<tr><td colSpan={5} className={styles.td}>No members found in this workspace.</td></tr>
) : (
users.map(user => (
<tr key={user.id}>
<td className={styles.td}>
<div className={styles.memberCell}>
<div className={styles.avatar}>{(user.full_name?.slice(0,1) || user.email?.slice(0,1) || '?').toUpperCase()}</div>
<div className={styles.memberInfo}>
<span className={styles.memberName}>{user.full_name}</span>
<span className={styles.memberEmail}>{user.email}</span>
</div>
</div>
</td>
<td className={styles.td}>
<span className={`${styles.roleBadge} ${user.role.includes('admin') ? styles.roleAdmin : ''}`}>
{user.role.replace('_', ' ')}
</span>
</td>
<td className={styles.td}>
<span className={styles.teamTag}>{user.team || '—'}</span>
</td>
<td className={styles.td}>
<div className={styles.statusCell}>
<span className={styles.statusDot} />
Active Member
</div>
</td>
<td className={styles.td} style={{ textAlign: 'right', position: 'relative' }}>
<button
className={styles.actionBtn}
onClick={() => setActiveMenuId(activeMenuId === user.id ? null : user.id)}
>
<MoreHorizontal size={16} />
</button>
{activeMenuId === user.id && (
<div className={styles.actionMenu} ref={menuRef}>
<button className={styles.menuItem} onClick={() => { setEditingUser(user); setActiveMenuId(null); setFormError(null); }}>
<Edit3 size={14} /> Edit Details
</button>
<button className={`${styles.menuItem} ${styles.menuItemDestructive}`} onClick={() => { setDeletingUser(user); setActiveMenuId(null); }}>
<Trash2 size={14} /> Remove Access
</button>
</div>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</section>
{/* Add Member Modal */}
{isModalOpen && (
<div className={styles.modalOverlay} onClick={() => setIsModalOpen(false)}>
<div className={styles.modal} onClick={e => e.stopPropagation()}>
<h2 className={styles.modalTitle}>Add Team Member</h2>
<p className={styles.modalSub}>Grant workspace access to a new team member.</p>
<form onSubmit={handleAddMember}>
<div className={styles.formGroup}>
<label className={styles.label}>Full Name</label>
<input
className={styles.input}
placeholder="John Doe"
required
value={formData.fullName}
onChange={e => setFormData({...formData, fullName: e.target.value})}
/>
</div>
<div className={styles.formGroup}>
<label className={styles.label}>Email Address</label>
<input
className={styles.input}
type="email"
placeholder="john@organization.com"
required
value={formData.email}
onChange={e => setFormData({...formData, email: e.target.value})}
/>
</div>
<div className={styles.formGroup}>
<label className={styles.label}>Department Team</label>
<select
className={styles.select}
value={formData.team}
onChange={e => setFormData({...formData, team: e.target.value})}
required
>
<option value="ENGINEERING">Engineering</option>
<option value="FINANCE">Finance</option>
<option value="SUCCESS">Customer Success</option>
<option value="ACCOUNT">Account Management</option>
<option value="SECURITY">Security / SecOps</option>
<option value="COMPLIANCE">Compliance / Legal</option>
<option value="GENERAL">General / Admin</option>
<option value="OTHER">Other</option>
</select>
</div>
<div className={styles.formGroup}>
<label className={styles.label}>Workspace Role</label>
<select
className={styles.select}
value={formData.role}
onChange={e => setFormData({...formData, role: e.target.value})}
>
<option value="3sc_agent">SC Agent (Staff)</option>
<option value="3sc_lead">SC Lead (Staff)</option>
<option value="3sc_admin">Co-Admin (Staff)</option>
<option value="customer_admin">Customer Admin</option>
<option value="customer_user">Customer User</option>
</select>
</div>
{formError && <div className={styles.error}>{formError}</div>}
<div className={styles.modalActions}>
<button type="button" className={styles.cancelBtn} onClick={() => setIsModalOpen(false)}>Cancel</button>
<button type="submit" className={styles.submitBtn} disabled={isSubmitting}>
{isSubmitting ? 'Creating...' : 'Create Member'}
</button>
</div>
</form>
</div>
</div>
)}
{/* Edit Member Modal */}
{editingUser && (
<div className={styles.modalOverlay} onClick={() => setEditingUser(null)}>
<div className={styles.modal} onClick={e => e.stopPropagation()}>
<h2 className={styles.modalTitle}>Edit Team Member</h2>
<p className={styles.modalSub}>Update details for {editingUser.email}</p>
<form onSubmit={handleUpdateMember}>
<div className={styles.formGroup}>
<label className={styles.label}>Full Name</label>
<input
className={styles.input}
required
value={editingUser.full_name}
onChange={e => setEditingUser({...editingUser, full_name: e.target.value})}
/>
</div>
<div className={styles.formGroup}>
<label className={styles.label}>Department Team</label>
<select
className={styles.select}
value={editingUser.team || ''}
onChange={e => setEditingUser({...editingUser, team: e.target.value})}
required
>
<option value="ENGINEERING">Engineering</option>
<option value="FINANCE">Finance</option>
<option value="SUCCESS">Customer Success</option>
<option value="ACCOUNT">Account Management</option>
<option value="SECURITY">Security / SecOps</option>
<option value="COMPLIANCE">Compliance / Legal</option>
<option value="GENERAL">General / Admin</option>
<option value="OTHER">Other</option>
</select>
</div>
<div className={styles.formGroup}>
<label className={styles.label}>Workspace Role</label>
<select
className={styles.select}
value={editingUser.role}
onChange={e => setEditingUser({...editingUser, role: e.target.value})}
>
<option value="3sc_agent">SC Agent (Staff)</option>
<option value="3sc_lead">SC Lead (Staff)</option>
<option value="3sc_admin">Co-Admin (Staff)</option>
<option value="customer_admin">Customer Admin</option>
<option value="customer_user">Customer User</option>
</select>
</div>
{formError && <div className={styles.error}>{formError}</div>}
<div className={styles.modalActions}>
<button type="button" className={styles.cancelBtn} onClick={() => setEditingUser(null)}>Cancel</button>
<button type="submit" className={styles.submitBtn} disabled={isSubmitting}>
{isSubmitting ? 'Saving...' : 'Save Changes'}
</button>
</div>
</form>
</div>
</div>
)}
{/* Delete Confirmation Modal */}
{deletingUser && (
<div className={styles.modalOverlay} onClick={() => setDeletingUser(null)}>
<div className={`${styles.modal} ${styles.modalDestructive}`} onClick={e => e.stopPropagation()}>
<div style={{ display: 'flex', gap: 16, marginBottom: 20 }}>
<div className={styles.warningIcon}><AlertCircle size={24} /></div>
<div>
<h2 className={styles.modalTitle} style={{ marginBottom: 4 }}>Remove Access?</h2>
<p className={styles.modalSub}>
Are you sure you want to revoke access for <strong>{deletingUser.full_name}</strong> ({deletingUser.email})?
They will be immediately removed from the workspace.
</p>
</div>
</div>
<div className={styles.modalActions}>
<button type="button" className={styles.cancelBtn} onClick={() => setDeletingUser(null)}>Keep Member</button>
<button
type="button"
className={`${styles.submitBtn} ${styles.btnDestructive}`}
onClick={handleDeleteMember}
disabled={isSubmitting}
>
{isSubmitting ? 'Removing...' : 'Confirm Removal'}
</button>
</div>
</div>
</div>
)}
</div>
);
};