Files
pos-system/docs/en/templates/mermaid-guide.md

12 KiB

Mermaid Diagram Guide / Hướng dẫn Sơ đồ Mermaid

Overview / Tổng quan

EN: This guide helps you choose the right Mermaid diagram type for your documentation and provides examples for common use cases.

VI: Hướng dẫn này giúp bạn chọn loại sơ đồ Mermaid phù hợp cho tài liệu của bạn và cung cấp ví dụ cho các trường hợp sử dụng phổ biến.

Quick Reference / Tham chiếu Nhanh

Diagram Type / Loại Use For / Sử dụng cho Complexity / Độ phức tạp
Flowchart Workflows, decision trees / Quy trình, cây quyết định
Sequence Diagram API interactions, request flows / Tương tác API, luồng request
Class Diagram Code structure, patterns / Cấu trúc code, patterns
Graph System architecture, dependencies / Kiến trúc hệ thống, dependencies
ER Diagram Database schema / Schema database
Gantt Timeline, project schedule / Timeline, lịch trình dự án
C4 Diagram System context, containers / Bối cảnh hệ thống, containers

1. Flowcharts / Sơ đồ Luồng

When to Use / Khi nào sử dụng

EN: Use flowcharts for:

  • Step-by-step guides and workflows
  • Decision trees and conditional logic
  • Process flows with multiple branches
  • Troubleshooting procedures

VI: Sử dụng flowcharts cho:

  • Hướng dẫn từng bước và quy trình
  • Cây quyết định và logic điều kiện
  • Luồng quy trình với nhiều nhánh
  • Thủ tục khắc phục sự cố

Basic Flowchart

flowchart TD
    Start([Start]) --> Input[Get Input]
    Input --> Check{Valid?}
    Check -->|Yes| Process[Process Data]
    Check -->|No| Error[Show Error]
    Process --> Output[Return Result]
    Output --> End([End])
    Error --> End
    
    style Start fill:#e1f5ff
    style End fill:#d4edda
    style Check fill:#fff3cd
    style Error fill:#f8d7da

Code:

```mermaid
flowchart TD
    Start([Start]) --> Input[Get Input]
    Input --> Check{Valid?}
    Check -->|Yes| Process[Process Data]
    Check -->|No| Error[Show Error]
    Process --> Output[Return Result]
    Output --> End([End])
    Error --> End
    
    style Start fill:#e1f5ff
    style End fill:#d4edda
    style Check fill:#fff3cd
    style Error fill:#f8d7da
```

Advanced Flowchart with Subgraphs

flowchart LR
    A[Client Request] --> B{Auth?}
    B -->|No| C[401 Unauthorized]
    B -->|Yes| D[Process]
    
    subgraph Processing["Request Processing"]
        D --> E[Validate Input]
        E --> F[Execute Logic]
        F --> G[Format Response]
    end
    
    G --> H[Return 200 OK]
    C --> I[End]
    H --> I
    
    style Processing fill:#f0e1ff

2. Sequence Diagrams / Sơ đồ Tuần tự

When to Use / Khi nào sử dụng

EN: Use sequence diagrams for:

  • API communication flows
  • Authentication/authorization flows
  • Service-to-service interactions
  • Request/response cycles

VI: Sử dụng sequence diagrams cho:

  • Luồng giao tiếp API
  • Luồng xác thực/phân quyền
  • Tương tác giữa các service
  • Chu kỳ request/response

Basic Sequence Diagram

sequenceDiagram
    participant Client
    participant API
    participant Service
    participant DB
    
    Client->>API: POST /login
    API->>Service: authenticate(credentials)
    Service->>DB: findUser(email)
    DB-->>Service: user
    Service->>Service: verifyPassword()
    Service-->>API: JWT token
    API-->>Client: 200 OK {token}

Code:

```mermaid
sequenceDiagram
    participant Client
    participant API
    participant Service
    participant DB
    
    Client->>API: POST /login
    API->>Service: authenticate(credentials)
    Service->>DB: findUser(email)
    DB-->>Service: user
    Service->>Service: verifyPassword()
    Service-->>API: JWT token
    API-->>Client: 200 OK {token}
```

Advanced with Alt/Opt/Loop

