> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/marcosfabricio3/simple-manager-mobile/llms.txt
> Use this file to discover all available pages before exploring further.

# Clean Architecture Layers

> Understanding the four-layer architecture of Simple Manager Mobile

## Architecture Layers

Simple Manager follows **Clean Architecture** principles with four distinct layers. Dependencies flow inward: outer layers depend on inner layers, but inner layers never depend on outer layers.

```mermaid theme={null}
graph TD
    A[Presentation Layer] --> B[Application Layer]
    B --> C[Domain Layer]
    A --> D[Infrastructure Layer]
    B --> D
    D --> C
    
    style C fill:#4CAF50
    style B fill:#2196F3
    style D fill:#FF9800
    style A fill:#9C27B0
```

## Layer Hierarchy

<Steps>
  <Step title="Domain Layer (Core)">
    Pure business logic and entities - no dependencies
  </Step>

  <Step title="Application Layer">
    Use cases and services - depends only on Domain
  </Step>

  <Step title="Infrastructure Layer">
    Database and external services - implements Domain interfaces
  </Step>

  <Step title="Presentation Layer">
    UI and user interaction - depends on Application
  </Step>
</Steps>

## 1. Domain Layer

<Card title="Location" icon="folder">
  `src/domain/`
</Card>

The **innermost layer** containing pure business logic with zero external dependencies.

### Responsibilities

* Define core entities and types
* Establish business rules
* Define interfaces (contracts)

### Structure

```
src/domain/
└── entities/
    ├── Record.ts
    ├── Appointment.ts
    └── Service.ts
```

### Example: Record Entity

<CodeGroup>
  ```typescript src/domain/entities/Record.ts theme={null}
  export interface Record {
    id: string;
    title: string;
    subtitle?: string;
    metadata?: string;
    type: string;
    userId?: string;
    createdAt: string;
    updatedAt: string;
    isDeleted: boolean;
  }
  ```
</CodeGroup>

<Note>
  Domain entities are plain TypeScript interfaces with no dependencies on frameworks or libraries.
</Note>

## 2. Application Layer

<Card title="Location" icon="folder">
  `src/application/`
</Card>

Contains **use cases** and **business logic** orchestration.

### Responsibilities

* Implement business use cases
* Coordinate between domain and infrastructure
* Handle validation
* Manage error handling

### Structure

```
src/application/
├── services/
│   └── RecordService.ts
├── validators/
│   └── recordValidator.ts
└── errors/
    └── getErrorMessage.ts
```

### Example: RecordService

<CodeGroup>
  ```typescript src/application/services/RecordService.ts theme={null}
  import { Record } from "@/src/domain/entities/Record";
  import { RecordRepository } from "@/src/infraestructure/repositories/RecordRepository";
  import * as Crypto from 'expo-crypto';

  export class RecordService {
    private repository = new RecordRepository();

    async create(title: string, type: string) {
      const now = new Date().toISOString();
      
      const record: Record = {
        id: Crypto.randomUUID(),
        title,
        type,
        createdAt: now,
        updatedAt: now,
        isDeleted: false,
      };

      await this.repository.create(record);
      return record;
    }

    async list() {
      return await this.repository.findAll();
    }

    async delete(id: string) {
      await this.repository.softDelete(id);
    }

    async update(record: Record) {
      record.updatedAt = new Date().toISOString();
      await this.repository.update(record);
    }
  }
  ```
</CodeGroup>

<Info>
  Services contain business logic and use repositories to access data. They don't know about UI or database implementation details.
</Info>

## 3. Infrastructure Layer

<Card title="Location" icon="folder">
  `src/infraestructure/`
</Card>

Handles **external concerns** like databases, APIs, and file systems.

### Responsibilities

* Implement data persistence
* Database access and queries
* External API integration (future)
* File storage

### Structure

```
src/infraestructure/
├── database/
│   ├── database.ts
│   └── initDatabase.ts
└── repositories/
    └── RecordRepository.ts
```

### Example: Database Setup

