feat: isolate all four portals with route groups + polished design system

Fix blank /org/login (and /admin/login): the guarded portal layout was
wrapping its own login route, rendering null when unauthenticated. Move
each portal's authed pages into a (authed)/(chapter) route group so login
pages live outside the guard.

Structure:
- app/(chapter)/* — chapter admin pages + guarded layout (was root-level)
- app/org/(authed)/* — org pages + guarded layout; /org/login now free
- app/admin/(authed)/* — admin pages + guarded layout; /admin/login free
- Root layout slimmed to providers only (no shared sidebar)
- Convert moved files' relative imports to @/app alias

Design system:
- PortalShell: shared sidebar shell (brand mark, themed active nav with
  accent bar, avatar dropdown user menu, loading skeletons)
- portal-theme.ts: per-portal theme tokens (violet/slate/blue/emerald)
- PortalLoginShell redesigned: two-column with gradient branding panel,
  dotted pattern, value-prop highlights, built-in back link
- New shadcn components: Avatar, DropdownMenu, Skeleton
- Move shared DraftCard to _components/draft-card.tsx (used by 2 portals)
- Portal selector: remove Super Admin card, icon tiles, hover lift
- All 4 login pages use react-hook-form + Zod + themed shell
- Member nav restored to full 11-section list with icons

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-20 18:20:06 +05:30
parent d7b5988858
commit 205418fc4e
50 changed files with 619 additions and 360 deletions
+98
View File
@@ -0,0 +1,98 @@
import { apiFetch } from '@/app/_lib/api';
import { redirect } from 'next/navigation';
import { getToken } from '@/app/_lib/api';
import { DraftCard } from '@/app/_components/draft-card';
import Link from 'next/link';
type DraftType = 'EVENT' | 'SEVA_TASK' | 'FAQ_ITEM';
interface Draft {
id: string;
type: DraftType;
status: string;
proposedJson: Record<string, any>;
confidence: number | null;
createdAt: string;
sourceMessage: {
id: string;
content: string;
senderName: string | null;
createdAt: string;
};
}
const TABS: { label: string; value: DraftType | 'ALL' }[] = [
{ label: 'All', value: 'ALL' },
{ label: 'Events', value: 'EVENT' },
{ label: 'Seva Tasks', value: 'SEVA_TASK' },
{ label: 'FAQs', value: 'FAQ_ITEM' },
];
async function fetchDrafts(type?: DraftType): Promise<Draft[]> {
const query = new URLSearchParams({ status: 'PENDING_REVIEW' });
if (type) query.set('type', type);
const res = await apiFetch(`/admin/drafts?${query}`);
if (!res.ok) return [];
return (await res.json()) as Draft[];
}
export default async function TenantDraftsPage({
searchParams,
}: {
searchParams: Promise<{ type?: string }>;
}) {
const token = await getToken();
if (!token) redirect('/login');
const { type } = await searchParams;
const activeType = (type as DraftType) ?? undefined;
const drafts = await fetchDrafts(activeType);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-semibold text-gray-900">AI Content Drafts</h1>
<p className="text-sm text-gray-500 mt-0.5">
Events, seva tasks, and FAQs auto-detected from your group messages
</p>
</div>
</div>
<div className="flex gap-1 border-b border-gray-200">
{TABS.map((tab) => {
const href = tab.value === 'ALL' ? '/drafts' : `/drafts?type=${tab.value}`;
const isActive = (tab.value === 'ALL' && !activeType) || tab.value === activeType;
return (
<Link
key={tab.value}
href={href}
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
isActive
? 'border-indigo-600 text-indigo-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
>
{tab.label}
</Link>
);
})}
</div>
{drafts.length === 0 ? (
<div className="text-center py-20 text-gray-400">
<p className="text-sm font-medium">No pending drafts</p>
<p className="text-xs mt-1">
Drafts appear here when the AI detects events, volunteer asks, or FAQ patterns in your group messages.
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{drafts.map((d) => (
<DraftCard key={d.id} draft={d} />
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,28 @@
'use client';
import Link from 'next/link';
interface Props {
current: 'mine' | 'shared' | 'all';
counts: { mine: number; shared: number };
}
export function GroupsTabs({ current, counts }: Props) {
const tabs: { key: Props['current']; label: string; href: string }[] = [
{ key: 'mine', label: `My Groups (${counts.mine})`, href: '/groups' },
{ key: 'shared', label: `Shared with me (${counts.shared})`, href: '/groups?tab=shared' },
];
return (
<div className="flex border-b border-gray-200">
{tabs.map((t) => (
<Link key={t.key} href={t.href}
className={`px-4 py-2 text-sm border-b-2 -mb-px transition-colors ${
current === t.key
? 'border-blue-600 text-blue-700 font-medium'
: 'border-transparent text-gray-600 hover:text-gray-900'
}`}>
{t.label}
</Link>
))}
</div>
);
}
@@ -0,0 +1,109 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { RouteManager } from './RouteManager';
const groups = [
{ id: 'grp_1', name: 'Alpha', platform: 'whatsapp', isActive: true },
{ id: 'grp_2', name: 'Beta', platform: 'whatsapp', isActive: true },
{ id: 'grp_3', name: 'Gamma', platform: 'whatsapp', isActive: true },
];
const routes = [
{
id: 'rt_1',
sourceGroupId: 'grp_1',
targetGroupId: 'grp_2',
sourceGroup: { name: 'Alpha' },
targetGroup: { name: 'Beta' },
},
];
let fetchSpy: jest.SpyInstance;
beforeEach(() => {
fetchSpy = jest.spyOn(global, 'fetch');
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('RouteManager', () => {
it('renders routes grouped by source group', () => {
render(<RouteManager groups={groups} initialRoutes={routes} />);
expect(screen.getByText('Alpha')).toBeInTheDocument();
expect(screen.getByText('Beta')).toBeInTheDocument();
});
it('shows source dropdown and target checkboxes', () => {
render(<RouteManager groups={groups} initialRoutes={routes} />);
expect(screen.getByRole('combobox')).toBeInTheDocument();
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
});
it('shows target checkboxes when a source is selected', () => {
render(<RouteManager groups={groups} initialRoutes={routes} />);
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'grp_1' } });
expect(screen.getAllByRole('checkbox')).toHaveLength(2);
});
it('calls POST /api/routes/batch with selected targetIds', async () => {
fetchSpy.mockResolvedValueOnce(
new Response(
JSON.stringify([
{ id: 'rt_new', sourceGroupId: 'grp_1', targetGroupId: 'grp_2', sourceGroup: { name: 'Alpha' }, targetGroup: { name: 'Beta' } },
{ id: 'rt_new2', sourceGroupId: 'grp_1', targetGroupId: 'grp_3', sourceGroup: { name: 'Alpha' }, targetGroup: { name: 'Gamma' } },
]),
{ status: 201, headers: { 'Content-Type': 'application/json' } },
),
);
render(<RouteManager groups={groups} initialRoutes={[]} />);
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'grp_1' } });
const checkboxes = screen.getAllByRole('checkbox');
fireEvent.click(checkboxes[0]);
fireEvent.click(checkboxes[1]);
fireEvent.click(screen.getByRole('button', { name: /create 2 routes/i }));
await waitFor(() => {
expect(fetchSpy).toHaveBeenCalledWith(
'/api/routes/batch',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ sourceGroupId: 'grp_1', targetGroupIds: ['grp_2', 'grp_3'] }),
}),
);
});
});
it('shows error message on 409 conflict', async () => {
fetchSpy.mockResolvedValueOnce(
new Response(
JSON.stringify({ message: 'Routes already exist for: Beta' }),
{ status: 409, headers: { 'Content-Type': 'application/json' } },
),
);
render(<RouteManager groups={groups} initialRoutes={routes} />);
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'grp_1' } });
fireEvent.click(screen.getAllByRole('checkbox')[0]);
fireEvent.click(screen.getByRole('button', { name: /create 1 route/i }));
await waitFor(() => {
expect(screen.getByText('Routes already exist for: Beta')).toBeInTheDocument();
});
});
it('shows a delete button for each existing route', () => {
render(<RouteManager groups={groups} initialRoutes={routes} />);
const deleteBtn = screen.getByRole('button', { name: /delete route to beta/i });
expect(deleteBtn).toBeInTheDocument();
});
it('calls DELETE /api/routes/:id when a route is deleted', async () => {
fetchSpy.mockResolvedValueOnce(new Response(null, { status: 204 }));
render(<RouteManager groups={groups} initialRoutes={routes} />);
fireEvent.click(screen.getByRole('button', { name: /delete route to beta/i }));
await waitFor(() => {
expect(fetchSpy).toHaveBeenCalledWith(
'/api/routes/rt_1',
expect.objectContaining({ method: 'DELETE' }),
);
});
});
});
@@ -0,0 +1,179 @@
'use client';
import { useState } from 'react';
interface Group {
id: string;
name: string;
platform: string;
isActive: boolean;
}
interface Route {
id: string;
sourceGroupId: string;
targetGroupId: string;
sourceGroup: { name: string };
targetGroup: { name: string };
}
export function RouteManager({
groups,
initialRoutes,
}: {
groups: Group[];
initialRoutes: Route[];
}) {
const [routes, setRoutes] = useState<Route[]>(initialRoutes);
const [sourceId, setSourceId] = useState('');
const [targetIds, setTargetIds] = useState<Set<string>>(new Set());
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Group routes by source group name
const grouped = new Map<string, { sourceId: string; targets: Route[] }>();
for (const r of routes) {
const key = r.sourceGroup.name;
if (!grouped.has(key)) grouped.set(key, { sourceId: r.sourceGroupId, targets: [] });
grouped.get(key)!.targets.push(r);
}
function toggleTarget(id: string) {
setTargetIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
setError(null);
}
async function addRoutes() {
if (!sourceId || targetIds.size === 0) return;
setBusy(true);
setError(null);
try {
const res = await fetch('/api/routes/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sourceGroupId: sourceId, targetGroupIds: [...targetIds] }),
});
if (res.status === 409) {
const errBody = await res.json();
setError(errBody.message ?? 'Some routes already exist');
return;
}
if (!res.ok) {
setError('Failed to create routes');
return;
}
const created: Route[] = await res.json();
setRoutes((prev) => [...created, ...prev]);
setSourceId('');
setTargetIds(new Set());
} finally {
setBusy(false);
}
}
async function deleteRoute(id: string) {
const res = await fetch(`/api/routes/${id}`, { method: 'DELETE' });
if (res.ok) setRoutes((prev) => prev.filter((r) => r.id !== id));
}
const eligibleTargets = groups.filter((g) => g.id !== sourceId && g.platform === 'whatsapp' && g.isActive);
return (
<div className="flex flex-col gap-6">
<section>
<h2 className="text-base font-semibold mb-3">Active sync routes</h2>
{routes.length === 0 ? (
<p className="text-sm text-gray-400">No routes configured.</p>
) : (
<ul className="flex flex-col gap-3">
{[...grouped.entries()].map(([sourceName, { sourceId: sId, targets }]) => (
<li key={sId} className="rounded-lg border border-gray-200 bg-white px-4 py-3">
<div className="flex items-start gap-3">
<span className="text-sm font-semibold text-gray-700 whitespace-nowrap mt-1 min-w-[120px]">{sourceName}</span>
<div className="flex flex-col gap-1.5 flex-1">
{targets.map((r) => (
<div key={r.id} className="flex items-center justify-between group">
<span className="text-sm text-gray-600">{r.targetGroup.name}</span>
<button
onClick={() => deleteRoute(r.id)}
className="text-xs text-red-400 hover:text-red-600 opacity-0 group-hover:opacity-100 transition-opacity"
aria-label={`Delete route to ${r.targetGroup.name}`}
>
Delete
</button>
</div>
))}
</div>
</div>
</li>
))}
</ul>
)}
</section>
<section>
<h2 className="text-base font-semibold mb-3">Add routes</h2>
<div className="flex flex-col gap-3">
<div className="flex gap-2 items-center">
<select
value={sourceId}
onChange={(e) => { setSourceId(e.target.value); setTargetIds(new Set()); setError(null); }}
className="rounded-lg border border-gray-200 px-3 py-2 text-sm"
aria-label="Source group"
>
<option value="">Source group</option>
{groups.filter((g) => g.platform === 'whatsapp' && g.isActive).map((g) => (
<option key={g.id} value={g.id}>{g.name}</option>
))}
</select>
<span className="text-gray-400 text-sm"></span>
<span className="text-xs text-gray-500">
{targetIds.size} target{targetIds.size !== 1 ? 's' : ''} selected
</span>
</div>
{sourceId && eligibleTargets.length > 0 && (
<div className="rounded-lg border border-gray-200 bg-white p-3 max-h-48 overflow-y-auto">
{eligibleTargets.map((g) => {
const checked = targetIds.has(g.id);
return (
<label
key={g.id}
className={`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer text-sm transition-colors ${
checked ? 'bg-blue-50 text-blue-700' : 'hover:bg-gray-50'
}`}
>
<input
type="checkbox"
checked={checked}
onChange={() => toggleTarget(g.id)}
className="rounded border-gray-300"
/>
{g.name}
</label>
);
})}
</div>
)}
{error && (
<p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2">{error}</p>
)}
<button
onClick={addRoutes}
disabled={!sourceId || targetIds.size === 0 || busy}
className="self-start rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
>
{busy ? 'Creating…' : `Create ${targetIds.size} route${targetIds.size !== 1 ? 's' : ''}`}
</button>
</div>
</section>
</div>
);
}
+105
View File
@@ -0,0 +1,105 @@
import { RouteManager } from './RouteManager';
import { GroupsTabs } from './GroupsTabs';
import { apiFetch } from '@/app/_lib/api';
interface Group {
id: string;
name: string;
platform: string;
platformId: string;
isActive: boolean;
accountId: string | null;
tenantId: string | null;
}
interface SharedGroup extends Group {
sharedByTenantName: string;
}
interface Route {
id: string;
sourceGroupId: string;
targetGroupId: string;
sourceGroup: { name: string };
targetGroup: { name: string };
}
type FetchResult<T> = { ok: true; data: T } | { ok: false; status: number; error: string };
async function fetchJson<T>(path: string): Promise<FetchResult<T>> {
let res: Response;
try {
res = await apiFetch(path);
} catch (err) {
return { ok: false, status: 0, error: `API unreachable: ${(err as Error).message}` };
}
if (!res.ok) {
const body = await res.text().catch(() => '');
return { ok: false, status: res.status, error: body.slice(0, 200) || res.statusText };
}
return { ok: true, data: (await res.json()) as T };
}
export default async function GroupsPage({
searchParams,
}: {
searchParams: Promise<{ tab?: 'mine' | 'shared' }>;
}) {
const { tab: rawTab } = await searchParams;
const tab: 'mine' | 'shared' = rawTab === 'shared' ? 'shared' : 'mine';
const [groupsR, sharedR, routesR] = await Promise.all([
fetchJson<Group[]>('/groups'),
tab === 'shared' ? fetchJson<SharedGroup[]>('/groups/shared') : Promise.resolve(null),
fetchJson<Route[]>('/routes'),
]);
const groups = groupsR?.ok ? groupsR.data : [];
const shared = sharedR && sharedR.ok ? sharedR.data : [];
const routes = routesR?.ok ? routesR.data : [];
const errors = [groupsR, sharedR, routesR]
.filter((r): r is { ok: false; status: number; error: string } => !!r && !r.ok && r.status !== 401)
.map((e) => `${e.status === 0 ? 'API unreachable' : `API ${e.status}`}: ${e.error}`);
return (
<div className="max-w-3xl">
<h1 className="text-xl font-semibold mb-6">Groups &amp; Routes</h1>
{errors.length > 0 && (
<div className="mb-4 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-800">
<div className="font-medium mb-1">Failed to load some data</div>
<ul className="list-disc pl-5 space-y-0.5">
{errors.map((e) => <li key={e}>{e}</li>)}
</ul>
</div>
)}
<GroupsTabs current={tab} counts={{ mine: groups.length, shared: shared.length }} />
{tab === 'shared' && (
<div className="mt-4">
<h2 className="text-sm font-medium mb-2">Shared with me</h2>
<p className="text-xs text-gray-500 mb-3">
Groups other tenants have shared with you. You can use them as TARGET groups in your routes.
</p>
{shared.length === 0 ? (
<p className="text-sm text-gray-400 italic">No groups shared with you yet.</p>
) : (
<ul className="space-y-2">
{shared.map((g) => (
<li key={g.id} className="border border-gray-200 rounded bg-white px-4 py-3 flex items-center justify-between">
<div>
<span className="text-sm font-medium">{g.name}</span>
{!g.isActive && <span className="ml-2 text-xs text-red-500 font-medium">(Bot removed)</span>}
<span className="text-xs text-gray-400 ml-2">shared by {g.sharedByTenantName}</span>
</div>
</li>
))}
</ul>
)}
</div>
)}
{tab === 'mine' && (
<div className="mt-4">
<RouteManager groups={groups} initialRoutes={routes} />
</div>
)}
</div>
);
}
+40
View File
@@ -0,0 +1,40 @@
'use client';
import { useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '@/app/_lib/auth-context';
import { PortalShell } from '@/app/_components/portal-shell';
import { Search, Users, Inbox, FileText, SlidersHorizontal, Bot } from 'lucide-react';
const NAV = [
{ href: '/search', label: 'Search', icon: <Search /> },
{ href: '/groups', label: 'Groups & Routes', icon: <Users /> },
{ href: '/messages/pending', label: 'Pending', icon: <Inbox /> },
{ href: '/drafts', label: 'AI Drafts', icon: <FileText /> },
{ href: '/settings/rules', label: 'Rules', icon: <SlidersHorizontal /> },
{ href: '/settings/bot', label: 'Bot', icon: <Bot /> },
];
export default function ChapterLayout({ children }: { children: React.ReactNode }) {
const { admin, loading, logout } = useAuth();
const router = useRouter();
const pathname = usePathname();
useEffect(() => {
if (!loading && !admin) router.replace(`/login?next=${encodeURIComponent(pathname)}`);
}, [admin, loading, pathname, router]);
return (
<PortalShell
portalName="Chapter"
theme="blue"
navItems={NAV}
loading={loading}
authed={!!admin}
user={admin ? { email: admin.email, name: admin.name, role: admin.role, subtitle: admin.tenantName } : undefined}
onLogout={() => { void logout(); router.replace('/login'); }}
>
{children}
</PortalShell>
);
}
@@ -0,0 +1,158 @@
import Link from 'next/link';
import { apiFetch } from '@/app/_lib/api';
interface MessageDetail {
id: string;
tenantId: string;
platform: string;
platformMsgId: string;
sourceGroupId: string;
sourceGroup: {
id: string;
name: string;
platformId: string;
claimStatus: string;
isActive: boolean;
createdAt: string;
} | null;
senderJid: string;
senderName: string | null;
senderTowerUser: {
id: string;
jid: string;
phoneHash: string;
displayName: string | null;
createdAt: string;
} | null;
content: string;
mediaUrl: string | null;
tags: string[];
status: string;
createdAt: string;
updatedAt: string;
approval: {
id: string;
adminId: string;
decision: string;
notes: string | null;
decidedAt: string;
} | null;
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="grid grid-cols-[160px_1fr] gap-2 text-sm py-2 border-b border-gray-100">
<span className="text-gray-500 font-medium">{label}</span>
<span className="text-gray-900 break-words">{children ?? <span className="text-gray-300"></span>}</span>
</div>
);
}
export default async function MessageDetailPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
let msg: MessageDetail | null = null;
let error: string | null = null;
try {
const res = await apiFetch(`/admin/messages/${id}`);
if (res.ok) {
msg = await res.json();
} else {
error = `API returned ${res.status}`;
}
} catch {
error = 'Failed to load message';
}
if (error || !msg) {
return (
<div className="max-w-2xl">
<Link href="/search" className="text-sm text-blue-600 hover:underline mb-4 inline-block">&larr; Back to search</Link>
<p className="text-red-600 text-sm">{error ?? 'Message not found'}</p>
</div>
);
}
return (
<div className="max-w-2xl">
<Link href="/search" className="text-sm text-blue-600 hover:underline mb-4 inline-block">&larr; Back to search</Link>
<h1 className="text-xl font-semibold mb-6">Message Detail</h1>
<div className="border border-gray-200 rounded-lg p-4 mb-6">
<p className="text-sm whitespace-pre-wrap bg-gray-50 rounded p-3 mb-2">{msg.content}</p>
<div className="flex flex-wrap gap-1">
{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 className="border border-gray-200 rounded-lg p-4">
<h2 className="text-sm font-semibold text-gray-700 mb-3">Metadata</h2>
<Field label="Status">
<span className={`font-medium ${msg.status === 'APPROVED' ? 'text-green-600' : msg.status === 'REJECTED' ? 'text-red-600' : 'text-amber-600'}`}>
{msg.status}
</span>
</Field>
<Field label="Message ID">{msg.id}</Field>
<Field label="Platform">{msg.platform}</Field>
<Field label="Platform Msg ID">{msg.platformMsgId}</Field>
<Field label="Created">{new Date(msg.createdAt).toLocaleString()}</Field>
<Field label="Updated">{new Date(msg.updatedAt).toLocaleString()}</Field>
<div className="mt-4 pt-2 border-t border-gray-200">
<h3 className="text-xs font-semibold text-gray-500 uppercase mb-2">Sender</h3>
<Field label="JID">{msg.senderJid}</Field>
<Field label="Name">{msg.senderName}</Field>
{msg.senderTowerUser && (
<>
<Field label="Display Name">{msg.senderTowerUser.displayName}</Field>
<Field label="Phone Hash">{msg.senderTowerUser.phoneHash}</Field>
<Field label="Tower User ID">{msg.senderTowerUser.id}</Field>
</>
)}
</div>
<div className="mt-4 pt-2 border-t border-gray-200">
<h3 className="text-xs font-semibold text-gray-500 uppercase mb-2">Source Group</h3>
{msg.sourceGroup ? (
<>
<Field label="Name">{msg.sourceGroup.name}</Field>
<Field label="Platform ID">{msg.sourceGroup.platformId}</Field>
<Field label="Claim Status">{msg.sourceGroup.claimStatus}</Field>
<Field label="Active">{msg.sourceGroup.isActive ? 'Yes' : 'No'}</Field>
</>
) : (
<Field label="Group">(deleted)</Field>
)}
</div>
{msg.approval && (
<div className="mt-4 pt-2 border-t border-gray-200">
<h3 className="text-xs font-semibold text-gray-500 uppercase mb-2">Approval</h3>
<Field label="Decision">
<span className={`font-medium ${msg.approval.decision === 'APPROVED' ? 'text-green-600' : 'text-red-600'}`}>
{msg.approval.decision}
</span>
</Field>
<Field label="Admin ID">{msg.approval.adminId}</Field>
<Field label="Decided At">{new Date(msg.approval.decidedAt).toLocaleString()}</Field>
<Field label="Notes">{msg.approval.notes}</Field>
</div>
)}
{msg.mediaUrl && (
<div className="mt-4 pt-2 border-t border-gray-200">
<h3 className="text-xs font-semibold text-gray-500 uppercase mb-2">Media</h3>
<Field label="Media URL">{msg.mediaUrl}</Field>
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,105 @@
import { apiFetch } from '@/app/_lib/api';
interface PendingMessage {
id: string;
content: string;
senderJid: string;
senderName: string | null;
tags: string[];
createdAt: string;
sourceGroupId: string;
sourceGroupName: string;
sourceGroupPlatformId: string;
}
type FetchResult<T> = { ok: true; data: T } | { ok: false; status: number; error: string };
async function fetchPending(): Promise<FetchResult<PendingMessage[]>> {
try {
const res = await apiFetch('/admin/messages/pending');
if (!res.ok) {
const body = await res.text().catch(() => '');
return { ok: false, status: res.status, error: body.slice(0, 200) || res.statusText };
}
return { ok: true, data: (await res.json()) as PendingMessage[] };
} catch (err) {
return { ok: false, status: 0, error: `API unreachable: ${(err as Error).message}` };
}
}
export default async function PendingMessagesPage() {
const result = await fetchPending();
const messages = result.ok ? result.data : [];
const error = !result.ok ? (result.status === 0 ? 'API unreachable' : `API ${result.status}: ${result.error}`) : null;
return (
<div className="max-w-3xl">
<h1 className="text-xl font-semibold mb-2">Pending messages</h1>
<p className="text-sm text-gray-500 mb-6">
Flagged messages waiting for an admin to approve. Approving forwards them to every active
route from the source group and indexes them in search.
</p>
{error && (
<div className="mb-4 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-800">
Failed to load: {error}
</div>
)}
{!error && messages.length === 0 && (
<div className="rounded-xl border border-gray-200 bg-white p-6 text-sm text-gray-500">
No pending messages right now. New flagged messages will appear here as they arrive.
</div>
)}
<ul className="space-y-3">
{messages.map((m) => (
<PendingMessageRow key={m.id} message={m} />
))}
</ul>
</div>
);
}
function PendingMessageRow({ message }: { message: PendingMessage }) {
return (
<li className="rounded-xl border border-gray-200 bg-white p-4 flex flex-col gap-2">
<div className="flex items-baseline justify-between gap-2">
<div className="text-sm font-medium text-gray-900">{message.sourceGroupName}</div>
<div className="text-xs text-gray-500">
{new Date(message.createdAt).toLocaleString()}
</div>
</div>
<div className="text-xs text-gray-500">
From <span className="font-mono">{message.senderName ?? message.senderJid}</span>
{message.tags.length > 0 && (
<span className="ml-2 inline-flex flex-wrap gap-1">
{message.tags.map((t) => (
<span
key={t}
className="rounded bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-700"
>
{t}
</span>
))}
</span>
)}
</div>
<div className="text-sm text-gray-800 whitespace-pre-wrap break-words">
{message.content}
</div>
<form
action={`/api/messages/${message.id}/approve`}
method="post"
className="flex justify-end pt-1"
>
<button
type="submit"
className="rounded bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700"
>
Approve &amp; forward
</button>
</form>
</li>
);
}
@@ -0,0 +1,49 @@
import { render, screen } from '@testing-library/react';
import { SearchResults } from './page';
const makeHit = (id: string, content: string) => ({
id,
content,
senderName: 'Alice',
sourceGroupName: 'UP Parivar Dallas',
tags: ['#important'],
approvedAt: 1748390400000,
});
describe('SearchResults', () => {
it('shows "no results" when hits array is empty', () => {
render(<SearchResults hits={[]} total={0} q="missing" page={1} />);
expect(screen.getByText(/no results/i)).toBeInTheDocument();
});
it('renders each hit content', () => {
render(
<SearchResults
hits={[makeHit('m1', 'Hello world'), makeHit('m2', 'Event tonight')]}
total={2}
q="hello"
page={1}
/>,
);
expect(screen.getByText('Hello world')).toBeInTheDocument();
expect(screen.getByText('Event tonight')).toBeInTheDocument();
});
it('shows the total result count', () => {
render(<SearchResults hits={[makeHit('m1', 'Test')]} total={42} q="test" page={1} />);
expect(screen.getByText(/42/)).toBeInTheDocument();
});
it('shows sender name, group name, and formatted date for each hit', () => {
render(<SearchResults hits={[makeHit('m1', 'Test')]} total={1} q="test" page={1} />);
expect(screen.getByText(/alice/i)).toBeInTheDocument();
expect(screen.getByText(/UP Parivar Dallas/i)).toBeInTheDocument();
// approvedAt: 1748390400000 — verify a date string is rendered (locale-aware)
expect(screen.getByText(new Date(1748390400000).toLocaleDateString())).toBeInTheDocument();
});
it('shows tags for each hit', () => {
render(<SearchResults hits={[makeHit('m1', 'Test')]} total={1} q="test" page={1} />);
expect(screen.getByText('#important')).toBeInTheDocument();
});
});
+107
View File
@@ -0,0 +1,107 @@
import Link from 'next/link';
import { apiFetch } from '@/app/_lib/api';
interface MeiliHit {
id: string;
content: string;
senderName: string;
sourceGroupName: string;
tags: string[];
approvedAt: number;
}
interface SearchResponse {
hits: MeiliHit[];
total: number;
page: number;
limit: number;
query: string;
}
export function SearchResults({
hits,
total,
q,
page,
}: {
hits: MeiliHit[];
total: number;
q: string;
page: number;
}) {
return (
<div className="flex flex-col gap-4">
<form method="GET" className="flex gap-2">
<input
name="q"
defaultValue={q}
placeholder="Search approved messages…"
className="flex-1 rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400"
/>
<button
type="submit"
className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
>
Search
</button>
</form>
{hits.length === 0 ? (
<p className="text-gray-500 text-sm">No results{q ? ` for "${q}"` : ''}.</p>
) : (
<>
<p className="text-sm text-gray-500">
{total} result{total !== 1 ? 's' : ''}
</p>
<ul className="flex flex-col gap-3">
{hits.map((hit) => (
<li key={hit.id}>
<Link
href={`/messages/${hit.id}`}
className="block rounded-xl border border-gray-200 bg-white p-4 hover:border-blue-300 hover:shadow-sm transition-colors"
>
<p className="text-sm">{hit.content}</p>
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-gray-400">
<span>{hit.senderName}</span>
<span>·</span>
<span>{hit.sourceGroupName}</span>
<span>·</span>
<span>{new Date(hit.approvedAt).toLocaleDateString()}</span>
{hit.tags.map((tag) => (
<span key={tag} className="rounded-full bg-blue-50 px-2 py-0.5 text-blue-600">
{tag}
</span>
))}
</div>
</Link>
</li>
))}
</ul>
</>
)}
</div>
);
}
export default async function SearchPage({
searchParams,
}: {
searchParams: Promise<{ q?: string; page?: string }>;
}) {
const { q = '', page = '1' } = await searchParams;
let data: SearchResponse = { hits: [], total: 0, page: 1, limit: 20, query: q };
try {
const res = await apiFetch(`/search?q=${encodeURIComponent(q)}&page=${page}`);
if (res.ok) data = await res.json();
} catch {
// API unavailable — render empty results
}
return (
<div className="max-w-2xl">
<h1 className="text-xl font-semibold mb-4">Search</h1>
<SearchResults hits={data.hits} total={data.total} q={q} page={Number(page)} />
</div>
);
}
@@ -0,0 +1,87 @@
'use client';
import { useState } from 'react';
type Status = 'ACTIVE' | 'DISCONNECTED' | 'BANNED' | 'PAIRING';
interface BotSummary {
id: string;
jid: string | null;
displayName: string | null;
status: Status;
}
export function BotSettingsCard({ initial }: { initial: { bot: BotSummary | null; shared: boolean; sharedBotId?: string } }) {
const [bot, setBot] = useState<BotSummary | null>(initial.bot);
const [revealedJid, setRevealedJid] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
async function onReveal() {
setError(null);
const res = await fetch('/api/bot/reveal', {
method: 'POST',
credentials: 'include',
});
if (res.ok) {
const data = (await res.json()) as { jid: string };
setRevealedJid(data.jid);
} else {
setError('Reveal failed');
}
}
if (!bot) {
return (
<div className="rounded-lg border border-gray-200 p-6 bg-white">
<h2 className="text-lg font-medium mb-2">Bot</h2>
<p className="text-sm text-gray-600">
No bot assigned yet. Contact your platform administrator to get one assigned.
</p>
</div>
);
}
return (
<div className="rounded-lg border border-gray-200 p-6 bg-white">
<div className="flex items-center justify-between mb-3">
<h2 className="text-lg font-medium">Bot</h2>
<span
className={`text-xs px-2 py-1 rounded ${
bot.status === 'ACTIVE'
? 'bg-green-100 text-green-800'
: bot.status === 'PAIRING'
? 'bg-yellow-100 text-yellow-800'
: 'bg-red-100 text-red-800'
}`}
>
{bot.status}
</span>
</div>
<dl className="text-sm space-y-1 mb-4">
<div>
<dt className="inline font-medium">Number: </dt>
<dd className="inline">
{revealedJid ?? (bot.jid ? '••••••••••' : '—')}
{!revealedJid && bot.status === 'ACTIVE' && (
<button
type="button"
onClick={onReveal}
className="ml-2 text-xs text-blue-600 underline"
>
Reveal
</button>
)}
</dd>
</div>
<div>
<dt className="inline font-medium">Display name: </dt>
<dd className="inline">{bot.displayName ?? '—'}</dd>
</div>
</dl>
<p className="text-xs text-gray-400">
Bot is assigned by the platform administrator. Contact support to change or remove it.
</p>
{error && <p className="text-sm text-red-600 mt-2">{error}</p>}
</div>
);
}
@@ -0,0 +1,41 @@
import { BotSettingsCard } from './BotSettingsCard';
import { apiFetch } from '@/app/_lib/api';
interface BotSummary {
id: string;
platform: string;
jid: string | null;
displayName: string | null;
status: 'ACTIVE' | 'DISCONNECTED' | 'BANNED' | 'PAIRING';
isBot: boolean;
createdAt: string;
updatedAt: string;
}
interface BotState {
bot: BotSummary | null;
shared: boolean;
}
export default async function BotSettingsPage() {
let state: BotState = { bot: null, shared: false };
try {
const res = await apiFetch('/admin/bot');
if (res.ok) {
state = (await res.json()) as BotState;
}
} catch {
state = { bot: null, shared: false };
}
return (
<div className="max-w-2xl">
<h1 className="text-xl font-semibold mb-6">Bot Settings</h1>
<p className="text-sm text-gray-600 mb-4">
TOWER runs on a dedicated WhatsApp number. Adding the bot to a group makes it eligible for
claim by any tenant admin. The bot number is hidden from members and the public web.
</p>
<BotSettingsCard initial={state} />
</div>
);
}
@@ -0,0 +1,189 @@
'use client';
import { useState } from 'react';
interface RuleData {
id: string;
matchType: 'HASHTAG' | 'PREFIX' | 'REACTION_EMOJI';
matchValue: string;
action: 'FLAG' | 'AUTO_APPROVE' | 'SKIP' | 'REJECT';
priority: number;
isActive: boolean;
createdAt: string;
updatedAt: string;
}
const MATCH_TYPE_LABELS: Record<string, string> = {
HASHTAG: 'Hashtag',
PREFIX: 'Prefix',
REACTION_EMOJI: 'Reaction Emoji',
};
const ACTION_LABELS: Record<string, string> = {
FLAG: 'Flag (Pending)',
AUTO_APPROVE: 'Auto-approve',
SKIP: 'Skip (Silent Drop)',
REJECT: 'Reject (Visible)',
};
export function RuleManager({ initial }: { initial: RuleData[] }) {
const [rules, setRules] = useState<RuleData[]>(initial);
const [matchType, setMatchType] = useState<'HASHTAG' | 'PREFIX' | 'REACTION_EMOJI'>('HASHTAG');
const [matchValue, setMatchValue] = useState('');
const [action, setAction] = useState<'FLAG' | 'AUTO_APPROVE' | 'SKIP' | 'REJECT'>('FLAG');
const [priority, setPriority] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
async function addRule() {
if (!matchValue.trim()) return;
setBusy(true);
setError('');
try {
const res = await fetch('/api/rules', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ matchType, matchValue: matchValue.trim(), action, priority }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({ message: 'Failed to create rule' }));
setError(err.message ?? 'Failed to create rule');
return;
}
const created: RuleData = await res.json();
setRules((prev) => [...prev, created].sort((a, b) => a.priority - b.priority));
setMatchValue('');
setAction('FLAG');
setPriority(0);
} finally {
setBusy(false);
}
}
async function toggleRule(rule: RuleData) {
const res = await fetch(`/api/rules/${rule.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ isActive: !rule.isActive }),
});
if (res.ok) {
const updated: RuleData = await res.json();
setRules((prev) => prev.map((r) => (r.id === rule.id ? updated : r)));
}
}
async function deleteRule(id: string) {
const res = await fetch(`/api/rules/${id}`, { method: 'DELETE' });
if (res.ok) setRules((prev) => prev.filter((r) => r.id !== id));
}
return (
<div className="flex flex-col gap-6">
<section className="border border-gray-200 rounded-lg p-4">
<h2 className="text-base font-semibold mb-3">Add Rule</h2>
<div className="flex flex-wrap items-end gap-3">
<div className="flex flex-col gap-1">
<label className="text-xs text-gray-500">Type</label>
<select
value={matchType}
onChange={(e) => setMatchType(e.target.value as any)}
className="border border-gray-300 rounded px-3 py-2 text-sm"
>
<option value="HASHTAG">Hashtag</option>
<option value="PREFIX">Prefix</option>
<option value="REACTION_EMOJI">Reaction Emoji</option>
</select>
</div>
<div className="flex flex-col gap-1">
<label className="text-xs text-gray-500">Value</label>
<input
value={matchValue}
onChange={(e) => setMatchValue(e.target.value)}
placeholder={matchType === 'REACTION_EMOJI' ? '⭐' : '#important'}
className="border border-gray-300 rounded px-3 py-2 text-sm w-40"
/>
</div>
<div className="flex flex-col gap-1">
<label className="text-xs text-gray-500">Action</label>
<select
value={action}
onChange={(e) => setAction(e.target.value as any)}
className="border border-gray-300 rounded px-3 py-2 text-sm"
>
<option value="FLAG">Flag (Pending)</option>
<option value="AUTO_APPROVE">Auto-approve</option>
<option value="SKIP">Skip (Silent Drop)</option>
<option value="REJECT">Reject (Visible)</option>
</select>
</div>
<div className="flex flex-col gap-1">
<label className="text-xs text-gray-500">Priority</label>
<input
type="number"
value={priority}
onChange={(e) => setPriority(Number(e.target.value))}
className="border border-gray-300 rounded px-3 py-2 text-sm w-20"
/>
</div>
<button
type="button"
onClick={() => void addRule()}
disabled={busy || !matchValue.trim()}
className="bg-blue-600 text-white rounded px-4 py-2 text-sm hover:bg-blue-700 disabled:opacity-40"
>
{busy ? 'Adding...' : 'Add Rule'}
</button>
</div>
{error && <p className="text-red-600 text-sm mt-2">{error}</p>}
</section>
<section>
<h2 className="text-base font-semibold mb-3">Active Rules</h2>
{rules.length === 0 ? (
<p className="text-sm text-gray-400">No rules configured. Messages without matching rules are ignored.</p>
) : (
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-200 text-left text-gray-500">
<th className="pb-2 pr-3">Type</th>
<th className="pb-2 pr-3">Value</th>
<th className="pb-2 pr-3">Action</th>
<th className="pb-2 pr-3">Priority</th>
<th className="pb-2 pr-3">Active</th>
<th className="pb-2" />
</tr>
</thead>
<tbody>
{rules.map((rule) => (
<tr key={rule.id} className="border-b border-gray-100">
<td className="py-2 pr-3">{MATCH_TYPE_LABELS[rule.matchType] ?? rule.matchType}</td>
<td className="py-2 pr-3 font-mono">{rule.matchValue}</td>
<td className="py-2 pr-3">{ACTION_LABELS[rule.action] ?? rule.action}</td>
<td className="py-2 pr-3">{rule.priority}</td>
<td className="py-2 pr-3">
<button
type="button"
onClick={() => void toggleRule(rule)}
className={`text-xs rounded px-2 py-0.5 ${rule.isActive ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-500'}`}
>
{rule.isActive ? 'ON' : 'OFF'}
</button>
</td>
<td className="py-2">
<button
type="button"
onClick={() => void deleteRule(rule.id)}
className="text-red-600 hover:text-red-800 text-xs"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</section>
</div>
);
}
@@ -0,0 +1,36 @@
import { RuleManager } from './RuleManager';
import { apiFetch } from '@/app/_lib/api';
interface RuleData {
id: string;
matchType: 'HASHTAG' | 'PREFIX' | 'REACTION_EMOJI';
matchValue: string;
action: 'FLAG' | 'AUTO_APPROVE' | 'SKIP' | 'REJECT';
priority: number;
isActive: boolean;
createdAt: string;
updatedAt: string;
}
export default async function RulesSettingsPage() {
let rules: RuleData[] = [];
try {
const res = await apiFetch('/admin/rules');
if (res.ok) {
rules = (await res.json()) as RuleData[];
}
} catch {
rules = [];
}
return (
<div className="max-w-2xl">
<h1 className="text-xl font-semibold mb-6">Rules Engine</h1>
<p className="text-sm text-gray-600 mb-4">
Configure which hashtags, prefixes, and reaction emojis trigger message processing
and what action TOWER should take. Rules are matched in priority order.
</p>
<RuleManager initial={rules} />
</div>
);
}
@@ -0,0 +1,107 @@
import Link from 'next/link';
import { apiFetch } from '@/app/_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">&larr; 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">&larr; 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} &middot; {thread.messageCount} messages &middot; 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">&middot;</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>
);
}
+68
View File
@@ -0,0 +1,68 @@
import Link from 'next/link';
import { apiFetch } from '@/app/_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>
);
}