---
title: "Code Structure"
description: "Code Structure documentation for Ring Platform"
locale: "ru"
---
# Структура кода

Понимание кодовой базы Ring Platform **v1.6.0**.

## 📁 Высокоуровневая архитектура

```
ring/
├── app/                    # Next.js 16 App Router
├── components/             # UI, editor, navigation
├── features/               # news, store, auth, …
├── lib/                    # locale-config, payments/conductor, database
├── locales/                # next-intl JSON (en, uk, ru)
├── data/                   # schema.sql + migrations/
└── scripts/                # Community OSS scripts
```

**Не в публичном OSS:** `k8s/`, `cli/`, `propagation/` (gitignored).

### Ключевые модули v1.6.0

| Область | Путь |
|---------|------|
| PaymentConductor | `lib/payments/conductor/` |
| News Kingdom | `features/news/services/`, `lib/news/` |
| Locale SSOT | `lib/locale-config.ts` |

## 🏗️ App Directory Structure

### App Router (Next.js 16)

```
app/
├── (auth)/            # Route groups for auth pages
│   ├── login/
│   └── register/
├── (dashboard)/       # Protected dashboard routes
│   ├── entities/
│   ├── opportunities/
│   └── wallet/
├── api/              # API routes
│   ├── auth/
│   ├── entities/
│   └── opportunities/
├── globals.css       # Global styles
├── layout.tsx        # Root layout
└── page.tsx          # Homepage
```

### Route Groups
- `(auth)` - Authentication-related pages
- `(dashboard)` - Protected user dashboard
- `(public)` - Public marketing pages

## 🧩 Components Architecture

### Component Hierarchy

```
components/
├── ui/               # Base UI components (shadcn/ui)
│   ├── button.tsx
│   ├── input.tsx
│   └── dialog.tsx
├── features/         # Feature-specific components
│   ├── entities/
│   ├── opportunities/
│   └── wallet/
├── layout/          # Layout components
│   ├── navbar.tsx
│   ├── sidebar.tsx
│   └── footer.tsx
└── shared/          # Shared business components
    ├── user-avatar.tsx
    └── loading-spinner.tsx
```

### Component Patterns

#### 1. Base UI Components
// components/ui/button.tsx

{`import { cn } from '@/lib/utils'

interface ButtonProps {
  variant?: 'default' | 'destructive' | 'outline'
  size?: 'default' | 'sm' | 'lg'
  children: React.ReactNode
}

export function Button({ variant = 'default', size = 'default', children, ...props }: ButtonProps) {
  return (
    
      {children}
    
  )
}`}

#### 2. Feature Components
// components/features/entities/entity-card.tsx

{`import { Entity } from '@/types/entities'
import { Button } from '@/components/ui/button'

interface EntityCardProps {
  entity: Entity
  onEdit?: (entity: Entity) => void
}

export function EntityCard({ entity, onEdit }: EntityCardProps) {
  return (
    
      {entity.name}
      {entity.description}
      {onEdit && (
         onEdit(entity)}>
          Edit
        
      )}
    
  )
}`}

## 🎯 Features Architecture

### Feature-Based Organization

```
features/
├── entities/         # Entity management feature
│   ├── components/   # Feature-specific components
│   ├── hooks/       # Custom hooks
│   ├── types/       # TypeScript types
│   ├── utils/       # Feature utilities
│   └── index.ts     # Public API
├── opportunities/   # Opportunities feature
├── wallet/         # Web3 wallet feature
└── messaging/      # Real-time messaging
```

### Feature Module Pattern

// features/entities/index.ts - Public API

{`export { EntityCard } from './components/entity-card'
export { useEntities } from './hooks/use-entities'
export type { Entity, EntityType } from './types'
export { createEntity, updateEntity } from './utils/entity-operations'`}

### Custom Hooks Pattern

// features/entities/hooks/use-entities.ts

{`import { useQuery } from '@tanstack/react-query'
import { getEntities } from '../utils/entity-operations'

export function useEntities(userId?: string) {
  return useQuery({
    queryKey: ['entities', userId],
    queryFn: () => getEntities(userId),
    enabled: !!userId
  })
}`}

## 🔧 Lib Directory

### Shared Utilities

```
lib/
├── auth.ts          # Auth.js configuration
├── firebase.ts      # Firebase setup
├── db.ts           # Database utilities
├── utils.ts        # General utilities
├── validations.ts  # Zod schemas
├── constants.ts    # App constants
└── types.ts        # Global types
```

### Key Utilities

#### Authentication Configuration
// lib/auth.ts

{`import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
  ],
  // ... configuration
})`}

#### Database Utilities
// lib/db.ts

{`import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'

const app = initializeApp(firebaseConfig)
export const db = getFirestore(app)`}

## ⚡ Server Actions

### Server Actions Structure

```
@actions/
├── entities/
│   ├── create-entity.ts
│   ├── update-entity.ts
│   └── delete-entity.ts
├── opportunities/
└── auth/
```

### Server Action Pattern

{`// @actions/entities/create-entity.ts
'use server'

import { auth } from '@/lib/auth'
import { createEntitySchema } from '@/lib/validations'
import { redirect } from 'next/navigation'

export async function createEntity(formData: FormData) {
  const session = await auth()
  if (!session?.user) {
    redirect('/login')
  }

  const validatedFields = createEntitySchema.safeParse({
    name: formData.get('name'),
    type: formData.get('type'),
    description: formData.get('description'),
  })

  if (!validatedFields.success) {
    return { error: 'Invalid fields' }
  }

  // Create entity logic...
  
  redirect('/dashboard/entities')
}`}

## 📝 TypeScript Patterns

### Type Organization

// types/entities.ts

{`export interface Entity {
  id: string
  name: string
  type: EntityType
  description: string
  createdAt: Date
  updatedAt: Date
}

export type EntityType = 
  | 'technology'
  | 'healthcare'
  | 'finance'
  // ... other types

export interface CreateEntityRequest {
  name: string
  type: EntityType
  description: string
}`}

### API Response Types

// types/api.ts

{`export interface ApiResponse {
  data?: T
  error?: string
  message?: string
}

export interface PaginatedResponse {
  data: T[]
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}`}

## 🎨 Styling Architecture

### Tailwind CSS Organization

```
app/globals.css
├── @tailwind base;
├── @tailwind components;
├── @tailwind utilities;
└── /* Custom component styles */
```

### Component Styling Patterns

// Using cn utility for conditional classes

{`import { cn } from '@/lib/utils'

function Component({ variant, className }: Props) {
  return (
    
      Content
    
  )
}`}

## 📚 Best Practices

### 1. Import Organization
// External imports first

{`import React from 'react'
import { NextPage } from 'next'

// Internal imports
import { Button } from '@/components/ui/button'
import { useEntities } from '@/features/entities'
import { cn } from '@/lib/utils'

// Type imports last
import type { Entity } from '@/types/entities'`}

### 2. Component File Structure
// 1. Imports

{`// 2. Types/Interfaces
// 3. Component implementation
// 4. Default export
// 5. Named exports (if any)`}

### 3. Feature Boundaries
- Keep feature code within feature directories
- Use public APIs for cross-feature communication
- Avoid deep imports from other features

---

*Next: [Development Workflow](/ru/docs/development/workflow) - Learn about our Git workflow and development process.*