<CodeGroup>
  ```typescript src/infraestructure/database/database.ts theme={null}
  import * as SQLite from "expo-sqlite";

  export const db = SQLite.openDatabaseSync("simple_manager.db");
  ```

  ```typescript src/infraestructure/database/initDatabase.ts theme={null}
  import { db } from "./database";

  export function initDatabase() {
    db.execSync(`
      PRAGMA foreign_keys = ON;

      CREATE TABLE IF NOT EXISTS records (
        id TEXT PRIMARY KEY NOT NULL,
        title TEXT NOT NULL,
        subtitle TEXT,
        metadata TEXT,
        type TEXT NOT NULL,
        userId TEXT,
        createdAt TEXT NOT NULL,
        updatedAt TEXT NOT NULL,
        isDeleted INTEGER NOT NULL
      );
    `);
  }
  ```
</CodeGroup>

### Example: Repository Implementation

<CodeGroup>
  ```typescript src/infraestructure/repositories/RecordRepository.ts theme={null}
  import { Record } from "../../domain/entities/Record";
  import { db } from "../database/database";

  export class RecordRepository {
    async create(record: Record) {
      await db.runAsync(
        `INSERT INTO records (
          id, title, subtitle, metadata, type, userId, 
          createdAt, updatedAt, isDeleted
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          record.id,
          record.title,
          record.subtitle ?? null,
          record.metadata ?? null,
          record.type,
          record.userId ?? null,
          record.createdAt,
          record.updatedAt,
          record.isDeleted ? 1 : 0,
        ]
      );
    }

    async findAll(): Promise<Record[]> {
      const rows = await db.getAllAsync<any>(
        `SELECT * FROM records WHERE isDeleted = 0`
      );
      
      return rows.map((r) => ({
        ...r,
        isDeleted: Boolean(r.isDeleted),
      }));
    }

    async softDelete(id: string) {
      await db.runAsync(
        `UPDATE records SET isDeleted = 1 WHERE id = ?`,
        [id]
      );
    }
  }
  ```
</CodeGroup>

<Warning>
  Repositories handle all database interactions. Never access the database directly from services or UI components.
</Warning>

## 4. Presentation Layer

<Card title="Location" icon="folder">
  `src/presentation/`
</Card>

The **outermost layer** containing UI components and user interaction logic.

### Responsibilities

* Render UI components
* Handle user input
* Manage local component state
* Connect to application services via hooks

### Structure

```
src/presentation/
├── screens/
│   └── RecordsScreen.tsx
├── components/
│   └── RecordCard.tsx
└── hooks/
    └── useRecords.ts
```

### Example: Custom Hook

<CodeGroup>
  ```typescript src/presentation/hooks/useRecords.ts theme={null}
  import { RecordService } from "@/src/application/services/RecordService";
  import { Record } from "@/src/domain/entities/Record";
  import { useEffect, useMemo, useState } from "react";

  export function useRecords() {
    const service = useMemo(() => new RecordService(), []);
    const [records, setRecords] = useState<Record[]>([]);

    const load = async () => {
      const data = await service.list();
      setRecords(data);
    };

    const create = async (title: string, type: string) => {
      await service.create(title, type);
      await load();
    };

    const remove = async (id: string) => {
      await service.delete(id);
      await load();
    };

    useEffect(() => {
      load();
    }, []);

    return { records, load, create, remove };
  }
  ```
</CodeGroup>

<Tip>
  Custom hooks bridge the presentation layer and application layer, providing a clean API for components.
</Tip>

## Benefits of This Architecture

<CardGroup cols={2}>
  <Card title="Testability" icon="vial">
    Each layer can be tested independently with mocked dependencies
  </Card>

  <Card title="Maintainability" icon="wrench">
    Clear separation of concerns makes code easier to understand and modify
  </Card>

  <Card title="Scalability" icon="arrow-up">
    Easy to add new features without affecting existing code
  </Card>

  <Card title="Flexibility" icon="shuffle">
    Swap implementations (e.g., SQLite → API) without changing business logic
  </Card>
</CardGroup>

## Dependency Rule

<Warning>
  **Critical Rule**: Dependencies must point inward only. Inner layers must never import from outer layers.
</Warning>

```
✅ Presentation → Application ✅
✅ Application → Domain ✅
✅ Infrastructure → Domain ✅
❌ Domain → Application ❌
❌ Domain → Infrastructure ❌
```

## Related Pages

<CardGroup cols={2}>
  <Card title="Data Flow" icon="arrows-spin" href="/architecture/data-flow">
    See how data moves through layers
  </Card>

  <Card title="Folder Structure" icon="folder-tree" href="/architecture/folder-structure">
    Explore the complete project structure
  </Card>
</CardGroup>
