# Portal Web Architecture Documentation

## Overview

Portal Web is a modern Next.js frontend application that provides a comprehensive user interface for the portal system. It features role-based access control, dynamic theming, rich text editing, and seamless API integration with the backend.

## Technology Stack

- **Framework**: Next.js 16.2.3 with App Router
- **Language**: TypeScript 5 with strict mode
- **UI Library**: React 19.2.4
- **Styling**: Tailwind CSS 4 with PostCSS
- **Authorization**: CASL 6.8.0 (@casl/ability, @casl/react)
- **Rich Text**: Tiptap editor with extensions
- **Icons**: @iconify/react
- **Notifications**: react-toastify, sweetalert2
- **State Management**: React Context (AuthContext, SettingsContext)

## Core Architecture

### Project Structure
```
portal.web/
├── app/
│   ├── layout.tsx                 # Root layout with providers
│   ├── page.tsx                   # Redirects to /dashboard
│   ├── globals.css               # Global styles & CSS variables
│   ├── (dashboard)/              # Protected dashboard routes
│   │   ├── layout.tsx           # Dashboard layout guard
│   │   ├── dashboard/
│   │   ├── inventory/
│   │   ├── security/
│   │   ├── settings/
│   │   ├── Sidebar.tsx          # Collapsible navigation
│   │   ├── Topbar.tsx           # Header with user menu
│   │   ├── nav-config.ts        # Navigation structure
│   │   └── _components/         # Dashboard-specific components
│   ├── login/
│   ├── register/
│   ├── recover-password/
│   └── forbidden/
├── components/
│   ├── Button.tsx               # Variants: primary, secondary, danger, ghost
│   ├── Input.tsx                # Form inputs with addons
│   ├── Modal.tsx                # Dialog with size variants
│   ├── Table.tsx                # Generic table with sorting
│   ├── Select.tsx               # Multi-select dropdown
│   ├── Spinner.tsx              # Loading indicator
│   ├── RoleGuard.tsx            # Permission-gated component
│   ├── TiptapEditor.tsx         # Rich text editor
│   └── index.ts                 # Component exports
├── context/
│   ├── AuthContext.tsx          # Authentication & authorization
│   └── SettingsContext.tsx      # UI preferences & theming
├── modules/
│   ├── inventory/               # Stock management module
│   ├── security/                # User/role/permission management
│   └── settings/                # Email templates & configuration
├── services/
│   ├── api-client.ts            # API integration layer
│   └── [module]-service.ts      # Module-specific API calls
├── types/
│   └── index.ts                 # Global type definitions
└── utils/
    ├── ability.ts               # CASL ability builder
    └── [utility].ts             # Helper functions
```

## State Management

### AuthContext - Authentication & Authorization

**Core State**:
```typescript
interface AuthState {
  user: User | null;
  accessToken: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  activeRoleId: number | null;
}
```

**Key Methods**:
- `login(email, password)` - Authenticate user
- `logout()` - Clear session and redirect
- `switchRole(roleId)` - Change active role
- `refreshSession()` - Restore session on app mount

**Session Management**:
- Access token stored in React state (memory only)
- Refresh token in httpOnly cookie (backend-managed)
- Automatic token refresh on 401 responses
- Session restoration on app initialization

### SettingsContext - UI Preferences

**Theme Configuration**:
```typescript
interface SettingsState {
  themeMode: 'light' | 'dark';
  contrast: 'default' | 'high';
  layout: 'full' | 'compact';
  navLayout: 'left' | 'top' | 'mini';
  navColor: 'normal' | 'dark';
  presetColor: keyof { teal, blue, purple, ... };
  fontFamily: 'Inter' | 'Public Sans' | 'DM Sans' | 'Nunito Sans';
  fontSize: number;
}
```

**Persistence**: Cookie-based storage
**Application**: CSS variables on `<html>` element

## API Integration

### API Client ([services/api-client.ts](services/api-client.ts))

**Features**:
- Fetch wrapper with automatic Bearer token attachment
- 401 handling with token refresh and retry logic
- Concurrency control for multiple simultaneous 401s
- httpOnly cookie support (`credentials: "include"`)

**Configuration Bridge**:
```typescript
// AuthContext configures the client
configureApiClient({
  getAccessToken: () => accessTokenRef.current,
  onTokenRefreshed: (newToken) => setAccessToken(newToken),
  onLogout: () => performLogout(),
});
```

**Request Methods**:
```typescript
export async function apiGet<T>(path: string): Promise<T>
export async function apiPost<T>(path: string, data?: any): Promise<T>
export async function apiPatch<T>(path: string, data?: any): Promise<T>
export async function apiDelete<T>(path: string): Promise<T>
```

### Module Services

**Pattern**: Services encapsulate API calls and data transformation
```typescript
// modules/inventory/services/stock.service.ts
export async function getStockLevels(filters: StockLevelsFilters) {
  const params = new URLSearchParams();
  Object.entries(filters).forEach(([key, value]) => {
    if (value !== undefined) params.set(key, String(value));
  });
  
  return apiGet<StockItem[]>(`/inventory/stock-levels?${params}`);
}
```