sequenceDiagram
    participant Client
    participant API
    participant Cache
    participant DB
    
    Client->>API: GET /users/:id
    API->>Cache: get(key)
    
    alt Cache Hit
        Cache-->>API: cached data
        API-->>Client: 200 OK (from cache)
    else Cache Miss
        Cache-->>API: null
        API->>DB: SELECT * FROM users
        DB-->>API: user data
        API->>Cache: set(key, data, ttl)
        API-->>Client: 200 OK (from DB)
    end

3. Class Diagrams / Sơ đồ Class

When to Use / Khi nào sử dụng

EN: Use class diagrams for:

  • Design patterns and code structure
  • Object-oriented architecture
  • Inheritance and relationships
  • Module dependencies

VI: Sử dụng class diagrams cho:

  • Design patterns và cấu trúc code
  • Kiến trúc hướng đối tượng
  • Kế thừa và mối quan hệ
  • Dependencies giữa các module

Basic Class Diagram

classDiagram
    class BaseRepository {
        #prisma: PrismaClient
        #modelName: string
        +findById(id: string) T
        +findAll(options: QueryOptions) T[]
        +create(data: CreateDto) T
        +update(id: string, data: UpdateDto) T
        +delete(id: string) void
    }
    
    class UserRepository {
        +findByEmail(email: string) User
        +findByUsername(username: string) User
    }
    
    class FeatureRepository {
        +findByName(name: string) Feature
        +toggleStatus(id: string) Feature
    }
    
    BaseRepository <|-- UserRepository
    BaseRepository <|-- FeatureRepository

4. Graph Diagrams / Sơ đồ Graph

When to Use / Khi nào sử dụng

EN: Use graph diagrams for:

  • System architecture overview
  • Component relationships
  • Data flow diagrams
  • Dependency graphs

VI: Sử dụng graph diagrams cho:

  • Tổng quan kiến trúc hệ thống
  • Mối quan hệ giữa các thành phần
  • Sơ đồ luồng dữ liệu
  • Đồ thị dependencies

System Architecture

graph TD
    Client[Web Client] --> Gateway[Traefik Gateway]
    Gateway --> Auth[Auth Service]
    Gateway --> IAM[IAM Service]
    Gateway --> User[User Service]
    
    Auth --> DB[(PostgreSQL)]
    IAM --> DB
    User --> DB
    
    Auth --> Cache[(Redis)]
    IAM --> Cache
    User --> Cache
    
    style Gateway fill:#e1f5ff
    style DB fill:#f0e1ff
    style Cache fill:#fff4e1

Data Flow

graph LR
    Input[User Input] --> Validation[Zod Validation]
    Validation --> Controller[Controller]
    Controller --> Service[Service Layer]
    Service --> Repository[Repository]
    Repository --> Prisma[Prisma ORM]
    Prisma --> DB[(Database)]
    
    Service --> Cache[Cache Service]
    Cache --> Redis[(Redis)]
    
    style Validation fill:#d4edda
    style Service fill:#e1f5ff
    style Cache fill:#fff4e1

5. ER Diagrams / Sơ đồ ER

When to Use / Khi nào sử dụng

EN: Use ER diagrams for:

  • Database schema documentation
  • Entity relationships
  • Data modeling
  • Prisma schema visualization

VI: Sử dụng ER diagrams cho:

  • Tài liệu schema database
  • Mối quan hệ giữa các entity
  • Mô hình dữ liệu
  • Visualization Prisma schema

Database Schema

