feat: add web app pages for org portal, thread viewer, and admin org management
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
|
||||
|
||||
interface OrgProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
role: 'ORG_OWNER' | 'ORG_ADMIN';
|
||||
organization: { id: string; slug: string; name: string };
|
||||
}
|
||||
|
||||
interface OrgAdminState {
|
||||
orgAdmin: OrgProfile | null;
|
||||
loading: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
const OrgAdminContext = createContext<OrgAdminState | null>(null);
|
||||
|
||||
export function OrgAdminProvider({ children }: { children: React.ReactNode }) {
|
||||
const [orgAdmin, setOrgAdmin] = useState<OrgProfile | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const checkSession = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/auth/org/me', { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setOrgAdmin(data);
|
||||
} else {
|
||||
setOrgAdmin(null);
|
||||
}
|
||||
} catch {
|
||||
setOrgAdmin(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { void checkSession(); }, [checkSession]);
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
const res = await fetch('/api/auth/org/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ message: 'Login failed' }));
|
||||
throw new Error(err.message ?? 'Login failed');
|
||||
}
|
||||
const data = await res.json();
|
||||
setOrgAdmin(data.orgAdmin);
|
||||
// Refresh full profile (includes organization object)
|
||||
void checkSession();
|
||||
}, [checkSession]);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await fetch('/api/auth/org/logout', { method: 'POST', credentials: 'include' });
|
||||
setOrgAdmin(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<OrgAdminContext.Provider value={{ orgAdmin, loading, login, logout }}>
|
||||
{children}
|
||||
</OrgAdminContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useOrgAdmin(): OrgAdminState {
|
||||
const ctx = useContext(OrgAdminContext);
|
||||
if (!ctx) throw new Error('useOrgAdmin must be used within <OrgAdminProvider>');
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
'use client';
|
||||
|
||||
import { use, useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useSuperAdmin } from '../../../_lib/super-admin-context';
|
||||
|
||||
export default function AdminOrgDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = use(params);
|
||||
const { admin, loading } = useSuperAdmin();
|
||||
const router = useRouter();
|
||||
const [org, setOrg] = useState<any>(null);
|
||||
const [showAdminForm, setShowAdminForm] = useState(false);
|
||||
const [adminForm, setAdminForm] = useState({ email: '', password: '', name: '', role: 'ORG_OWNER' });
|
||||
const [tenantId, setTenantId] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function load() {
|
||||
const res = await fetch(`/api/admin/orgs/${id}`);
|
||||
if (res.ok) setOrg(await res.json());
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (!admin) { router.replace('/admin/login'); return; }
|
||||
void load();
|
||||
}, [admin, loading, router, id]);
|
||||
|
||||
async function handleCreateAdmin(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch(`/api/admin/orgs/${id}/admins`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(adminForm),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.message ?? 'Failed');
|
||||
}
|
||||
setShowAdminForm(false);
|
||||
setAdminForm({ email: '', password: '', name: '', role: 'ORG_OWNER' });
|
||||
void load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAssignTenant(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch(`/api/admin/tenants/${tenantId}/org`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ organizationId: id }),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to assign');
|
||||
setTenantId('');
|
||||
void load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading || !admin) return <p className="text-gray-500">Loading...</p>;
|
||||
if (!org) return <p className="text-gray-400">Organization not found.</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button onClick={() => router.back()} className="text-sm text-gray-500 hover:text-gray-700 mb-3">← Back</button>
|
||||
<h1 className="text-2xl font-bold mb-1">{org.name}</h1>
|
||||
<p className="text-sm text-gray-500 mb-6">{org.slug}</p>
|
||||
|
||||
{/* Chapters */}
|
||||
<div className="bg-white rounded-xl border mb-6">
|
||||
<div className="px-5 py-4 border-b flex items-center justify-between">
|
||||
<h2 className="font-semibold">Chapters</h2>
|
||||
<form onSubmit={(e) => void handleAssignTenant(e)} className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={tenantId}
|
||||
onChange={(e) => setTenantId(e.target.value)}
|
||||
className="border rounded-lg px-3 py-1.5 text-sm"
|
||||
placeholder="Tenant ID to assign"
|
||||
/>
|
||||
<button type="submit" disabled={!tenantId || saving} className="bg-blue-600 text-white rounded-lg px-3 py-1.5 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">
|
||||
Assign
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 text-left">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">Name</th>
|
||||
<th className="px-4 py-3 font-medium">Slug</th>
|
||||
<th className="px-4 py-3 font-medium">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{(org.tenants ?? []).map((t: any) => (
|
||||
<tr key={t.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3 font-medium">{t.name}</td>
|
||||
<td className="px-4 py-3 text-gray-500">{t.slug}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`text-xs font-medium px-2 py-1 rounded-full ${t.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
|
||||
{t.isActive ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{org.tenants?.length === 0 && <p className="p-4 text-gray-400">No chapters assigned.</p>}
|
||||
</div>
|
||||
|
||||
{/* Org Admins */}
|
||||
<div className="bg-white rounded-xl border">
|
||||
<div className="px-5 py-4 border-b flex items-center justify-between">
|
||||
<h2 className="font-semibold">Org Admins</h2>
|
||||
<button
|
||||
onClick={() => setShowAdminForm(!showAdminForm)}
|
||||
className="bg-blue-600 text-white rounded-lg px-3 py-1.5 text-sm font-medium hover:bg-blue-700"
|
||||
>
|
||||
Add Admin
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showAdminForm && (
|
||||
<form onSubmit={(e) => void handleCreateAdmin(e)} className="p-5 border-b flex flex-col gap-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Email</label>
|
||||
<input type="email" value={adminForm.email} onChange={(e) => setAdminForm({ ...adminForm, email: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Password</label>
|
||||
<input type="password" value={adminForm.password} onChange={(e) => setAdminForm({ ...adminForm, password: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Name</label>
|
||||
<input type="text" value={adminForm.name} onChange={(e) => setAdminForm({ ...adminForm, name: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Role</label>
|
||||
<select value={adminForm.role} onChange={(e) => setAdminForm({ ...adminForm, role: e.target.value })} className="w-full border rounded-lg px-3 py-2 text-sm">
|
||||
<option value="ORG_OWNER">ORG_OWNER</option>
|
||||
<option value="ORG_ADMIN">ORG_ADMIN</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="text-red-600 text-sm">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" disabled={saving} className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">{saving ? 'Saving...' : 'Create'}</button>
|
||||
<button type="button" onClick={() => setShowAdminForm(false)} className="border rounded-lg px-4 py-2 text-sm hover:bg-gray-50">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 text-left">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">Email</th>
|
||||
<th className="px-4 py-3 font-medium">Name</th>
|
||||
<th className="px-4 py-3 font-medium">Role</th>
|
||||
<th className="px-4 py-3 font-medium">Created</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{(org.orgAdmins ?? []).map((a: any) => (
|
||||
<tr key={a.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3">{a.email}</td>
|
||||
<td className="px-4 py-3 text-gray-500">{a.name ?? '—'}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className="text-xs font-medium px-2 py-1 rounded-full bg-purple-100 text-purple-700">{a.role}</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500">{new Date(a.createdAt).toLocaleDateString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{org.orgAdmins?.length === 0 && <p className="p-4 text-gray-400">No org admins yet.</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSuperAdmin } from '../../_lib/super-admin-context';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function AdminOrgsPage() {
|
||||
const { admin, loading } = useSuperAdmin();
|
||||
const router = useRouter();
|
||||
const [orgs, setOrgs] = useState<any[]>([]);
|
||||
const [showAdd, setShowAdd] = useState(false);
|
||||
const [form, setForm] = useState({ slug: '', name: '' });
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function load() {
|
||||
const res = await fetch('/api/admin/orgs');
|
||||
if (res.ok) setOrgs(await res.json());
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (!admin) { router.replace('/admin/login'); return; }
|
||||
void load();
|
||||
}, [admin, loading, router]);
|
||||
|
||||
async function handleAdd(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch('/api/admin/orgs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.message ?? 'Failed');
|
||||
}
|
||||
setShowAdd(false);
|
||||
setForm({ slug: '', name: '' });
|
||||
void load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <p className="text-gray-500">Loading...</p>;
|
||||
if (!admin) return null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold">Organizations</h1>
|
||||
<button
|
||||
onClick={() => setShowAdd(!showAdd)}
|
||||
className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700"
|
||||
>
|
||||
Create Org
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showAdd && (
|
||||
<form onSubmit={(e) => void handleAdd(e)} className="bg-white rounded-xl border p-5 mb-6 flex flex-col gap-4">
|
||||
<h2 className="font-semibold">New Organization</h2>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.name}
|
||||
onChange={(e) => setForm({ ...form, name: e.target.value })}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
placeholder="UP Parivaar"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Slug</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.slug}
|
||||
onChange={(e) => setForm({ ...form, slug: e.target.value })}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
placeholder="org_up_parivaar"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="text-red-600 text-sm">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" disabled={saving} className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">
|
||||
{saving ? 'Creating...' : 'Create'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setShowAdd(false)} className="border rounded-lg px-4 py-2 text-sm hover:bg-gray-50">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="bg-white rounded-xl border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 text-left">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">Name</th>
|
||||
<th className="px-4 py-3 font-medium">Slug</th>
|
||||
<th className="px-4 py-3 font-medium">Chapters</th>
|
||||
<th className="px-4 py-3 font-medium">Org Admins</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{orgs.map((org: any) => (
|
||||
<tr key={org.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3">
|
||||
<Link href={`/admin/orgs/${org.id}`} className="text-blue-600 hover:underline font-medium">
|
||||
{org.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500">{org.slug}</td>
|
||||
<td className="px-4 py-3">{org._count?.tenants ?? 0}</td>
|
||||
<td className="px-4 py-3">{org._count?.orgAdmins ?? 0}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{orgs.length === 0 && <p className="p-4 text-gray-400">No organizations yet.</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getSuperToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_super_token')?.value;
|
||||
}
|
||||
|
||||
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
|
||||
const { id } = await params;
|
||||
const token = await getSuperToken();
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const res = await fetch(`${getApiBaseUrl()}/admin/orgs/${id}/admins`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getSuperToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_super_token')?.value;
|
||||
}
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
|
||||
const { id } = await params;
|
||||
const token = await getSuperToken();
|
||||
const res = await fetch(`${getApiBaseUrl()}/admin/orgs/${id}`, {
|
||||
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getSuperToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_super_token')?.value;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const token = await getSuperToken();
|
||||
const res = await fetch(`${getApiBaseUrl()}/admin/orgs`, {
|
||||
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
|
||||
export async function POST(req: Request): Promise<Response> {
|
||||
const token = await getSuperToken();
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const res = await fetch(`${getApiBaseUrl()}/admin/orgs`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getSuperToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_super_token')?.value;
|
||||
}
|
||||
|
||||
export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
|
||||
const { id } = await params;
|
||||
const token = await getSuperToken();
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const res = await fetch(`${getApiBaseUrl()}/admin/tenants/${id}/org`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function POST(req: Request): Promise<Response> {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const res = await fetch(`${getApiBaseUrl()}/auth/org/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
const payload = await res.json();
|
||||
const headers: Record<string, string> = {};
|
||||
if (res.ok && payload.token) {
|
||||
headers['Set-Cookie'] = `tower_org_token=${payload.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${7 * 24 * 60 * 60}`;
|
||||
}
|
||||
return jsonResponse(payload, res.status, headers);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { jsonResponse } from '../../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function POST(): Promise<Response> {
|
||||
return jsonResponse({ ok: true }, 200, {
|
||||
'Set-Cookie': 'tower_org_token=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0',
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const token = await (await import('next/headers')).cookies().then(c => c.get('tower_org_token')?.value);
|
||||
const res = await fetch(`${getApiBaseUrl()}/auth/org/me`, {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
cache: 'no-store',
|
||||
});
|
||||
const body = await res.json();
|
||||
return jsonResponse(body, res.status);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getOrgToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_org_token')?.value;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const token = await getOrgToken();
|
||||
const res = await fetch(`${getApiBaseUrl()}/org/dashboard`, {
|
||||
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getOrgToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_org_token')?.value;
|
||||
}
|
||||
|
||||
export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
|
||||
const { id } = await params;
|
||||
const token = await getOrgToken();
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const res = await fetch(`${getApiBaseUrl()}/org/rules/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
|
||||
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
|
||||
const { id } = await params;
|
||||
const token = await getOrgToken();
|
||||
const res = await fetch(`${getApiBaseUrl()}/org/rules/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
cache: 'no-store',
|
||||
});
|
||||
return res.ok ? jsonResponse({ ok: true }, 200) : jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getOrgToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_org_token')?.value;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const token = await getOrgToken();
|
||||
const res = await fetch(`${getApiBaseUrl()}/org/rules`, {
|
||||
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
|
||||
export async function POST(req: Request): Promise<Response> {
|
||||
const token = await getOrgToken();
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const res = await fetch(`${getApiBaseUrl()}/org/rules`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getOrgToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_org_token')?.value;
|
||||
}
|
||||
|
||||
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
|
||||
const { id } = await params;
|
||||
const token = await getOrgToken();
|
||||
const res = await fetch(`${getApiBaseUrl()}/org/tenants/${id}`, {
|
||||
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { getApiBaseUrl, jsonResponse } from '../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function getOrgToken(): Promise<string | undefined> {
|
||||
const { cookies } = await import('next/headers');
|
||||
return (await cookies()).get('tower_org_token')?.value;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const token = await getOrgToken();
|
||||
const res = await fetch(`${getApiBaseUrl()}/org/tenants`, {
|
||||
headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
|
||||
export async function POST(req: Request): Promise<Response> {
|
||||
const token = await getOrgToken();
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const res = await fetch(`${getApiBaseUrl()}/org/tenants`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
return jsonResponse(await res.json(), res.status);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { apiFetch, jsonResponse } from '../../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(
|
||||
_req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
): Promise<Response> {
|
||||
const { id } = await params;
|
||||
const res = await apiFetch(`/admin/threads/${id}`);
|
||||
const body = await res.json();
|
||||
return jsonResponse(body, res.status);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { apiFetch, jsonResponse } from '../../_lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(_req: Request): Promise<Response> {
|
||||
const res = await apiFetch('/admin/threads');
|
||||
const body = await res.json();
|
||||
return jsonResponse(body, res.status);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function OrgLayout({ children }: { children: React.ReactNode }) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useOrgAdmin } from '../../_lib/org-admin-context';
|
||||
|
||||
export default function OrgLoginPage() {
|
||||
const { login } = useOrgAdmin();
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
await login(email, password);
|
||||
router.replace('/org');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Login failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="bg-white rounded-xl border p-8 w-full max-w-sm">
|
||||
<h1 className="text-2xl font-bold mb-1">TOWER</h1>
|
||||
<p className="text-sm text-gray-500 mb-6">Organization portal</p>
|
||||
<form onSubmit={(e) => void handleSubmit(e)} className="flex flex-col gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Email</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-red-600 text-sm">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
|
||||
>
|
||||
{loading ? 'Signing in...' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useOrgAdmin } from '../_lib/org-admin-context';
|
||||
|
||||
export default function OrgDashboardPage() {
|
||||
const { orgAdmin, loading } = useOrgAdmin();
|
||||
const router = useRouter();
|
||||
const [data, setData] = useState<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (!orgAdmin) { router.replace('/org/login'); return; }
|
||||
fetch('/api/org/dashboard')
|
||||
.then((r) => r.ok ? r.json() : null)
|
||||
.then((d) => setData(d))
|
||||
.catch(() => {});
|
||||
}, [orgAdmin, loading, router]);
|
||||
|
||||
if (loading || !orgAdmin) return <p className="text-gray-500 p-6">Loading...</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold mb-1">{orgAdmin.organization?.name ?? 'Organization'}</h1>
|
||||
<p className="text-sm text-gray-500 mb-6">{data?.chapterCount ?? '—'} chapters</p>
|
||||
|
||||
<div className="grid gap-4">
|
||||
{(data?.chapters ?? []).map((chapter: any) => (
|
||||
<div key={chapter.id} className="bg-white rounded-xl border p-5 flex items-center justify-between">
|
||||
<div>
|
||||
<Link href={`/org/tenants/${chapter.id}`} className="font-medium text-blue-600 hover:underline">
|
||||
{chapter.name}
|
||||
</Link>
|
||||
<p className="text-xs text-gray-500 mt-1">{chapter.slug}</p>
|
||||
</div>
|
||||
<div className="flex gap-6 text-sm text-right">
|
||||
<div>
|
||||
<p className="font-medium">{chapter.messageCount}</p>
|
||||
<p className="text-xs text-gray-400">messages</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{chapter.memberCount}</p>
|
||||
<p className="text-xs text-gray-400">members</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{chapter.adminCount}</p>
|
||||
<p className="text-xs text-gray-400">admins</p>
|
||||
</div>
|
||||
<span className={`self-center text-xs font-medium px-2 py-1 rounded-full ${chapter.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
|
||||
{chapter.isActive ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{data && data.chapters.length === 0 && (
|
||||
<p className="text-gray-400">No chapters yet. <Link href="/org/tenants" className="text-blue-600 hover:underline">Add a chapter</Link>.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useOrgAdmin } from '../../_lib/org-admin-context';
|
||||
|
||||
const MATCH_TYPES = ['HASHTAG', 'PREFIX', 'REACTION_EMOJI'];
|
||||
const ACTIONS = ['FLAG', 'AUTO_APPROVE', 'SKIP', 'REJECT', 'P1'];
|
||||
|
||||
export default function OrgRulesPage() {
|
||||
const { orgAdmin, loading } = useOrgAdmin();
|
||||
const router = useRouter();
|
||||
const [rules, setRules] = useState<any[]>([]);
|
||||
const [showAdd, setShowAdd] = useState(false);
|
||||
const [form, setForm] = useState({ matchType: 'HASHTAG', matchValue: '', action: 'FLAG', priority: 0 });
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function load() {
|
||||
const res = await fetch('/api/org/rules');
|
||||
if (res.ok) setRules(await res.json());
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (!orgAdmin) { router.replace('/org/login'); return; }
|
||||
void load();
|
||||
}, [orgAdmin, loading, router]);
|
||||
|
||||
async function handleAdd(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch('/api/org/rules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.message ?? 'Failed');
|
||||
}
|
||||
setShowAdd(false);
|
||||
setForm({ matchType: 'HASHTAG', matchValue: '', action: 'FLAG', priority: 0 });
|
||||
void load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleActive(rule: any) {
|
||||
await fetch(`/api/org/rules/${rule.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ isActive: !rule.isActive }),
|
||||
});
|
||||
void load();
|
||||
}
|
||||
|
||||
async function deleteRule(id: string) {
|
||||
if (!confirm('Delete this rule?')) return;
|
||||
await fetch(`/api/org/rules/${id}`, { method: 'DELETE' });
|
||||
void load();
|
||||
}
|
||||
|
||||
if (loading || !orgAdmin) return <p className="text-gray-500">Loading...</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Org-wide Rules</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">These rules apply to all chapters and take priority over chapter-specific rules.</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowAdd(!showAdd)}
|
||||
className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700"
|
||||
>
|
||||
Add Rule
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showAdd && (
|
||||
<form onSubmit={(e) => void handleAdd(e)} className="bg-white rounded-xl border p-5 mb-6 flex flex-col gap-4">
|
||||
<h2 className="font-semibold">New Org Rule</h2>
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Match type</label>
|
||||
<select
|
||||
value={form.matchType}
|
||||
onChange={(e) => setForm({ ...form, matchType: e.target.value })}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
>
|
||||
{MATCH_TYPES.map((t) => <option key={t}>{t}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Match value</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.matchValue}
|
||||
onChange={(e) => setForm({ ...form, matchValue: e.target.value })}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
placeholder="e.g. #emergency"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Action</label>
|
||||
<select
|
||||
value={form.action}
|
||||
onChange={(e) => setForm({ ...form, action: e.target.value })}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
>
|
||||
{ACTIONS.map((a) => <option key={a}>{a}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Priority</label>
|
||||
<input
|
||||
type="number"
|
||||
value={form.priority}
|
||||
onChange={(e) => setForm({ ...form, priority: Number(e.target.value) })}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="text-red-600 text-sm">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" disabled={saving} className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">
|
||||
{saving ? 'Saving...' : 'Save Rule'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setShowAdd(false)} className="border rounded-lg px-4 py-2 text-sm hover:bg-gray-50">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="bg-white rounded-xl border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 text-left">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">Match type</th>
|
||||
<th className="px-4 py-3 font-medium">Match value</th>
|
||||
<th className="px-4 py-3 font-medium">Action</th>
|
||||
<th className="px-4 py-3 font-medium">Priority</th>
|
||||
<th className="px-4 py-3 font-medium">Active</th>
|
||||
<th className="px-4 py-3 font-medium"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{rules.map((r: any) => (
|
||||
<tr key={r.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3 text-gray-500">{r.matchType}</td>
|
||||
<td className="px-4 py-3 font-mono">{r.matchValue}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className="text-xs font-medium px-2 py-1 rounded-full bg-blue-100 text-blue-700">{r.action}</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500">{r.priority}</td>
|
||||
<td className="px-4 py-3">
|
||||
<button
|
||||
onClick={() => void toggleActive(r)}
|
||||
className={`text-xs font-medium px-2 py-1 rounded-full ${r.isActive ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}
|
||||
>
|
||||
{r.isActive ? 'Active' : 'Inactive'}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<button
|
||||
onClick={() => void deleteRule(r.id)}
|
||||
className="text-xs text-red-600 hover:text-red-800"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{rules.length === 0 && <p className="p-4 text-gray-400">No org rules yet.</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
'use client';
|
||||
|
||||
import { use, useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useOrgAdmin } from '../../../_lib/org-admin-context';
|
||||
|
||||
export default function OrgTenantDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = use(params);
|
||||
const { orgAdmin, loading } = useOrgAdmin();
|
||||
const router = useRouter();
|
||||
const [tenant, setTenant] = useState<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (!orgAdmin) { router.replace('/org/login'); return; }
|
||||
fetch(`/api/org/tenants/${id}`)
|
||||
.then((r) => r.ok ? r.json() : null)
|
||||
.then((d) => setTenant(d))
|
||||
.catch(() => {});
|
||||
}, [orgAdmin, loading, router, id]);
|
||||
|
||||
if (loading || !orgAdmin) return <p className="text-gray-500">Loading...</p>;
|
||||
if (!tenant) return <p className="text-gray-400">Chapter not found.</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-6">
|
||||
<button onClick={() => router.back()} className="text-sm text-gray-500 hover:text-gray-700 mb-3">← Back</button>
|
||||
<h1 className="text-2xl font-bold">{tenant.name}</h1>
|
||||
<p className="text-sm text-gray-500">{tenant.slug}</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4 mb-8">
|
||||
{[
|
||||
{ label: 'Messages', value: tenant._count?.messages },
|
||||
{ label: 'Members', value: tenant._count?.towerUsers },
|
||||
{ label: 'Groups', value: tenant._count?.groups },
|
||||
].map((stat) => (
|
||||
<div key={stat.label} className="bg-white rounded-xl border p-5">
|
||||
<p className="text-2xl font-bold">{stat.value ?? '—'}</p>
|
||||
<p className="text-sm text-gray-500">{stat.label}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border overflow-hidden">
|
||||
<div className="px-5 py-4 border-b">
|
||||
<h2 className="font-semibold">Chapter Admins</h2>
|
||||
</div>
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 text-left">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">Email</th>
|
||||
<th className="px-4 py-3 font-medium">Role</th>
|
||||
<th className="px-4 py-3 font-medium">Joined</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{(tenant.admins ?? []).map((a: any) => (
|
||||
<tr key={a.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3">{a.email}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className="text-xs font-medium px-2 py-1 rounded-full bg-gray-100 text-gray-700">{a.role}</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500">{new Date(a.createdAt).toLocaleDateString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{tenant.admins?.length === 0 && <p className="p-4 text-gray-400">No admins yet.</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useOrgAdmin } from '../../_lib/org-admin-context';
|
||||
|
||||
export default function OrgTenantsPage() {
|
||||
const { orgAdmin, loading } = useOrgAdmin();
|
||||
const router = useRouter();
|
||||
const [tenants, setTenants] = useState<any[]>([]);
|
||||
const [showAdd, setShowAdd] = useState(false);
|
||||
const [form, setForm] = useState({ name: '', slug: '' });
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function load() {
|
||||
const res = await fetch('/api/org/tenants');
|
||||
if (res.ok) setTenants(await res.json());
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (!orgAdmin) { router.replace('/org/login'); return; }
|
||||
void load();
|
||||
}, [orgAdmin, loading, router]);
|
||||
|
||||
async function handleAdd(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch('/api/org/tenants', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.message ?? 'Failed to create chapter');
|
||||
}
|
||||
setShowAdd(false);
|
||||
setForm({ name: '', slug: '' });
|
||||
void load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading || !orgAdmin) return <p className="text-gray-500">Loading...</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold">Chapters</h1>
|
||||
{orgAdmin.role === 'ORG_OWNER' && (
|
||||
<button
|
||||
onClick={() => setShowAdd(!showAdd)}
|
||||
className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700"
|
||||
>
|
||||
Add Chapter
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showAdd && (
|
||||
<form onSubmit={(e) => void handleAdd(e)} className="bg-white rounded-xl border p-5 mb-6 flex flex-col gap-4">
|
||||
<h2 className="font-semibold">New Chapter</h2>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.name}
|
||||
onChange={(e) => setForm({ ...form, name: e.target.value })}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Slug</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.slug}
|
||||
onChange={(e) => setForm({ ...form, slug: e.target.value })}
|
||||
className="w-full border rounded-lg px-3 py-2 text-sm"
|
||||
placeholder="e.g. tenant_up_parivaar_dallas"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="text-red-600 text-sm">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" disabled={saving} className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-blue-700 disabled:opacity-50">
|
||||
{saving ? 'Creating...' : 'Create'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setShowAdd(false)} className="border rounded-lg px-4 py-2 text-sm hover:bg-gray-50">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="bg-white rounded-xl border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 text-left">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">Name</th>
|
||||
<th className="px-4 py-3 font-medium">Slug</th>
|
||||
<th className="px-4 py-3 font-medium">Messages</th>
|
||||
<th className="px-4 py-3 font-medium">Members</th>
|
||||
<th className="px-4 py-3 font-medium">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{tenants.map((t: any) => (
|
||||
<tr key={t.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3">
|
||||
<Link href={`/org/tenants/${t.id}`} className="text-blue-600 hover:underline font-medium">
|
||||
{t.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500">{t.slug}</td>
|
||||
<td className="px-4 py-3">{t._count?.messages ?? '—'}</td>
|
||||
<td className="px-4 py-3">{t._count?.towerUsers ?? '—'}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`text-xs font-medium px-2 py-1 rounded-full ${t.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
|
||||
{t.isActive ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{tenants.length === 0 && <p className="p-4 text-gray-400">No chapters yet.</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import Link from 'next/link';
|
||||
import { apiFetch } from '../../_lib/api';
|
||||
|
||||
interface ThreadMessage {
|
||||
id: string;
|
||||
content: string;
|
||||
senderJid: string;
|
||||
senderName: string | null;
|
||||
tags: string[];
|
||||
status: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface ThreadDetail {
|
||||
id: string;
|
||||
topic: string | null;
|
||||
sourceGroupName: string;
|
||||
messageCount: number;
|
||||
lastActivityAt: string;
|
||||
createdAt: string;
|
||||
messages: ThreadMessage[];
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
APPROVED: 'text-green-600',
|
||||
PENDING: 'text-amber-600',
|
||||
REJECTED: 'text-red-600',
|
||||
RAW: 'text-gray-400',
|
||||
DNC: 'text-gray-400',
|
||||
DISTRIBUTED: 'text-blue-600',
|
||||
};
|
||||
|
||||
export default async function ThreadDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
|
||||
let thread: ThreadDetail | null = null;
|
||||
let error: string | null = null;
|
||||
|
||||
try {
|
||||
const res = await apiFetch(`/admin/threads/${id}`);
|
||||
if (res.ok) {
|
||||
thread = await res.json();
|
||||
} else {
|
||||
error = `API returned ${res.status}`;
|
||||
}
|
||||
} catch {
|
||||
error = 'Failed to load thread';
|
||||
}
|
||||
|
||||
if (error || !thread) {
|
||||
return (
|
||||
<div className="max-w-2xl">
|
||||
<Link href="/threads" className="text-sm text-blue-600 hover:underline mb-4 inline-block">← Back to threads</Link>
|
||||
<p className="text-red-600 text-sm">{error ?? 'Thread not found'}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl">
|
||||
<Link href="/threads" className="text-sm text-blue-600 hover:underline mb-4 inline-block">← Back to threads</Link>
|
||||
|
||||
<div className="mb-6">
|
||||
<h1 className="text-xl font-semibold">
|
||||
{thread.topic ?? `Thread ${thread.id.slice(0, 8)}`}
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{thread.sourceGroupName} · {thread.messageCount} messages · last activity {new Date(thread.lastActivityAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
{thread.messages.map((msg) => (
|
||||
<div key={msg.id} className="border border-gray-200 rounded-lg p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="text-xs text-gray-500">
|
||||
<span className="font-medium text-gray-700">{msg.senderName ?? msg.senderJid}</span>
|
||||
<span className="mx-1">·</span>
|
||||
<span>{new Date(msg.createdAt).toLocaleString()}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`text-xs font-medium ${STATUS_COLORS[msg.status] ?? 'text-gray-500'}`}>
|
||||
{msg.status}
|
||||
</span>
|
||||
<Link href={`/messages/${msg.id}`} className="text-xs text-blue-600 hover:underline">
|
||||
View
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-gray-900 whitespace-pre-wrap">{msg.content}</p>
|
||||
{msg.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mt-2">
|
||||
{msg.tags.map((tag) => (
|
||||
<span key={tag} className="rounded-full bg-blue-50 px-2 py-0.5 text-xs text-blue-600">{tag}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import Link from 'next/link';
|
||||
import { apiFetch } from '../_lib/api';
|
||||
|
||||
interface ThreadSummary {
|
||||
id: string;
|
||||
topic: string | null;
|
||||
sourceGroupName: string;
|
||||
messageCount: number;
|
||||
lastActivityAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default async function ThreadsPage() {
|
||||
let threads: ThreadSummary[] = [];
|
||||
let error: string | null = null;
|
||||
|
||||
try {
|
||||
const res = await apiFetch('/admin/threads');
|
||||
if (res.ok) {
|
||||
threads = await res.json();
|
||||
} else {
|
||||
error = `API returned ${res.status}`;
|
||||
}
|
||||
} catch {
|
||||
error = 'Failed to load threads';
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl">
|
||||
<h1 className="text-xl font-semibold mb-6">Threads</h1>
|
||||
|
||||
{error && (
|
||||
<p className="text-red-600 text-sm mb-4">{error}</p>
|
||||
)}
|
||||
|
||||
{!error && threads.length === 0 && (
|
||||
<p className="text-gray-500 text-sm">No threads yet. Threads are created automatically when members reply to messages.</p>
|
||||
)}
|
||||
|
||||
{threads.length > 0 && (
|
||||
<div className="border border-gray-200 rounded-lg divide-y divide-gray-100">
|
||||
{threads.map((thread) => (
|
||||
<Link
|
||||
key={thread.id}
|
||||
href={`/threads/${thread.id}`}
|
||||
className="flex items-start justify-between p-4 hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">
|
||||
{thread.topic ?? `Thread ${thread.id.slice(0, 8)}`}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-0.5">{thread.sourceGroupName}</p>
|
||||
</div>
|
||||
<div className="ml-4 shrink-0 text-right">
|
||||
<span className="inline-flex items-center rounded-full bg-blue-50 px-2.5 py-0.5 text-xs font-medium text-blue-700">
|
||||
{thread.messageCount} {thread.messageCount === 1 ? 'message' : 'messages'}
|
||||
</span>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
{new Date(thread.lastActivityAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user