## Authorization System (CASL)

### Permission Model

**Permission Structure**:
```typescript
interface Permission {
  action: string;        // "READ" | "CREATE" | "UPDATE" | "DELETE" | "MANAGE"
  resource: string;      // "Inventory", "Users.List", "Inventory.StockLevels"
  scope?: string;        // "module" | "page" | "component"
  effect: string;        // "ALLOW" | "DENY"
  conditions?: Record<string, unknown>; // ABAC conditions
}
```

### Ability Building ([utils/ability.ts](utils/ability.ts))

Converts permission array to CASL rules:
```typescript
export function buildAbility(
  permissions: Permission[],
  user?: { id: string; [key: string]: unknown },
): AppAbility {
  const rules = [
    // DENY rules first (override ALLOW)
    ...denyPerms.map(p => ({
      inverted: true,
      action: p.action,
      subject: p.resource,
      conditions: interpolateConditions(p.conditions, user),
    })),
    // ALLOW rules
    ...allowPerms.map(p => ({
      action: p.action,
      subject: p.resource,
      conditions: interpolateConditions(p.conditions, user),
    })),
  ];
  
  return createMongoAbility(rules);
}
```

### Component-Level Guards

**RoleGuard Component**:
```typescript
// Gated component access
<RoleGuard action="READ" resource="Inventory">
  <InventoryPage />
</RoleGuard>
```

**Hook-Based Checks**:
```typescript
export function useCan(action: string, resource: string): boolean {
  const ability = useAbility();
  return ability.can(action, resource);
}

// Usage
const canEdit = useCan('UPDATE', 'Users');
```

### Navigation Filtering

Sidebar dynamically filters menu items based on permissions:
```typescript
const filteredSections = NAV_SECTIONS
  .filter(section => ability.can('READ', section.resource))
  .map(section => ({
    items: section.items.filter(item => ability.can('READ', item.resource))
  }));
```

## Component Architecture

### Shared UI Components

**Button Component**:
```typescript
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
  size?: 'sm' | 'md' | 'lg';
  isLoading?: boolean;
}

const variantClasses = {
  primary: 'bg-[var(--primary-color)] text-white hover:opacity-90',
  secondary: 'bg-[var(--bg-paper)] border border-[var(--border-default)]',
  danger: 'bg-red-600 text-white hover:bg-red-700',
};
```

**Table Component**:
- Generic table with sorting and pagination
- Skeleton loading states
- Customizable columns and actions

**TiptapEditor**:
- Rich text editing with toolbar
- Extensions: bold, italic, lists, links, images
- Content serialization

### Layout Components

**Dashboard Layout**:
- Sidebar with collapsible navigation
- Topbar with user menu and breadcrumbs
- Main content area with responsive padding
- Authentication guard (redirects to login if not authenticated)

## Module Organization

### Security Module (`modules/security/`)

**Features**:
- User management (CRUD operations)
- Role management and assignment
- Permission management
- User-role relationships

**Key Types**:
```typescript
export interface User {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  status: 'ACTIVE' | 'PENDING' | 'INACTIVE' | 'SUSPENDED';
  userRoles: UserRole[];
}

export interface Role {
  id: number;
  name: string;
  color?: string;
  icon?: string;
}

export interface Permission {
  id: string;
  action: string;
  resource: string;
  scope?: string;
  effect: string;
  conditions?: Record<string, unknown>;
}
```

### Inventory Module (`modules/inventory/`)

**Features**:
- Stock level management
- Stock adjustments
- Product catalog

**Key Types**:
```typescript
export interface StockItem {
  id: string;
  sku: string;
  name: string;
  quantity: number;
  warehouseId: string;
  ownerId: string;  // For ABAC filtering
}

export interface StockLevelsFilters {
  warehouseId?: string;
  ownerId?: string;
  category?: string;
  search?: string;
}
```

### Settings Module (`modules/settings/`)

**Features**:
- Email template management
- Application configuration
- System settings

## Routing and Navigation

### App Router Structure

**Route Groups**:
- `(dashboard)` - Protected routes sharing layout
- Public routes: `login`, `register`, `recover-password`
- Error routes: `forbidden`

**Navigation Configuration** ([app/(dashboard)/nav-config.ts](app/(dashboard)/nav-config.ts)):
```typescript
export const NAV_SECTIONS = [
  {
    title: 'Dashboard',
    items: [
      {
        title: 'Overview',
        path: '/dashboard',
        resource: 'Dashboard',
      },
    ],
  },
  {
    title: 'Inventory',
    resource: 'Inventory',
    items: [
      {
        title: 'Stock Levels',
        path: '/dashboard/inventory/stock-levels',
        resource: 'Inventory.StockLevels',
      },
    ],
  },
];
```

## Styling and Theming

### CSS Architecture

