@company-manager/docs
Apps

Main Web Application

Comprehensive guide to the primary Company Manager web application built with Next.js, React, and TypeScript.

Main Web Application

The main web application (apps/app) is the primary interface for Company Manager, built with modern web technologies and designed for multi-tenant business management.

🏗️ Architecture

Technology Stack

  • Framework: Next.js 15+ with App Router
  • Language: TypeScript
  • UI Library: React 18+
  • Styling: Tailwind CSS with ShadCN/UI components
  • State Management: Zustand + React Query
  • API Layer: TRPC for type-safe APIs
  • Database: Prisma ORM with PostgreSQL
  • Authentication: Custom auth system with JWT
  • Form Handling: React Hook Form with Zod validation

Project Structure

apps/app/
├── src/
│   ├── app/                 # Next.js App Router pages
│   ├── components/          # React components
│   │   ├── ui/             # Base UI components
│   │   ├── forms/          # Form components
│   │   ├── layout/         # Layout components
│   │   └── features/       # Feature-specific components
│   ├── lib/                # Utility libraries
│   ├── hooks/              # Custom React hooks
│   ├── stores/             # Zustand stores
│   ├── types/              # TypeScript type definitions
│   ├── utils/              # Utility functions
│   └── styles/             # Global styles
├── public/                 # Static assets
├── prisma/                 # Database schema (symlinked)
└── package.json

🚀 Getting Started

Prerequisites

  • Node.js 18.17.0+
  • Bun package manager
  • PostgreSQL database
  • Redis server (for caching and sessions)

Development Setup

# From project root
cd apps/app

# Install dependencies
bun install

# Set up environment variables
cp .env.example .env.local
# Edit .env.local with your configuration

# Run database migrations
bun run db:migrate

# Start development server
bun run dev

Environment Configuration

Create .env.local with the following variables:

# Database
DATABASE_URL="postgresql://user:password@localhost:5432/company_manager"

# Authentication
NEXTAUTH_SECRET="your-secret-key"
NEXTAUTH_URL="http://localhost:3000"

# External APIs
STRIPE_SECRET_KEY="sk_test_..."
WEBHOOK_SECRET="whsec_..."

# Redis
REDIS_URL="redis://localhost:6379"

💼 Core Features

Multi-Tenant Architecture

The application supports multiple tenants and sites:

  • Tenant: Top-level organization
  • Site: Sub-organization within a tenant
  • User: Can belong to multiple tenants/sites with different roles

Authentication & Authorization

  • JWT-based authentication
  • Role-based access control (RBAC)
  • Permission-based authorization
  • Multi-factor authentication support

Business Entities

  • Users: System users with roles and permissions
  • Clients: Customer management
  • Orders: Order processing and tracking
  • Products: Inventory and catalog management
  • Vendors: Supplier management
  • Invoices: Billing and payment tracking

🎨 UI Components

Design System

The application uses a consistent design system based on:

  • ShadCN/UI: Base component library
  • Tailwind CSS: Utility-first CSS framework
  • Radix UI: Accessible component primitives
  • Lucide Icons: Icon library

Key Components

  • EntityManager: Generic CRUD interface for business entities
  • DataTable: Advanced table with sorting, filtering, and pagination
  • FormBuilder: Dynamic form generation
  • Dashboard: Analytics and metrics visualization
  • NotificationSystem: Real-time notifications

Component Structure

// Example component structure
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { useEntityManager } from "@/hooks/useEntityManager"

export function ClientManager() {
  const { data, loading, error } = useEntityManager('clients')

  return (
    <Card>
      <CardHeader>
        <CardTitle>Client Management</CardTitle>
      </CardHeader>
      <CardContent>
        {/* Component content */}
      </CardContent>
    </Card>
  )
}

🔄 State Management

Zustand Stores

The application uses Zustand for global state management:

  • AuthStore: Authentication state
  • TenantStore: Multi-tenant context
  • UIStore: UI state (modals, notifications)
  • PreferencesStore: User preferences

React Query Integration

Data fetching and caching with React Query:

  • Server state management
  • Optimistic updates
  • Background refetching
  • Error handling

Example Store

import { create } from "zustand";
import { persist } from "zustand/middleware";

interface AuthState {
  user: User | null;
  tenant: Tenant | null;
  isAuthenticated: boolean;
  login: (user: User, tenant: Tenant) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      tenant: null,
      isAuthenticated: false,
      login: (user, tenant) => set({ user, tenant, isAuthenticated: true }),
      logout: () => set({ user: null, tenant: null, isAuthenticated: false }),
    }),
    {
      name: "auth-storage",
    }
  )
);

🔗 API Integration

TRPC Router Structure

The application uses TRPC for type-safe API communication:

// Example router
export const clientRouter = createTRPCRouter({
  getAll: protectedProcedure
    .input(
      z.object({
        tenantId: z.string(),
        siteId: z.string().optional(),
      })
    )
    .query(async ({ input, ctx }) => {
      return ctx.db.client.findMany({
        where: {
          tenantId: input.tenantId,
          siteId: input.siteId,
        },
      });
    }),

  create: protectedProcedure
    .input(createClientSchema)
    .mutation(async ({ input, ctx }) => {
      return ctx.db.client.create({
        data: input,
      });
    }),
});

Data Fetching Patterns

// Component data fetching
export function ClientList() {
  const { data: clients, isLoading } = api.client.getAll.useQuery({
    tenantId: currentTenant.id,
    siteId: currentSite?.id,
  })

  const createClient = api.client.create.useMutation({
    onSuccess: () => {
      // Refetch clients list
      utils.client.getAll.invalidate()
    },
  })

  return (
    <div>
      {isLoading ? (
        <LoadingSpinner />
      ) : (
        <ClientTable clients={clients} />
      )}
    </div>
  )
}

🧪 Testing

Testing Strategy

  • Unit Tests: Component and utility testing with Vitest
  • Integration Tests: API and database testing
  • E2E Tests: End-to-end user flows with Playwright
  • Visual Tests: Component visual regression testing

Test Structure

// Example component test
import { render, screen } from '@testing-library/react'
import { ClientManager } from './ClientManager'

describe('ClientManager', () => {
  it('renders client list', async () => {
    render(<ClientManager />)

    expect(screen.getByText('Client Management')).toBeInTheDocument()
    expect(await screen.findByText('Loading...')).toBeInTheDocument()
  })
})

🚀 Performance

Optimization Strategies

  • Code Splitting: Dynamic imports for route-based splitting
  • Image Optimization: Next.js Image component with optimization
  • Caching: Redis-based caching for frequently accessed data
  • Bundle Analysis: Regular bundle size monitoring
  • Lazy Loading: Component and data lazy loading

Performance Monitoring

  • Core Web Vitals: LCP, FID, CLS tracking
  • Bundle Analysis: Webpack bundle analyzer
  • Runtime Performance: React DevTools Profiler
  • API Performance: TRPC performance monitoring

🔒 Security

Security Measures

  • Authentication: JWT with refresh tokens
  • Authorization: Role-based access control
  • Data Validation: Zod schema validation
  • CSRF Protection: Built-in Next.js CSRF protection
  • XSS Prevention: Sanitized user inputs
  • SQL Injection Prevention: Prisma ORM protection

Security Best Practices

  • Environment variable management
  • Secure cookie configuration
  • API rate limiting
  • Input sanitization
  • Regular security audits

📱 Responsive Design

Breakpoint Strategy

  • Mobile: 640px and below
  • Tablet: 641px - 1024px
  • Desktop: 1025px and above

Mobile-First Approach

All components are designed mobile-first with progressive enhancement for larger screens.

🔧 Configuration

Application Configuration

// config/app.ts
export const appConfig = {
  name: "Company Manager",
  version: "1.0.0",
  api: {
    baseUrl: process.env.NEXT_PUBLIC_API_URL,
    timeout: 30000,
  },
  features: {
    multiTenant: true,
    payments: true,
    analytics: true,
  },
};

Feature Flags

// config/features.ts
export const featureFlags = {
  newDashboard: process.env.NEXT_PUBLIC_FEATURE_NEW_DASHBOARD === "true",
  advancedFiltering: true,
  realTimeNotifications: true,
};

🚀 Deployment

Build Process

# Production build
bun run build

# Start production server
bun run start

# Export static files (if needed)
bun run export

Environment-Specific Builds

  • Development: Full debugging, hot reload
  • Staging: Production-like with debugging
  • Production: Optimized, minified build

📊 Analytics & Monitoring

Application Monitoring

  • Error Tracking: Sentry integration
  • Performance Monitoring: Real User Monitoring (RUM)
  • Analytics: Custom event tracking
  • Logging: Structured logging with Winston

Business Metrics

  • User engagement tracking
  • Feature usage analytics
  • Performance metrics
  • Conversion tracking

🔄 Continuous Integration

CI/CD Pipeline

# Example GitHub Actions workflow
name: Build and Deploy
on:
  push:
    branches: [main]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
      - run: bun install
      - run: bun run build
      - run: bun run test

🤝 Contributing

Development Workflow

  1. Create feature branch
  2. Implement changes with tests
  3. Run quality checks
  4. Submit pull request
  5. Code review process
  6. Merge and deploy

Code Quality

  • Linting: ESLint with custom rules
  • Formatting: Prettier with consistent config
  • Type Checking: Strict TypeScript
  • Testing: Minimum 80% coverage

📚 Additional Resources


For more specific implementation details, see the individual component and feature documentation.