erDiagram
    User ||--o{ Session : has
    User ||--o{ RefreshToken : has
    User ||--o{ UserRole : has
    Role ||--o{ UserRole : has
    Role ||--o{ RolePermission : has
    Permission ||--o{ RolePermission : has
    
    User {
        string id PK
        string email UK
        string passwordHash
        boolean mfaEnabled
        datetime createdAt
        datetime updatedAt
    }
    
    Session {
        string id PK
        string userId FK
        string token UK
        string deviceId
        string ipAddress
        datetime expiresAt
    }
    
    Role {
        string id PK
        string name UK
        string description
        datetime createdAt
    }
    
    Permission {
        string id PK
        string code UK
        string resource
        string action
        string scope
    }

6. Gantt Charts / Biểu đồ Gantt

When to Use / Khi nào sử dụng

EN: Use Gantt charts for:

  • Project timelines
  • Implementation phases
  • Migration schedules
  • Deployment plans

VI: Sử dụng Gantt charts cho:

  • Timeline dự án
  • Các giai đoạn triển khai
  • Lịch trình migration
  • Kế hoạch deployment

Project Timeline

gantt
    title Documentation Update Project Timeline
    dateFormat YYYY-MM-DD
    section Phase 1
    Analysis & Research           :done, p1, 2024-01-01, 1d
    section Phase 2
    Templates & Strategy          :active, p2, 2024-01-02, 0.5d
    section Phase 3
    High Priority Docs            :p3, 2024-01-03, 2d
    section Phase 4
    Remaining Docs                :p4, 2024-01-05, 3d
    section Phase 5
    QA & Verification             :p5, 2024-01-08, 1d

7. C4 Diagrams / Sơ đồ C4

When to Use / Khi nào sử dụng

EN: Use C4 diagrams for:

  • System context (highest level)
  • Container diagrams (services, databases)
  • Component diagrams (modules within services)
  • Code diagrams (classes, functions)

VI: Sử dụng C4 diagrams cho:

  • Bối cảnh hệ thống (cấp cao nhất)
  • Sơ đồ container (services, databases)
  • Sơ đồ component (modules trong services)
  • Sơ đồ code (classes, functions)

System Context

C4Context
    title System Context Diagram for IAM System
    
    Person(user, "User", "System user needing authentication")
    Person(admin, "Admin", "System administrator")
    
    System(iam, "IAM System", "Identity and Access Management")
    
    System_Ext(email, "Email Service", "SendGrid/AWS SES")
    System_Ext(oauth, "OAuth Providers", "Google, Facebook, GitHub")
    
    Rel(user, iam, "Authenticates with", "HTTPS")
    Rel(admin, iam, "Manages users and permissions", "HTTPS")
    Rel(iam, email, "Sends emails", "SMTP/API")
    Rel(iam, oauth, "OAuth login", "OAuth 2.0")

Styling Tips / Mẹo Styling

Color Palette / Bảng màu

graph LR
    A["Primary<br/>#e1f5ff"] --> B["Secondary<br/>#fff4e1"]
    B --> C["Success<br/>#d4edda"]
    C --> D["Warning<br/>#fff3cd"]
    D --> E["Error<br/>#f8d7da"]
    E --> F["Info<br/>#f0e1ff"]
    
    style A fill:#e1f5ff
    style B fill:#fff4e1
    style C fill:#d4edda
    style D fill:#fff3cd
    style E fill:#f8d7da
    style F fill:#f0e1ff

Style Syntax

style NodeId fill:#colorcode,stroke:#bordercolor,stroke-width:2px

Examples:

style Start fill:#e1f5ff
style Error fill:#f8d7da
style Process fill:#d4edda,stroke:#28a745,stroke-width:2px

Best Practices / Best Practices

EN: Guidelines

  1. Keep it Simple: Don't overcomplicate diagrams
  2. Use Consistent Styling: Apply color scheme consistently
  3. Add Legends: Explain symbols and colors when needed
  4. Limit Complexity: Break into multiple diagrams if too complex
  5. Test Rendering: Always test diagrams render correctly

VI: Hướng dẫn

  1. Giữ đơn giản: Đừng làm phức tạp sơ đồ quá mức
  2. Sử dụng Styling nhất quán: Áp dụng bảng màu nhất quán
  3. Thêm Chú giải: Giải thích ký hiệu và màu sắc khi cần
  4. Giới hạn Độ phức tạp: Chia thành nhiều sơ đồ nếu quá phức tạp
  5. Test Rendering: Luôn test sơ đồ render chính xác

Common Pitfalls / Lỗi Thường gặp

Too Complex

graph TD
    A --> B
    A --> C
    B --> D
    B --> E
    C --> F
    C --> G
    D --> H
    E --> H
    F --> I
    G --> I
    H --> J
    I --> J

Simplified with Subgraphs

graph TD
    A[Start] --> B[Process A]
    B --> C[Process B]
    
    subgraph "Detailed Processing"
        C --> D[Step 1]
        D --> E[Step 2]
    end
    
    E --> F[End]

Testing Diagrams / Test Sơ đồ

EN: Always test your diagrams before committing:

VI: Luôn test sơ đồ trước khi commit:

# Install mermaid-cli
npm install -g @mermaid-js/mermaid-cli

# Test render
mmdc -i your-doc.md -o test-output.svg

# Check for errors
echo $?  # Should be 0 if successful

Resources / Tài nguyên


Last Updated: 2026-01-05