**Global Variables** ([app/globals.css](app/globals.css)):
```css
:root {
  --font-inter: 'Inter', system-ui, sans-serif;
  --font-main: 'Public Sans', sans-serif;
  --font-size-base: 16px;
  --bg-default: #f9fafb;
  --bg-paper: #ffffff;
  --text-primary: #212B36;
  --text-secondary: #637381;
  --border-default: #e9ecef;
  --primary-color: #00BFA5;
}

.dark {
  --bg-default: #161C24;
  --bg-paper: #212B36;
  --text-primary: #ffffff;
  --text-secondary: #919EAB;
}
```

**Dynamic Theming**:
- SettingsContext updates CSS variables
- Components use `var(--variable-name)` for theming
- Preset color system with multiple themes

### Responsive Design

**Breakpoint System**:
- Mobile-first approach
- Grid: `grid-cols-1 sm:grid-cols-2 lg:grid-cols-3`
- Flexbox: `flex flex-col md:flex-row`
- Hidden: `hidden sm:flex`

**Layout Patterns**:
- Sidebar collapses on mobile
- Tables stack on small screens
- Modal dialogs adapt to screen size

## Data Flow and State Updates

### Authentication Flow

1. **Login**: User enters credentials → `POST /auth/login` → Store tokens → Build ability → Redirect to dashboard
2. **Session Restore**: On mount → `POST /auth/refresh` → Restore user and permissions → Set loading to false
3. **Token Refresh**: On 401 → Automatic refresh → Retry original request
4. **Logout**: Clear state → `POST /auth/logout` → Redirect to login

### Permission-Aware Data Fetching

1. **Frontend Filtering**: Components check `ability.can()` before rendering
2. **API Enforcement**: Backend enforces ABAC conditions at database level
3. **Navigation**: Sidebar filters menu items by resource permissions
4. **UI Gating**: Buttons and actions conditionally rendered based on permissions

### Error Handling

**API Errors**:
```typescript
try {
  const data = await apiGet('/resource');
} catch (err) {
  if (err.statusCode === 401) {
    // Handled automatically by api-client
  } else if (err.statusCode === 403) {
    toast.error('Access denied');
  } else {
    toast.error(err.message);
  }
}
```

**Toast Notifications**:
- Success messages for operations
- Error messages for failures
- Loading states for async operations

## Development Patterns

### Custom Hooks

**Data Fetching**:
```typescript
export function useStockLevels(filters = {}) {
  const [items, setItems] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  
  const fetch = useCallback(async () => {
    const data = await getStockLevels(filters);
    setItems(data);
  }, [filters]);
  
  useEffect(() => { void fetch(); }, [fetch]);
  
  return { items, isLoading, refetch: fetch };
}
```

**Permission Checks**:
```typescript
export function useCan(action: string, resource: string): boolean {
  const ability = useAbility();
  return ability.can(action, resource);
}
```

### Type Safety

**Global Types** ([types/index.ts](types/index.ts)):
```typescript
export interface User {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  userRoles: UserRole[];
}

export interface AuthContextValue extends AuthState {
  login: (email: string, password: string) => Promise<void>;
  logout: (email: string, password: string) => Promise<void>;
  switchRole: (roleId: number | null) => Promise<void>;
}
```

### Component Composition

**Higher-Order Components**:
```typescript
// Permission wrapper
export function withPermission<P extends object>(
  WrappedComponent: React.ComponentType<P>,
  action: string,
  resource: string,
) {
  return function PermissionWrapper(props: P) {
    const canAccess = useCan(action, resource);
    
    if (!canAccess) {
      return <ForbiddenPage />;
    }
    
    return <WrappedComponent {...props} />;
  };
}
```

## Configuration and Environment

### Environment Variables

```bash
# API Configuration
NEXT_PUBLIC_API_URL=http://localhost:3000/api

# Development
NODE_ENV=development
```

### Build Configuration ([next.config.ts](next.config.ts))

```typescript
const nextConfig = {
  experimental: {
    appDir: true,
  },
  env: {
    API_URL: process.env.NEXT_PUBLIC_API_URL,
  },
};
```

## Key Architectural Decisions

| Aspect | Decision | Rationale |
|--------|----------|-----------|
| **State Management** | React Context | Simpler than Redux, sufficient for auth + settings |
| **Token Storage** | Memory + httpOnly cookie | Security: no XSS risk for refresh token |
| **API Client** | Singleton with callbacks | Avoids circular imports, manages refresh queue |
| **Authorization** | CASL with ABAC | Granular permissions, supports complex rules |
| **Navigation** | Static config + runtime filtering | SEO-friendly, permission-aware |
| **Styling** | Tailwind + CSS variables | Dynamic theming, performance, developer experience |
| **Modules** | Feature-based organization | Scalability, clear boundaries |
| **Routing** | Next.js App Router | Modern, nested layouts, server components ready |

This architecture provides a robust, scalable frontend foundation with enterprise-grade security, theming, and user experience features.</content>
<parameter name="filePath">/Users/david/Documents/Projects/repo/app.portal/architecture-portal-api.md