feat: portal redesign — shadcn/ui, React Query, Zod, isolated portals
Foundation: - CLAUDE.md with full coding rules (tech stack, patterns, redirect rules) - Install @tanstack/react-query, zod, react-hook-form, shadcn/ui deps - CSS variables design system (Tailwind v4 + tw-animate-css) - Shared components: Button, Input, Label, Card, Badge, Separator, Form - PortalLoginShell: two-column login layout (branding left, form right) - PortalNav: shared sidebar nav used by all portals - ReactQueryProvider in root layout - api-client.ts: typed fetch wrapper (no raw fetch in components) Portal isolation: - Sidebar now returns null for all non-chapter routes; portals own their layout - Admin layout: auth guard + PortalNav (slate accent) - Org layout: auth guard + PortalNav (violet accent) - Member layout: server-side cookie check → MemberNav client component - Chapter admin sidebar: PortalNav (blue accent) Login pages (all use react-hook-form + Zod + PortalLoginShell): - /login → defaults next to /search (was /) — fixes redirect bug - /admin/login → replaces /admin - /org/login → replaces /org - /member-login → two-step phone+OTP with proper form validation Portal selector (/) redesigned with accent border-left cards Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
# TOWER — Claude Code Rules
|
||||
|
||||
## Project Overview
|
||||
|
||||
TOWER is a multi-tenant WhatsApp community management platform. It has four portals served by a single Next.js app and a single NestJS API:
|
||||
|
||||
| Portal | Path prefix | Auth cookie | Guard |
|
||||
|--------|------------|-------------|-------|
|
||||
| Portal selector | `/` | — | public |
|
||||
| Chapter admin | `/`, `/search`, `/groups`, `/messages`, `/drafts`, `/settings`, `/threads`, `/claim-group` | `tower_token` | `JwtAuthGuard` |
|
||||
| Organisation admin | `/org/*` | `tower_org_token` | `OrgAdminGuard` |
|
||||
| Super admin | `/admin/*` | `tower_super_token` | `SuperAdminGuard` |
|
||||
| Member | `/my/*`, `/onboard`, `/member-login` | `tower_member_token` | `MemberAuthGuard` |
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Next.js 16** (App Router, TypeScript) — `apps/web`
|
||||
- **NestJS** (TypeScript) — `apps/api`
|
||||
- **Prisma** — ORM, PostgreSQL
|
||||
- **BullMQ** + **Redis** — job queues
|
||||
- **Tailwind CSS v4** — utility-first CSS
|
||||
- **shadcn/ui** — component library (new-york style, CSS variables)
|
||||
- **TanStack React Query** — all data fetching and mutations, no raw `fetch` in components
|
||||
- **Zod** — all schema validation (forms, API response shapes)
|
||||
- **react-hook-form** + **@hookform/resolvers/zod** — all forms
|
||||
- **lucide-react** — icons
|
||||
|
||||
## File & Folder Conventions
|
||||
|
||||
```
|
||||
apps/web/app/
|
||||
_lib/ # Shared utilities and contexts
|
||||
api.ts # getApiBaseUrl, jsonResponse, cookie helpers
|
||||
query-client.tsx # QueryClientProvider wrapper
|
||||
auth-context.tsx # Chapter admin auth (tower_token)
|
||||
super-admin-context.tsx # Super admin auth (tower_super_token)
|
||||
org-admin-context.tsx # Org admin auth (tower_org_token)
|
||||
utils.ts # cn() helper
|
||||
_components/ # Shared UI components (shadcn + custom)
|
||||
ui/ # Raw shadcn components (never edit directly)
|
||||
portal-shell.tsx # Shared portal layout wrapper
|
||||
nav-user.tsx # User dropdown in nav
|
||||
data-table.tsx # Shared table component
|
||||
api/ # Next.js BFF route handlers only
|
||||
auth/…
|
||||
admin/…
|
||||
org/…
|
||||
my/…
|
||||
(public)/ # Portal selector + all login pages (no auth)
|
||||
admin/ # Super admin portal
|
||||
org/ # Org admin portal
|
||||
my/ # Member portal
|
||||
[chapter pages]/ # Chapter admin pages at root level
|
||||
```
|
||||
|
||||
## Coding Rules
|
||||
|
||||
### General
|
||||
- **No raw `fetch` in components.** All API calls go through TanStack Query hooks. Define queries in a co-located `_queries.ts` or inline `useQuery`/`useMutation`.
|
||||
- **No `useState` for server data.** Use React Query. `useState` is for UI-only state (modal open, tab selection, etc.).
|
||||
- **All forms use react-hook-form + Zod.** Schema first: define a `z.object({...})` schema, derive the type with `z.infer`, pass resolver to `useForm`.
|
||||
- **Shared components live in `app/_components/`.** Never duplicate a button, input, or card across portals.
|
||||
- **Each portal has its own layout** with nav/sidebar. Do not put portal UI logic in the root layout.
|
||||
- **No `any` types.** Use proper types or `unknown` + type narrowing.
|
||||
|
||||
### TanStack React Query
|
||||
```tsx
|
||||
// Define query key factories
|
||||
export const tenantKeys = {
|
||||
all: ['tenants'] as const,
|
||||
list: () => [...tenantKeys.all, 'list'] as const,
|
||||
detail: (id: string) => [...tenantKeys.all, 'detail', id] as const,
|
||||
};
|
||||
|
||||
// In component
|
||||
const { data, isPending } = useQuery({
|
||||
queryKey: tenantKeys.list(),
|
||||
queryFn: () => api.get<Tenant[]>('/api/admin/tenants'),
|
||||
});
|
||||
|
||||
// Mutations always invalidate related queries
|
||||
const mutation = useMutation({
|
||||
mutationFn: (body: CreateTenantInput) => api.post('/api/admin/tenants', body),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: tenantKeys.all }),
|
||||
});
|
||||
```
|
||||
|
||||
### Forms
|
||||
```tsx
|
||||
const schema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
function MyForm() {
|
||||
const form = useForm<FormValues>({ resolver: zodResolver(schema) });
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<FormField control={form.control} name="email" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl><Input {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### API Helper
|
||||
Use the typed `api` helper from `_lib/api-client.ts` — never call `fetch` directly in components or hooks:
|
||||
```ts
|
||||
// app/_lib/api-client.ts
|
||||
export const api = {
|
||||
get: <T>(url: string) => fetch(url, { cache: 'no-store' }).then(r => r.ok ? r.json() as T : Promise.reject(r)),
|
||||
post: <T>(url: string, body: unknown) => fetch(url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body) }).then(r => r.ok ? r.json() as T : Promise.reject(r)),
|
||||
patch: <T>(url: string, body: unknown) => fetch(url, { method: 'PATCH', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body) }).then(r => r.ok ? r.json() as T : Promise.reject(r)),
|
||||
del: (url: string) => fetch(url, { method: 'DELETE' }).then(r => { if (!r.ok) return Promise.reject(r); }),
|
||||
};
|
||||
```
|
||||
|
||||
### Auth Contexts
|
||||
Each portal's auth context provides:
|
||||
- `user` / `admin` — the authenticated entity (undefined when loading)
|
||||
- `loading` — boolean
|
||||
- `login(...)` — sets cookie via BFF, updates context
|
||||
- `logout()` — clears cookie, redirects to portal login
|
||||
|
||||
Auth guard pattern (in portal layout, server component):
|
||||
```tsx
|
||||
// In a portal layout — always server component
|
||||
import { cookies } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default async function PortalLayout({ children }) {
|
||||
const token = (await cookies()).get('tower_token')?.value;
|
||||
if (!token) redirect('/login');
|
||||
return <PortalShell>{children}</PortalShell>;
|
||||
}
|
||||
```
|
||||
|
||||
### Styling
|
||||
- Use shadcn/ui components as the base. Extend with Tailwind utilities.
|
||||
- **No inline styles.** All styles via Tailwind classes.
|
||||
- **No magic numbers in class names** — use design tokens (`text-sm`, `p-4`, `gap-2` — not arbitrary `p-[13px]`).
|
||||
- Colors: use semantic tokens (`text-foreground`, `bg-muted`, `border`) not raw colors.
|
||||
- Dark mode: set up via `class` strategy but only if explicitly requested.
|
||||
|
||||
### NestJS API Rules
|
||||
- All protected endpoints use a Guard decorator — never trust the request without it.
|
||||
- DTOs use `class-validator` decorators. `ValidationPipe` with `whitelist: true, forbidNonWhitelisted: true` is global.
|
||||
- Always use `select` in Prisma queries to avoid leaking `passwordHash` or other sensitive fields.
|
||||
- Org-scoped queries always include `organizationId` in the `where` clause.
|
||||
- Tenant-scoped queries always include `tenantId` in the `where` clause.
|
||||
|
||||
### Redirect Rules (IMPORTANT)
|
||||
After successful login, each portal redirects to its own home:
|
||||
- Chapter admin: `/search` (or `next` param if set)
|
||||
- Org admin: `/org`
|
||||
- Super admin: `/admin`
|
||||
- Member: `/my`
|
||||
|
||||
Never redirect to `/` after login — that is the public portal selector.
|
||||
|
||||
### Commit Style
|
||||
Conventional commits: `feat:`, `fix:`, `refactor:`, `chore:`
|
||||
Co-author every commit with Claude.
|
||||
@@ -0,0 +1,49 @@
|
||||
import { cn } from '../_lib/utils';
|
||||
|
||||
interface PortalLoginShellProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
accentClass?: string;
|
||||
children: React.ReactNode;
|
||||
footer?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function PortalLoginShell({ title, subtitle, accentClass = 'bg-primary', children, footer }: PortalLoginShellProps) {
|
||||
return (
|
||||
<div className="min-h-screen grid lg:grid-cols-2">
|
||||
{/* Left branding panel */}
|
||||
<div className={cn('hidden lg:flex flex-col justify-between p-10 text-white', accentClass)}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-bold text-xl tracking-tight">TOWER</span>
|
||||
</div>
|
||||
<div>
|
||||
<blockquote className="space-y-2">
|
||||
<p className="text-lg font-medium leading-relaxed">
|
||||
"Community knowledge, beautifully organised."
|
||||
</p>
|
||||
<footer className="text-sm opacity-70">Insignia TOWER Platform</footer>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right form panel */}
|
||||
<div className="flex items-center justify-center p-8 bg-background">
|
||||
<div className="w-full max-w-sm space-y-6">
|
||||
{/* Mobile logo */}
|
||||
<div className="flex items-center gap-2 lg:hidden">
|
||||
<span className="font-bold text-lg">TOWER</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-2xl font-bold tracking-tight">{title}</h1>
|
||||
<p className="text-sm text-muted-foreground">{subtitle}</p>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
|
||||
{footer && <div className="text-center text-sm text-muted-foreground">{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { cn } from '../_lib/utils';
|
||||
import { Button } from './ui/button';
|
||||
import { Separator } from './ui/separator';
|
||||
import { LogOut } from 'lucide-react';
|
||||
|
||||
interface NavItem {
|
||||
href: string;
|
||||
label: string;
|
||||
icon?: React.ReactNode;
|
||||
}
|
||||
|
||||
interface PortalNavProps {
|
||||
portalName: string;
|
||||
navItems: NavItem[];
|
||||
user?: { name?: string | null; email?: string | null; role?: string };
|
||||
onLogout: () => void;
|
||||
accentClass?: string;
|
||||
}
|
||||
|
||||
export function PortalNav({ portalName, navItems, user, onLogout, accentClass = 'text-primary' }: PortalNavProps) {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<nav className="w-56 shrink-0 flex flex-col h-full border-r bg-sidebar">
|
||||
{/* Logo */}
|
||||
<div className="px-4 py-5 flex items-center gap-2">
|
||||
<span className={cn('font-bold text-base', accentClass)}>TOWER</span>
|
||||
<Separator orientation="vertical" className="h-4" />
|
||||
<span className="text-xs text-muted-foreground font-medium">{portalName}</span>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Nav links */}
|
||||
<div className="flex-1 overflow-y-auto py-3 px-2 space-y-0.5">
|
||||
{navItems.map((item) => {
|
||||
const active = item.href === '/'
|
||||
? pathname === '/'
|
||||
: pathname.startsWith(item.href);
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={cn(
|
||||
'flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors',
|
||||
active
|
||||
? 'bg-accent text-accent-foreground font-medium'
|
||||
: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
|
||||
)}
|
||||
>
|
||||
{item.icon && <span className="size-4 shrink-0">{item.icon}</span>}
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* User footer */}
|
||||
{user && (
|
||||
<div className="p-3 space-y-2">
|
||||
<div className="px-3 py-2">
|
||||
<p className="text-sm font-medium truncate">{user.name ?? user.email}</p>
|
||||
{user.name && <p className="text-xs text-muted-foreground truncate">{user.email}</p>}
|
||||
{user.role && (
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wide mt-0.5">{user.role.replace(/_/g, ' ')}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="w-full justify-start text-muted-foreground" onClick={onLogout}>
|
||||
<LogOut className="size-4" />
|
||||
Sign out
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../../_lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
destructive: 'border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80',
|
||||
outline: 'text-foreground',
|
||||
success: 'border-transparent bg-emerald-100 text-emerald-700',
|
||||
warning: 'border-transparent bg-amber-100 text-amber-700',
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'default' },
|
||||
},
|
||||
);
|
||||
|
||||
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -0,0 +1,43 @@
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../../_lib/utils';
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
|
||||
destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
|
||||
outline: 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
|
||||
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
||||
link: 'text-primary underline-offset-4 hover:underline',
|
||||
},
|
||||
size: {
|
||||
default: 'h-9 px-4 py-2',
|
||||
sm: 'h-8 rounded-md px-3 text-xs',
|
||||
lg: 'h-10 rounded-md px-8',
|
||||
icon: 'h-9 w-9',
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: 'default', size: 'default' },
|
||||
},
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
|
||||
},
|
||||
);
|
||||
Button.displayName = 'Button';
|
||||
|
||||
export { Button, buttonVariants };
|
||||
@@ -0,0 +1,44 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../../_lib/utils';
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('rounded-xl border bg-card text-card-foreground shadow-sm', className)} {...props} />
|
||||
),
|
||||
);
|
||||
Card.displayName = 'Card';
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardHeader.displayName = 'CardHeader';
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<h3 ref={ref} className={cn('font-semibold leading-none tracking-tight', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardTitle.displayName = 'CardTitle';
|
||||
|
||||
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<p ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardDescription.displayName = 'CardDescription';
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => <div ref={ref} className={cn('p-6 pt-0', className)} {...props} />,
|
||||
);
|
||||
CardContent.displayName = 'CardContent';
|
||||
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />
|
||||
),
|
||||
);
|
||||
CardFooter.displayName = 'CardFooter';
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
|
||||
@@ -0,0 +1,100 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { Controller, FormProvider, useFormContext, type ControllerProps, type FieldPath, type FieldValues } from 'react-hook-form';
|
||||
import { cn } from '../../_lib/utils';
|
||||
import { Label } from './label';
|
||||
|
||||
const Form = FormProvider;
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = { name: TName };
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue);
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
);
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext);
|
||||
const itemContext = React.useContext(FormItemContext);
|
||||
const { getFieldState, formState } = useFormContext();
|
||||
const fieldState = getFieldState(fieldContext.name, formState);
|
||||
if (!fieldContext) throw new Error('useFormField should be used within <FormField>');
|
||||
const { id } = itemContext;
|
||||
return { id, name: fieldContext.name, formItemId: `${id}-form-item`, formDescriptionId: `${id}-form-item-description`, formMessageId: `${id}-form-item-message`, ...fieldState };
|
||||
};
|
||||
|
||||
type FormItemContextValue = { id: string };
|
||||
const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue);
|
||||
|
||||
const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => {
|
||||
const id = React.useId();
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div ref={ref} className={cn('space-y-2', className)} {...props} />
|
||||
</FormItemContext.Provider>
|
||||
);
|
||||
});
|
||||
FormItem.displayName = 'FormItem';
|
||||
|
||||
const FormLabel = React.forwardRef<
|
||||
React.ComponentRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { error, formItemId } = useFormField();
|
||||
return <Label ref={ref} className={cn(error && 'text-destructive', className)} htmlFor={formItemId} {...props} />;
|
||||
});
|
||||
FormLabel.displayName = 'FormLabel';
|
||||
|
||||
const FormControl = React.forwardRef<React.ComponentRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot>>(
|
||||
({ ...props }, ref) => {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
|
||||
return (
|
||||
<Slot
|
||||
ref={ref}
|
||||
id={formItemId}
|
||||
aria-describedby={!error ? formDescriptionId : `${formDescriptionId} ${formMessageId}`}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
FormControl.displayName = 'FormControl';
|
||||
|
||||
const FormDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
|
||||
({ className, ...props }, ref) => {
|
||||
const { formDescriptionId } = useFormField();
|
||||
return <p ref={ref} id={formDescriptionId} className={cn('text-sm text-muted-foreground', className)} {...props} />;
|
||||
},
|
||||
);
|
||||
FormDescription.displayName = 'FormDescription';
|
||||
|
||||
const FormMessage = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
|
||||
({ className, children, ...props }, ref) => {
|
||||
const { error, formMessageId } = useFormField();
|
||||
const body = error ? String(error?.message ?? '') : children;
|
||||
if (!body) return null;
|
||||
return (
|
||||
<p ref={ref} id={formMessageId} className={cn('text-sm font-medium text-destructive', className)} {...props}>
|
||||
{body}
|
||||
</p>
|
||||
);
|
||||
},
|
||||
);
|
||||
FormMessage.displayName = 'FormMessage';
|
||||
|
||||
export { useFormField, Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField };
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../../_lib/utils';
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
|
||||
({ className, type, ...props }, ref) => (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
Input.displayName = 'Input';
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import { cn } from '../../_lib/utils';
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ComponentRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn('text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Label.displayName = LabelPrimitive.Root.displayName;
|
||||
|
||||
export { Label };
|
||||
@@ -0,0 +1,21 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as SeparatorPrimitive from '@radix-ui/react-separator';
|
||||
import { cn } from '../../_lib/utils';
|
||||
|
||||
const Separator = React.forwardRef<
|
||||
React.ComponentRef<typeof SeparatorPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||
>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => (
|
||||
<SeparatorPrimitive.Root
|
||||
ref={ref}
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn('shrink-0 bg-border', orientation === 'horizontal' ? 'h-px w-full' : 'h-full w-px', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Separator.displayName = SeparatorPrimitive.Root.displayName;
|
||||
|
||||
export { Separator };
|
||||
@@ -0,0 +1,29 @@
|
||||
async function handleResponse<T>(res: Response): Promise<T> {
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ message: res.statusText })) as { message?: string };
|
||||
throw new Error(body.message ?? `HTTP ${res.status}`);
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(url: string) =>
|
||||
fetch(url, { cache: 'no-store' }).then((r) => handleResponse<T>(r)),
|
||||
|
||||
post: <T>(url: string, body?: unknown) =>
|
||||
fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
}).then((r) => handleResponse<T>(r)),
|
||||
|
||||
patch: <T>(url: string, body: unknown) =>
|
||||
fetch(url, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}).then((r) => handleResponse<T>(r)),
|
||||
|
||||
del: (url: string) =>
|
||||
fetch(url, { method: 'DELETE' }).then((r) => handleResponse<void>(r)),
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
'use client';
|
||||
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
|
||||
export function ReactQueryProvider({ children }: { children: React.ReactNode }) {
|
||||
const [client] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { staleTime: 30_000, retry: 1 },
|
||||
mutations: { retry: 0 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
|
||||
}
|
||||
+34
-114
@@ -1,137 +1,57 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSuperAdmin } from './super-admin-context';
|
||||
import { useEffect } from 'react';
|
||||
import { useAuth } from './auth-context';
|
||||
import { PortalNav } from '../_components/portal-nav';
|
||||
import {
|
||||
Search, Users, MessageSquare, FileText, Settings, Bot,
|
||||
LayoutDashboard, Building2, Server, Inbox,
|
||||
} from 'lucide-react';
|
||||
|
||||
const NAV_LINKS = [
|
||||
{ href: '/search', label: 'Search' },
|
||||
{ href: '/groups', label: 'Groups & Routes' },
|
||||
{ href: '/messages/pending', label: 'Pending messages' },
|
||||
{ href: '/drafts', label: 'AI Drafts' },
|
||||
{ href: '/settings/rules', label: 'Rules' },
|
||||
{ href: '/settings/bot', label: 'Bot' },
|
||||
// Paths that render their own full-screen layout (no sidebar)
|
||||
const FULLSCREEN_PATHS = ['/', '/login', '/member-login', '/onboard', '/admin/login', '/org/login', '/org', '/admin', '/my'];
|
||||
|
||||
const CHAPTER_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: <Settings /> },
|
||||
{ href: '/settings/bot', label: 'Bot', icon: <Bot /> },
|
||||
];
|
||||
|
||||
const SUPER_ADMIN_LINKS = [
|
||||
{ href: '/admin', label: 'Dashboard' },
|
||||
{ href: '/admin/tenants', label: 'Tenants' },
|
||||
{ href: '/admin/bots', label: 'Bot Pool' },
|
||||
{ href: '/admin/drafts', label: 'AI Drafts' },
|
||||
];
|
||||
|
||||
const PUBLIC_PATHS = ['/login', '/onboard', '/member-login'];
|
||||
const ADMIN_PATHS = ['/admin'];
|
||||
const MEMBER_PATHS = ['/my'];
|
||||
const ORG_PATHS = ['/org'];
|
||||
|
||||
export function Sidebar() {
|
||||
const { admin, loading, logout } = useAuth();
|
||||
const { admin: superAdmin, logout: superLogout } = useSuperAdmin();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const [pendingCount, setPendingCount] = useState<number | null>(null);
|
||||
|
||||
const isFullscreen = FULLSCREEN_PATHS.some((p) =>
|
||||
p === '/' ? pathname === '/' : pathname === p || pathname.startsWith(p + '/'),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/messages/pending/count')
|
||||
.then((r) => r.ok ? r.json() : null)
|
||||
.then((data) => setPendingCount(data?.count ?? null))
|
||||
.catch(() => setPendingCount(null));
|
||||
}, []);
|
||||
if (loading || isFullscreen) return;
|
||||
if (!admin) router.replace(`/login?next=${encodeURIComponent(pathname)}`);
|
||||
}, [loading, admin, pathname, router, isFullscreen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (pathname === '/') return;
|
||||
if (PUBLIC_PATHS.some((p) => pathname.startsWith(p))) return;
|
||||
if (ADMIN_PATHS.some((p) => pathname.startsWith(p))) return;
|
||||
if (MEMBER_PATHS.some((p) => pathname.startsWith(p))) return;
|
||||
if (ORG_PATHS.some((p) => pathname.startsWith(p))) return;
|
||||
if (!admin) {
|
||||
router.replace(`/login?next=${encodeURIComponent(pathname)}`);
|
||||
}
|
||||
}, [loading, admin, pathname, router]);
|
||||
if (isFullscreen) return null;
|
||||
|
||||
if (pathname === '/' || PUBLIC_PATHS.some((p) => pathname.startsWith(p))) {
|
||||
if (loading) {
|
||||
return (
|
||||
<nav className="w-52 shrink-0 bg-white border-r border-gray-200 p-4">
|
||||
<span className="font-bold text-base">TOWER</span>
|
||||
</nav>
|
||||
<div className="w-56 shrink-0 border-r bg-sidebar animate-pulse" />
|
||||
);
|
||||
}
|
||||
|
||||
if (ADMIN_PATHS.some((p) => pathname.startsWith(p))) {
|
||||
return (
|
||||
<nav className="w-52 shrink-0 bg-white border-r border-gray-200 p-4 flex flex-col">
|
||||
<span className="font-bold text-base mb-4">TOWER Admin</span>
|
||||
<div className="flex flex-col gap-1 flex-1">
|
||||
{SUPER_ADMIN_LINKS.map((link) => (
|
||||
<Link key={link.href} href={link.href} className="rounded px-3 py-2 text-sm hover:bg-gray-100">
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<div className="border-t border-gray-200 pt-3 mt-3 flex flex-col gap-2">
|
||||
<div className="px-3 text-xs text-gray-500">
|
||||
<div className="font-medium text-gray-700 truncate">{superAdmin?.email}</div>
|
||||
<div className="uppercase tracking-wide">Super Admin</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void superLogout()}
|
||||
className="text-left rounded px-3 py-2 text-sm hover:bg-gray-100"
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
if (MEMBER_PATHS.some((p) => pathname.startsWith(p))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ORG_PATHS.some((p) => pathname.startsWith(p))) {
|
||||
return null;
|
||||
}
|
||||
if (!admin) return null;
|
||||
|
||||
return (
|
||||
<nav className="w-52 shrink-0 bg-white border-r border-gray-200 p-4 flex flex-col">
|
||||
<span className="font-bold text-base mb-4">TOWER</span>
|
||||
<div className="flex flex-col gap-1 flex-1">
|
||||
{NAV_LINKS.map((link) => (
|
||||
<Link
|
||||
key={link.href}
|
||||
href={link.href}
|
||||
className="rounded px-3 py-2 text-sm hover:bg-gray-100 flex items-center justify-between"
|
||||
>
|
||||
<span>{link.label}</span>
|
||||
{link.href === '/messages/pending' && pendingCount !== null && pendingCount > 0 && (
|
||||
<span className="bg-blue-600 text-white text-[11px] font-bold rounded-full w-5 h-5 flex items-center justify-center">
|
||||
{pendingCount > 99 ? '99+' : pendingCount}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
{admin && (
|
||||
<div className="border-t border-gray-200 pt-3 mt-3 flex flex-col gap-2">
|
||||
<div className="px-3 text-xs text-gray-500">
|
||||
<div className="font-medium text-gray-700 truncate">{admin.name ?? admin.email}</div>
|
||||
<div className="truncate">{admin.tenantName}</div>
|
||||
<div className="uppercase tracking-wide">{admin.role}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void logout()}
|
||||
className="text-left rounded px-3 py-2 text-sm hover:bg-gray-100"
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</nav>
|
||||
<PortalNav
|
||||
portalName="Chapter"
|
||||
navItems={CHAPTER_NAV}
|
||||
accentClass="text-blue-600"
|
||||
user={{ email: admin.email, name: admin.name ?? undefined, role: admin.role }}
|
||||
onLogout={() => { void logout(); router.replace('/login'); }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -1,3 +1,47 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useSuperAdmin } from '../_lib/super-admin-context';
|
||||
import { PortalNav } from '../_components/portal-nav';
|
||||
import { LayoutDashboard, Building2, Server, FileText } from 'lucide-react';
|
||||
|
||||
const NAV = [
|
||||
{ href: '/admin', label: 'Dashboard', icon: <LayoutDashboard /> },
|
||||
{ href: '/admin/orgs', label: 'Organisations', icon: <Building2 /> },
|
||||
{ href: '/admin/tenants', label: 'Chapters', icon: <Building2 /> },
|
||||
{ href: '/admin/bots', label: 'Bot Pool', icon: <Server /> },
|
||||
{ href: '/admin/drafts', label: 'AI Drafts', icon: <FileText /> },
|
||||
];
|
||||
|
||||
export default function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
return <>{children}</>;
|
||||
const { admin, loading, logout } = useSuperAdmin();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && !admin) router.replace('/admin/login');
|
||||
}, [admin, loading, router]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex h-screen -m-6">
|
||||
<div className="w-56 shrink-0 border-r bg-sidebar animate-pulse" />
|
||||
<div className="flex-1" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!admin) return null;
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden -m-6">
|
||||
<PortalNav
|
||||
portalName="Admin"
|
||||
navItems={NAV}
|
||||
accentClass="text-slate-900"
|
||||
user={{ email: admin.email, name: admin.name ?? undefined, role: 'Super Admin' }}
|
||||
onLogout={() => { void logout(); router.replace('/admin/login'); }}
|
||||
/>
|
||||
<main className="flex-1 overflow-auto bg-muted/30 p-6">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,60 +1,68 @@
|
||||
'use client';
|
||||
|
||||
import { FormEvent, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { useSuperAdmin } from '../../_lib/super-admin-context';
|
||||
import { PortalLoginShell } from '../../_components/portal-login-shell';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../../_components/ui/form';
|
||||
import { Input } from '../../_components/ui/input';
|
||||
import { Button } from '../../_components/ui/button';
|
||||
import Link from 'next/link';
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().email('Enter a valid email'),
|
||||
password: z.string().min(1, 'Password is required'),
|
||||
});
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
export default function SuperAdminLoginPage() {
|
||||
const { login } = useSuperAdmin();
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setBusy(true);
|
||||
const form = useForm<FormValues>({ resolver: zodResolver(schema), defaultValues: { email: '', password: '' } });
|
||||
|
||||
async function onSubmit(values: FormValues) {
|
||||
try {
|
||||
await login(email, password);
|
||||
await login(values.email, values.password);
|
||||
router.replace('/admin');
|
||||
} catch (err: any) {
|
||||
setError(err.message ?? 'Login failed');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
} catch (err) {
|
||||
form.setError('root', { message: err instanceof Error ? err.message : 'Login failed' });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-sm mx-auto mt-24">
|
||||
<h1 className="text-xl font-bold mb-4">Super Admin Login</h1>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-3">
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
className="border rounded px-3 py-2 text-sm"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
className="border rounded px-3 py-2 text-sm"
|
||||
/>
|
||||
{error && <p className="text-red-600 text-sm">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
className="bg-blue-600 text-white rounded px-4 py-2 text-sm font-medium disabled:opacity-50"
|
||||
<PortalLoginShell
|
||||
title="Super Admin"
|
||||
subtitle="Platform-wide administration access."
|
||||
accentClass="bg-slate-900"
|
||||
footer={<Link href="/" className="hover:text-foreground transition-colors">← Back to portal selector</Link>}
|
||||
>
|
||||
{busy ? 'Signing in...' : 'Sign in'}
|
||||
</button>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField control={form.control} name="email" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl><Input type="email" placeholder="superadmin@tower.com" autoComplete="username" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="password" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl><Input type="password" autoComplete="current-password" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
{form.formState.errors.root && (
|
||||
<p className="text-sm text-destructive">{form.formState.errors.root.message}</p>
|
||||
)}
|
||||
<Button type="submit" className="w-full" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Signing in…' : 'Sign in'}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</Form>
|
||||
</PortalLoginShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1 +1,80 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
:root {
|
||||
--radius: 0.5rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--destructive-foreground: oklch(0.985 0 0);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--radius-sm: calc(var(--radius) - 2px);
|
||||
--radius-md: var(--radius);
|
||||
--radius-lg: calc(var(--radius) + 2px);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
* {
|
||||
border-color: var(--border);
|
||||
outline-color: var(--ring);
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import type { Metadata } from 'next';
|
||||
import Link from 'next/link';
|
||||
import './globals.css';
|
||||
import { ReactQueryProvider } from './_lib/query-client';
|
||||
import { AuthProvider } from './_lib/auth-context';
|
||||
import { SuperAdminProvider } from './_lib/super-admin-context';
|
||||
import { OrgAdminProvider } from './_lib/org-admin-context';
|
||||
import { Sidebar } from './_lib/sidebar';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Insignia TOWER',
|
||||
title: 'TOWER',
|
||||
description: 'Community Knowledge Infrastructure Platform',
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className="flex min-h-screen bg-gray-50 text-gray-900 antialiased">
|
||||
<body className="flex min-h-screen bg-background text-foreground antialiased">
|
||||
<ReactQueryProvider>
|
||||
<AuthProvider>
|
||||
<SuperAdminProvider>
|
||||
<OrgAdminProvider>
|
||||
@@ -23,6 +24,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
||||
</OrgAdminProvider>
|
||||
</SuperAdminProvider>
|
||||
</AuthProvider>
|
||||
</ReactQueryProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
+53
-79
@@ -1,113 +1,87 @@
|
||||
'use client';
|
||||
|
||||
import { Suspense } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { Suspense, useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { useAuth } from '../_lib/auth-context';
|
||||
import { useSuperAdmin } from '../_lib/super-admin-context';
|
||||
import { PortalLoginShell } from '../_components/portal-login-shell';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../_components/ui/form';
|
||||
import { Input } from '../_components/ui/input';
|
||||
import { Button } from '../_components/ui/button';
|
||||
import Link from 'next/link';
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().email('Enter a valid email'),
|
||||
password: z.string().min(1, 'Password is required'),
|
||||
});
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
function LoginForm() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refresh } = useAuth();
|
||||
const { admin: superAdmin, loading: superLoading } = useSuperAdmin();
|
||||
const next = searchParams.get('next') ?? '/';
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [redirecting, setRedirecting] = useState(false);
|
||||
const next = searchParams.get('next') ?? '/search';
|
||||
|
||||
useEffect(() => {
|
||||
if (!superLoading && superAdmin) {
|
||||
setRedirecting(true);
|
||||
router.replace('/admin');
|
||||
}
|
||||
}, [superAdmin, superLoading, router]);
|
||||
const form = useForm<FormValues>({ resolver: zodResolver(schema), defaultValues: { email: '', password: '' } });
|
||||
|
||||
if (superLoading) {
|
||||
return <div className="bg-white p-6 rounded-xl border border-gray-200 h-64 animate-pulse" />;
|
||||
}
|
||||
|
||||
if (redirecting) {
|
||||
return <p className="text-sm text-gray-500">Redirecting to admin panel…</p>;
|
||||
}
|
||||
|
||||
async function onSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
async function onSubmit(values: FormValues) {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
body: JSON.stringify(values),
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setError(data?.message ?? 'Invalid email or password');
|
||||
const data = await res.json().catch(() => ({})) as { message?: string };
|
||||
form.setError('root', { message: data.message ?? 'Invalid email or password' });
|
||||
return;
|
||||
}
|
||||
await refresh();
|
||||
router.push(next);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Network error');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-4 bg-white p-6 rounded-xl border border-gray-200">
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
<span className="font-medium text-gray-700">Email</span>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
autoComplete="username"
|
||||
className="rounded border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-200"
|
||||
/>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
<span className="font-medium text-gray-700">Password</span>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
autoComplete="current-password"
|
||||
className="rounded border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-200"
|
||||
/>
|
||||
</label>
|
||||
{error && <p className="text-sm text-red-600" role="alert">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="rounded bg-blue-600 text-white py-2 font-medium hover:bg-blue-700 disabled:opacity-50"
|
||||
>
|
||||
{submitting ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField control={form.control} name="email" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl><Input type="email" placeholder="admin@chapter.com" autoComplete="username" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="password" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl><Input type="password" autoComplete="current-password" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
{form.formState.errors.root && (
|
||||
<p className="text-sm text-destructive">{form.formState.errors.root.message}</p>
|
||||
)}
|
||||
<Button type="submit" className="w-full" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Signing in…' : 'Sign in'}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
export default function ChapterLoginPage() {
|
||||
return (
|
||||
<div className="max-w-sm mx-auto mt-16">
|
||||
<h1 className="text-2xl font-semibold mb-2">Sign in</h1>
|
||||
<p className="text-sm text-gray-500 mb-6">TOWER administrative console</p>
|
||||
<Suspense fallback={<div className="bg-white p-6 rounded-xl border border-gray-200 h-64" />}>
|
||||
<PortalLoginShell
|
||||
title="Chapter Portal"
|
||||
subtitle="Sign in to manage your chapter's messages and groups."
|
||||
accentClass="bg-blue-600"
|
||||
footer={<Link href="/" className="hover:text-foreground transition-colors">← Back to portal selector</Link>}
|
||||
>
|
||||
<Suspense>
|
||||
<LoginForm />
|
||||
</Suspense>
|
||||
<p className="text-sm text-gray-500 mt-6 text-center">
|
||||
New here?{' '}
|
||||
<a href="/signup" className="text-blue-600 hover:underline">
|
||||
Create a community
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</PortalLoginShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,144 +2,122 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { PortalLoginShell } from '../_components/portal-login-shell';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../_components/ui/form';
|
||||
import { Input } from '../_components/ui/input';
|
||||
import { Button } from '../_components/ui/button';
|
||||
import Link from 'next/link';
|
||||
|
||||
const API_BASE = process.env['NEXT_PUBLIC_API_URL'] ?? 'http://localhost:3001';
|
||||
|
||||
type Step = 'phone' | 'code';
|
||||
const phoneSchema = z.object({ phone: z.string().min(8, 'Enter your WhatsApp number') });
|
||||
const otpSchema = z.object({ code: z.string().length(6, 'Enter the 6-digit code') });
|
||||
type PhoneValues = z.infer<typeof phoneSchema>;
|
||||
type OtpValues = z.infer<typeof otpSchema>;
|
||||
|
||||
export default function MemberLoginPage() {
|
||||
const router = useRouter();
|
||||
const [step, setStep] = useState<Step>('phone');
|
||||
const [step, setStep] = useState<'phone' | 'otp'>('phone');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [challengeId, setChallengeId] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function requestOtp() {
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const phoneForm = useForm<PhoneValues>({ resolver: zodResolver(phoneSchema), defaultValues: { phone: '' } });
|
||||
const otpForm = useForm<OtpValues>({ resolver: zodResolver(otpSchema), defaultValues: { code: '' } });
|
||||
|
||||
async function onPhone(values: PhoneValues) {
|
||||
const res = await fetch(`${API_BASE}/public/auth/member-login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ phone }),
|
||||
body: JSON.stringify({ phone: values.phone }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { challengeId?: string; message?: string };
|
||||
if (!res.ok) {
|
||||
setError(data.message ?? 'Failed to send code');
|
||||
return;
|
||||
}
|
||||
const data = await res.json().catch(() => ({})) as { challengeId?: string; message?: string };
|
||||
if (!res.ok) { phoneForm.setError('root', { message: data.message ?? 'Failed to send code' }); return; }
|
||||
setPhone(values.phone);
|
||||
setChallengeId(data.challengeId ?? '');
|
||||
setStep('code');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
setStep('otp');
|
||||
}
|
||||
|
||||
async function verifyOtp() {
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
async function onOtp(values: OtpValues) {
|
||||
const res = await fetch('/api/my/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ challengeId, phone, code }),
|
||||
body: JSON.stringify({ challengeId, phone, code: values.code }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as { message?: string };
|
||||
if (!res.ok) {
|
||||
setError(data.message ?? 'Verification failed');
|
||||
return;
|
||||
}
|
||||
const data = await res.json().catch(() => ({})) as { message?: string };
|
||||
if (!res.ok) { otpForm.setError('root', { message: data.message ?? 'Verification failed' }); return; }
|
||||
router.push('/my');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-sm bg-white rounded-2xl border border-gray-200 shadow-sm p-7 space-y-6">
|
||||
<div>
|
||||
<div className="w-10 h-10 rounded-xl bg-indigo-100 flex items-center justify-center text-xl mb-4">🏠</div>
|
||||
<h1 className="text-lg font-semibold text-gray-900">Sign in to your portal</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{step === 'phone'
|
||||
? 'Enter your WhatsApp number and we\'ll send you a code.'
|
||||
: `We sent a 6-digit code to ${phone} on WhatsApp.`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{step === 'phone' && (
|
||||
<div className="space-y-4">
|
||||
<input
|
||||
type="tel"
|
||||
value={phone}
|
||||
onChange={(e) => setPhone(e.target.value)}
|
||||
placeholder="+91 98765 43210"
|
||||
autoFocus
|
||||
className="w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
/>
|
||||
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||
<button
|
||||
type="button"
|
||||
onClick={requestOtp}
|
||||
disabled={busy || phone.replace(/\D/g, '').length < 8}
|
||||
className="w-full rounded-lg bg-indigo-600 text-white text-sm font-medium py-2.5 hover:bg-indigo-700 disabled:opacity-50 transition-colors"
|
||||
<PortalLoginShell
|
||||
title="Member Portal"
|
||||
subtitle={step === 'phone' ? 'Enter your WhatsApp number to receive a sign-in code.' : `We sent a 6-digit code to ${phone} on WhatsApp.`}
|
||||
accentClass="bg-emerald-600"
|
||||
footer={
|
||||
step === 'phone'
|
||||
? <><Link href="/onboard" className="hover:text-foreground transition-colors">First time? Use your invite link</Link> · <Link href="/" className="hover:text-foreground transition-colors">Portal selector</Link></>
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{busy ? 'Sending…' : 'Send code'}
|
||||
</button>
|
||||
<p className="text-xs text-center text-gray-400">
|
||||
First time?{' '}
|
||||
<a href="/onboard" className="text-indigo-600 hover:underline">
|
||||
Use your invite link
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
{step === 'phone' ? (
|
||||
<Form {...phoneForm}>
|
||||
<form onSubmit={phoneForm.handleSubmit(onPhone)} className="space-y-4">
|
||||
<FormField control={phoneForm.control} name="phone" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>WhatsApp number</FormLabel>
|
||||
<FormControl><Input type="tel" placeholder="+91 98765 43210" autoFocus {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
{phoneForm.formState.errors.root && (
|
||||
<p className="text-sm text-destructive">{phoneForm.formState.errors.root.message}</p>
|
||||
)}
|
||||
|
||||
{step === 'code' && (
|
||||
<div className="space-y-4">
|
||||
<input
|
||||
type="text"
|
||||
<Button type="submit" className="w-full" disabled={phoneForm.formState.isSubmitting}>
|
||||
{phoneForm.formState.isSubmitting ? 'Sending…' : 'Send code'}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
) : (
|
||||
<Form {...otpForm}>
|
||||
<form onSubmit={otpForm.handleSubmit(onOtp)} className="space-y-4">
|
||||
<FormField control={otpForm.control} name="code" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>6-digit code</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
inputMode="numeric"
|
||||
pattern="[0-9]{6}"
|
||||
maxLength={6}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
|
||||
placeholder="000000"
|
||||
className="text-center text-xl tracking-[0.5em] font-mono"
|
||||
autoFocus
|
||||
className="w-full rounded-lg border border-gray-300 px-3 py-2.5 text-center text-lg tracking-[0.3em] font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
{...field}
|
||||
onChange={(e) => field.onChange(e.target.value.replace(/\D/g, ''))}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={requestOtp}
|
||||
disabled={busy}
|
||||
className="text-xs text-indigo-600 hover:underline disabled:opacity-50 w-full text-center"
|
||||
>
|
||||
Didn't get it? Resend code
|
||||
</button>
|
||||
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setStep('phone'); setCode(''); setError(null); }}
|
||||
className="rounded-lg border border-gray-300 text-gray-600 text-sm font-medium px-4 py-2.5 hover:bg-gray-50"
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={verifyOtp}
|
||||
disabled={busy || code.length < 6}
|
||||
className="flex-1 rounded-lg bg-indigo-600 text-white text-sm font-medium py-2.5 hover:bg-indigo-700 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{busy ? 'Verifying…' : 'Sign in'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
{otpForm.formState.errors.root && (
|
||||
<p className="text-sm text-destructive">{otpForm.formState.errors.root.message}</p>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant="outline" onClick={() => { setStep('phone'); otpForm.reset(); }} className="flex-none">
|
||||
Back
|
||||
</Button>
|
||||
<Button type="submit" className="flex-1" disabled={otpForm.formState.isSubmitting}>
|
||||
{otpForm.formState.isSubmitting ? 'Verifying…' : 'Sign in'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="button" variant="ghost" size="sm" className="w-full text-muted-foreground" onClick={() => void onPhone({ phone })}>
|
||||
Resend code
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
)}
|
||||
</PortalLoginShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,71 +1,15 @@
|
||||
import Link from 'next/link';
|
||||
import { getMemberToken } from '../_lib/api';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
const NAV = [
|
||||
{ href: '/my', label: 'Dashboard' },
|
||||
{ href: '/my/ask', label: 'Ask AI' },
|
||||
{ href: '/my/knowledge', label: 'Knowledge' },
|
||||
{ href: '/my/digest', label: 'Digest' },
|
||||
{ href: '/my/events', label: 'Events' },
|
||||
{ href: '/my/seva', label: 'Seva & Points' },
|
||||
{ href: '/my/circles', label: 'Circles' },
|
||||
{ href: '/my/directory', label: 'Directory' },
|
||||
{ href: '/my/memories', label: 'Memories' },
|
||||
{ href: '/my/groups', label: 'My Groups' },
|
||||
{ href: '/my/settings', label: 'Settings' },
|
||||
];
|
||||
import { MemberNav } from './member-nav';
|
||||
|
||||
export default async function MemberLayout({ children }: { children: React.ReactNode }) {
|
||||
const token = await getMemberToken();
|
||||
if (!token) redirect('/member-login');
|
||||
|
||||
return (
|
||||
<div className="flex h-full -m-6 min-h-screen">
|
||||
{/* Left sidebar */}
|
||||
<nav className="w-[220px] shrink-0 bg-white border-r border-gray-200 flex flex-col p-4">
|
||||
<span className="font-bold text-base mb-6 px-2">TOWER</span>
|
||||
<div className="flex flex-col gap-1 flex-1">
|
||||
{NAV.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className="rounded-md px-3 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors"
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<div className="border-t border-gray-200 pt-3 mt-3">
|
||||
<p className="px-3 text-xs text-gray-400 uppercase tracking-wide">Member portal</p>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Main content */}
|
||||
<main className="flex-1 overflow-auto p-6 bg-gray-50">
|
||||
{children}
|
||||
</main>
|
||||
|
||||
{/* Right activity rail */}
|
||||
<aside className="w-[280px] shrink-0 bg-white border-l border-gray-200 p-4 hidden lg:block">
|
||||
<p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-4">Quick actions</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Link
|
||||
href="/my/settings"
|
||||
className="text-sm text-gray-600 hover:text-gray-900 px-3 py-2 rounded-md hover:bg-gray-50"
|
||||
>
|
||||
Privacy settings
|
||||
</Link>
|
||||
<form method="POST" action="/api/my/logout">
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full text-left text-sm text-red-500 hover:text-red-700 px-3 py-2 rounded-md hover:bg-red-50"
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</aside>
|
||||
<div className="flex h-screen overflow-hidden -m-6">
|
||||
<MemberNav />
|
||||
<main className="flex-1 overflow-auto bg-muted/30 p-6">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { cn } from '../_lib/utils';
|
||||
import { Separator } from '../_components/ui/separator';
|
||||
import { Button } from '../_components/ui/button';
|
||||
import { LayoutDashboard, Settings, Users, LogOut } from 'lucide-react';
|
||||
|
||||
const NAV = [
|
||||
{ href: '/my', label: 'Dashboard', icon: <LayoutDashboard /> },
|
||||
{ href: '/my/groups', label: 'My Groups', icon: <Users /> },
|
||||
{ href: '/my/settings', label: 'Settings', icon: <Settings /> },
|
||||
];
|
||||
|
||||
export function MemberNav() {
|
||||
const pathname = usePathname();
|
||||
|
||||
async function logout() {
|
||||
await fetch('/api/my/logout', { method: 'POST' });
|
||||
window.location.href = '/member-login';
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="w-56 shrink-0 flex flex-col h-full border-r bg-sidebar">
|
||||
<div className="px-4 py-5 flex items-center gap-2">
|
||||
<span className="font-bold text-base text-emerald-600">TOWER</span>
|
||||
<Separator orientation="vertical" className="h-4" />
|
||||
<span className="text-xs text-muted-foreground font-medium">Member</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex-1 overflow-y-auto py-3 px-2 space-y-0.5">
|
||||
{NAV.map((item) => {
|
||||
const active = item.href === '/my' ? pathname === '/my' : pathname.startsWith(item.href);
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={cn(
|
||||
'flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors',
|
||||
active ? 'bg-accent text-accent-foreground font-medium' : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<span className="size-4 shrink-0">{item.icon}</span>
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="p-3">
|
||||
<Button variant="ghost" size="sm" className="w-full justify-start text-muted-foreground" onClick={() => void logout()}>
|
||||
<LogOut className="size-4" />
|
||||
Sign out
|
||||
</Button>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,45 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useOrgAdmin } from '../_lib/org-admin-context';
|
||||
import { PortalNav } from '../_components/portal-nav';
|
||||
import { LayoutDashboard, Building2, Shield } from 'lucide-react';
|
||||
|
||||
const NAV = [
|
||||
{ href: '/org', label: 'Dashboard', icon: <LayoutDashboard /> },
|
||||
{ href: '/org/tenants', label: 'Chapters', icon: <Building2 /> },
|
||||
{ href: '/org/rules', label: 'Org Rules', icon: <Shield /> },
|
||||
];
|
||||
|
||||
export default function OrgLayout({ children }: { children: React.ReactNode }) {
|
||||
return <>{children}</>;
|
||||
const { orgAdmin, loading, logout } = useOrgAdmin();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && !orgAdmin) router.replace('/org/login');
|
||||
}, [orgAdmin, loading, router]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex h-screen -m-6">
|
||||
<div className="w-56 shrink-0 border-r bg-sidebar animate-pulse" />
|
||||
<div className="flex-1" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!orgAdmin) return null;
|
||||
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden -m-6">
|
||||
<PortalNav
|
||||
portalName="Org"
|
||||
navItems={NAV}
|
||||
accentClass="text-violet-600"
|
||||
user={{ email: orgAdmin.email, name: orgAdmin.name ?? undefined, role: orgAdmin.role }}
|
||||
onLogout={() => { void logout(); router.replace('/org/login'); }}
|
||||
/>
|
||||
<main className="flex-1 overflow-auto bg-muted/30 p-6">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,67 +1,68 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { useOrgAdmin } from '../../_lib/org-admin-context';
|
||||
import { PortalLoginShell } from '../../_components/portal-login-shell';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '../../_components/ui/form';
|
||||
import { Input } from '../../_components/ui/input';
|
||||
import { Button } from '../../_components/ui/button';
|
||||
import Link from 'next/link';
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().email('Enter a valid email'),
|
||||
password: z.string().min(1, 'Password is required'),
|
||||
});
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
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);
|
||||
const form = useForm<FormValues>({ resolver: zodResolver(schema), defaultValues: { email: '', password: '' } });
|
||||
|
||||
async function onSubmit(values: FormValues) {
|
||||
try {
|
||||
await login(email, password);
|
||||
await login(values.email, values.password);
|
||||
router.replace('/org');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Login failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
form.setError('root', { message: err instanceof Error ? err.message : 'Login failed' });
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
<PortalLoginShell
|
||||
title="Organisation Portal"
|
||||
subtitle="Manage your chapters, admins and org-wide rules."
|
||||
accentClass="bg-violet-600"
|
||||
footer={<Link href="/" className="hover:text-foreground transition-colors">← Back to portal selector</Link>}
|
||||
>
|
||||
{loading ? 'Signing in...' : 'Sign in'}
|
||||
</button>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField control={form.control} name="email" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl><Input type="email" placeholder="admin@org.com" autoComplete="username" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="password" render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl><Input type="password" autoComplete="current-password" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)} />
|
||||
{form.formState.errors.root && (
|
||||
<p className="text-sm text-destructive">{form.formState.errors.root.message}</p>
|
||||
)}
|
||||
<Button type="submit" className="w-full" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Signing in…' : 'Sign in'}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</PortalLoginShell>
|
||||
);
|
||||
}
|
||||
|
||||
+36
-23
@@ -1,62 +1,75 @@
|
||||
import Link from 'next/link';
|
||||
import { ArrowRight } from 'lucide-react';
|
||||
|
||||
const PORTALS = [
|
||||
{
|
||||
href: '/org/login',
|
||||
title: 'Organisation Portal',
|
||||
description: 'For org-level admins managing multiple chapters and org-wide rules.',
|
||||
description: 'Manage multiple chapters, org-wide routing rules and admin access.',
|
||||
badge: 'Org Admin',
|
||||
color: 'hover:border-violet-400',
|
||||
badgeColor: 'bg-violet-100 text-violet-700',
|
||||
accent: 'border-l-4 border-l-violet-500',
|
||||
badgeClass: 'bg-violet-100 text-violet-700',
|
||||
hoverClass: 'hover:border-violet-300',
|
||||
},
|
||||
{
|
||||
href: '/login',
|
||||
title: 'Chapter Portal',
|
||||
description: 'For chapter admins approving messages, managing groups and routing rules.',
|
||||
description: 'Approve messages, manage groups, configure routing rules and AI drafts.',
|
||||
badge: 'Chapter Admin',
|
||||
color: 'hover:border-blue-400',
|
||||
badgeColor: 'bg-blue-100 text-blue-700',
|
||||
accent: 'border-l-4 border-l-blue-500',
|
||||
badgeClass: 'bg-blue-100 text-blue-700',
|
||||
hoverClass: 'hover:border-blue-300',
|
||||
},
|
||||
{
|
||||
href: '/member-login',
|
||||
title: 'Member Portal',
|
||||
description: 'For community members to view digests, manage privacy and explore the directory.',
|
||||
description: 'View digests, manage your privacy settings and explore your community.',
|
||||
badge: 'Member',
|
||||
color: 'hover:border-emerald-400',
|
||||
badgeColor: 'bg-emerald-100 text-emerald-700',
|
||||
accent: 'border-l-4 border-l-emerald-500',
|
||||
badgeClass: 'bg-emerald-100 text-emerald-700',
|
||||
hoverClass: 'hover:border-emerald-300',
|
||||
},
|
||||
{
|
||||
href: '/admin/login',
|
||||
title: 'Super Admin',
|
||||
description: 'Platform-wide administration — orgs, chapters, bots and system settings.',
|
||||
badge: 'Platform',
|
||||
accent: 'border-l-4 border-l-slate-500',
|
||||
badgeClass: 'bg-slate-100 text-slate-700',
|
||||
hoverClass: 'hover:border-slate-300',
|
||||
},
|
||||
];
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 p-6">
|
||||
<div className="w-full max-w-lg">
|
||||
<div className="mb-10 text-center">
|
||||
<h1 className="text-3xl font-bold tracking-tight text-gray-900">TOWER</h1>
|
||||
<p className="text-gray-500 mt-2 text-sm">Community Knowledge Infrastructure Platform</p>
|
||||
<div className="min-h-screen flex items-center justify-center bg-muted/30 p-6">
|
||||
<div className="w-full max-w-md space-y-8">
|
||||
<div className="text-center space-y-2">
|
||||
<h1 className="text-3xl font-bold tracking-tight">TOWER</h1>
|
||||
<p className="text-muted-foreground text-sm">Community Knowledge Infrastructure Platform</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="space-y-3">
|
||||
{PORTALS.map((p) => (
|
||||
<Link
|
||||
key={p.href}
|
||||
href={p.href}
|
||||
className={`bg-white rounded-2xl border border-gray-200 p-6 flex items-start gap-5 transition-colors ${p.color}`}
|
||||
className={`group flex items-start gap-4 bg-card rounded-xl border p-5 transition-colors ${p.accent} ${p.hoverClass}`}
|
||||
>
|
||||
<div className="flex-1">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h2 className="font-semibold text-gray-900">{p.title}</h2>
|
||||
<span className={`text-xs font-medium px-2 py-0.5 rounded-full ${p.badgeColor}`}>{p.badge}</span>
|
||||
<span className="font-semibold text-sm">{p.title}</span>
|
||||
<span className={`text-xs font-medium px-2 py-0.5 rounded-full ${p.badgeClass}`}>{p.badge}</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500">{p.description}</p>
|
||||
<p className="text-xs text-muted-foreground leading-relaxed">{p.description}</p>
|
||||
</div>
|
||||
<span className="text-gray-300 text-xl mt-0.5">›</span>
|
||||
<ArrowRight className="size-4 text-muted-foreground shrink-0 mt-0.5 transition-transform group-hover:translate-x-0.5" />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="text-center text-xs text-gray-400 mt-8">
|
||||
Administrators are provisioned by your organisation — contact your org admin if you need access.
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
Access is provisioned by your organisation admin
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+20
-1
@@ -9,11 +9,30 @@
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.4.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.17",
|
||||
"@radix-ui/react-avatar": "^1.2.0",
|
||||
"@radix-ui/react-dialog": "^1.1.17",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.18",
|
||||
"@radix-ui/react-label": "^2.1.10",
|
||||
"@radix-ui/react-select": "^2.3.1",
|
||||
"@radix-ui/react-separator": "^1.1.10",
|
||||
"@radix-ui/react-slot": "^1.3.0",
|
||||
"@radix-ui/react-toast": "^1.2.17",
|
||||
"@radix-ui/react-tooltip": "^1.2.10",
|
||||
"@tanstack/react-query": "^5.101.0",
|
||||
"@tower/types": "workspace:*",
|
||||
"@tower/ui": "workspace:*",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.21.0",
|
||||
"next": "^16.0.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
"react-dom": "^19.0.0",
|
||||
"react-hook-form": "^7.80.0",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"zod": "^3.23.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.0.0",
|
||||
|
||||
Generated
+1080
-6
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user