# vytor0-ifpi/designgest-o architecture

> Architecture diagram of the GitHub repository vytor0-ifpi/designgest-o, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-02-23). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/vytor0-ifpi/designgest-o
- Repository: https://github.com/vytor0-ifpi/designgest-o

## Overview

##### Tipo e propósito do projeto (o que o diagrama precisa “contar”)
Pelo file tree e README, isto é um **SPA (Single Page Application) front-end** em **React 19 + Vite**, com:
- **Persistência/sincronização em nuvem via Supabase** (Postgres + Auth/SDK).
- **Automação via Gmail API** usando **Google OAuth2** (client-side).
- **Multi-tenancy por usuário**: todas as entidades têm `userId` e o app garante isolamento por usuário (idealmente com RLS no Supabase).

Não existe backend próprio no repositório (não há `/server`, `/api`, functions). Então o “backend” do sistema é composto por **serviços externos**: **Supabase** e **Google APIs**. Isso muda o foco do diagrama: ele deve destacar **fluxos client ↔ supabase ↔ db** e **client ↔ google oauth ↔ gmail api**, além dos **context providers** e “camadas” internas do front.

##### Anatomia do repositório (quais “caixas” desenhar)
Mapeie o diagrama a partir de pastas-chave:

##### Camada de Apresentação (UI)
`src/components/*`
- `Layout.tsx`: “shell” da aplicação (navegação, estrutura, provavelmente header/sidebar).
- `Login.tsx`: autenticação/entrada.
- `Dashboard.tsx`: métricas e ações rápidas (inclui “botão de autorizar Google” segundo README).
- Módulos de domínio (telas):
- `Clients.tsx`, `Projects.tsx`, `Tasks.tsx`, `Messages.tsx`, `Reports.tsx`, `Users.tsx`

**Como representar no diagrama:** um bloco “UI Screens / Components” com sub-blocos (Dashboard, Projects, Tasks, etc.). Não precisa desenhar cada componente minúsculo, mas vale separar por **áreas de negócio**.

##### Camada de Estado / Orquestração (Context)
`src/context/*`
- `AuthContext.tsx`: sessão do usuário, login/logout, usuário atual, role.
- `DataContext.tsx`: carregamento e cache de dados (clients/projects/tasks/notes).
- `GmailContext.tsx`: estado e tokens/flag de autorização Google, gatilhos de envio.

**Como representar:** um bloco “State Management (React Context)” com três subcomponentes e setas:
- UI → Context (dispatch/consumo)
- Context → Services (chamadas)

##### Camada de Integração (Services)
`src/services/*`
- `db.ts`: gateway para Supabase (CRUD, queries filtradas por `userId`, subscriptions realtime se existirem).
- `gmail.ts`: gateway Google OAuth2 / Gmail API (envio e automações).

**Como representar:** um bloco “Service Layer” entre Context e serviços externos.

##### Tipos e Utilitários
- `src/types/index.ts`: modelos (User, Client, Project, Task, Note, etc.).
- `src/utils/cn.ts`: utilitário de classnames (Tailwind).
Esses não são “componentes” do sistema em runtime, mas você pode anotar no diagrama como “shared contracts”.

##### Bootstrap / Runtime
- `src/main.tsx`: entrypoint React.
- `src/App.tsx`: roteamento / composição de providers + layout.

**Como representar:** um bloco “App Bootstrap (main.tsx/App.tsx)” que instancia Providers.

##### Deploy
- `.github/workflows/deploy.yml`: pipeline de deploy para GitHub Pages.
- `vite.config.ts`, `package.json`: build toolchain.

**Como representar:** um diagrama secundário “CI/CD & Hosting”, separado do diagrama de runtime.

##### Componentes externos reais (backend de fato)
Do README:
- **Supabase**: usa `VITE_SUPABASE_URL` e `VITE_SUPABASE_ANON_KEY`.
- Banco Postgres com tabelas: `users, clients, projects, tasks, notes`
- Campos `userId` garantem multi-tenancy (ideal: RLS no banco; no diagrama, marque “Isolamento por usuário via userId (+ RLS)”.
- **Google OAuth2 + Gmail API** com `VITE_GOOGLE_CLIENT_ID`.

**Como representar:** dois grandes blocos externos:
##### “Supabase”
- Sub-blocos: “Auth (opcional)”, “Postgres DB”, “Realtime (opcional)”
##### “Google Identity/OAuth2” e “Gmail API”

E um bloco de hosting:
- “GitHub Pages (Static Hosting)” servindo `index.html` e bundle Vite.

##### Diagrama “Container/Component” (recomendado como principal)
Desenhe caixas e setas assim:

##### User (browser)
→ **2. GitHub Pages** (serve HTML/JS/CSS)
→ **3. React SPA (Vite build)**

##### UI / Screens
- Dashboard
- Clients / Projects / Tasks / Notes(Messages) / Reports / Users
##### Context Providers
- AuthContext
- DataContext
- GmailContext
##### Service Layer
- db.ts (Supabase client wrapper)
- gmail.ts (Google OAuth + Gmail API wrapper)
##### Shared
- types
- utils

**Externos (fora do SPA):**
- Supabase (Postgres + policies)
- Google OAuth2
- Gmail API

##### Setas (fluxos) que não podem faltar
**Fluxo de autenticação/isolamento**
- UI(Login) → AuthContext → (Supabase Auth, se usado) → retorna sessão/user
- DataContext → db.ts → Supabase DB: queries **filtradas por `userId`**
- Anote: “RLS/Policies recomendadas” + “todas as tabelas têm userId”.

**Fluxo de sincronização**
- DataContext ↔ db.ts ↔ Supabase
- Se houver realtime (README sugere “tempo real”), desenhe seta dupla “Realtime subscriptions / listeners” do Supabase para DataContext, e daí para UI.

**Fluxo Gmail**
- Dashboard (botão conectar) → GmailContext → gmail.ts → Google OAuth2 (consent)
- gmail.ts → Gmail API (send email / logs)
- Gatilhos (ex.: “novo cliente”) partem de UI/DataContext → GmailContext → Gmail API

**Fluxo de relatórios/admin**
- Reports/Users → DataContext/db.ts → Supabase
- Reports → GmailContext/gmail.ts → Gmail API (envio de logs para admins)

##### Padrões/decisões arquiteturais a explicitar no diagrama
- **SPA + BaaS**: sem backend próprio; Supabase é o backend.
- **Separação por camadas no front**:
- Components (apresentação)
- Context (estado e regras de fluxo)
- Services (integração com APIs externas)
- **Multi-tenancy**:
- `userId` em todas as entidades
- Isolamento: “somente dados do usuário logado”
- **Automação**:
- Gmail OAuth2 + Gmail API acoplado ao front (atenção a tokens/escopos; no diagrama, marque “OAuth2 tokens in browser session/storage” se aplicável).

##### Um segundo diagrama (CI/CD & Deploy) — pequeno, mas útil
Mostre:
- Dev → GitHub Repo
- GitHub Actions (`.github/workflows/deploy.yml`)
- steps: install → build (Vite) → deploy
- GitHub Pages hosting
- Config via `.env` (build-time `VITE_*`) e impacto: “env vars injected at build”.

Isso ajuda a explicar por que o app é totalmente client-side e como vai para produção.

##### Como detalhar sem “overthink”: separar em muitos componentes (do jeito certo)
Para máxima precisão, recomendo **dois níveis no mesmo desenho**:

##### Nível 1 (alto nível)
User → GitHub Pages → React SPA → (Supabase, Google OAuth2, Gmail)

##### Nível 2 (interno ao SPA)
App bootstrap (main/App)
→ Providers (Auth/Data/Gmail)
→ Screens (Dashboard, Clients, Projects, Tasks, Reports, Users, Messages/Notes)
→ Services (db.ts, gmail.ts)
→ External APIs

Assim você “explode” o front em partes relevantes sem inventar backend inexistente.

##### Convenções visuais (o que colocar no desenho)
- **Rótulos claros** (ex.: “DataContext (cache + sync)”, “db.ts (Supabase client)”, “GmailContext (OAuth state)”).
- **Setas direcionais com verbos**:
- “fetch clients (userId)”
- “subscribe realtime updates”
- “OAuth consent”
- “send welcome email”
- **Cores/formatos**
- Azul: componentes do SPA
- Roxo: context/state
- Cinza: serviços externos (Supabase/Google)
- Verde: deploy/CI/CD (num diagrama separado)
- **Notas de segurança** no canto:
- “Multi-tenancy via userId + (ideal) RLS”
- “OAuth tokens handled client-side”
- “VITE_* env vars are build-time”

##### Checklist final (para garantir que o diagrama ficou “fiel ao repo”)
- O diagrama mostra **somente** o que existe: React SPA + Supabase + Google/Gmail + GitHub Pages.
- Inclui explicitamente:
- `AuthContext`, `DataContext`, `GmailContext`
- `db.ts`, `gmail.ts`
- Entidades/tabelas principais e `userId`
- Deploy via GitHub Actions → GitHub Pages
- Fluxos críticos desenhados:
- Login/Session
- CRUD + sync (Supabase)
- OAuth2 + envio de emails (Gmail)

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% ===========
    %% External Actor & Hosting
    %% ===========
    U["User (Browser)"]:::external

    subgraph "Static Hosting"
        GH["GitHub Pages (Static Hosting)"]:::hosting
        IDX["index.html"]:::artifact
        GH -->|"serves"| IDX
    end

    U -->|"loads SPA bundle"| GH

    %% ===========
    %% React SPA (Runtime)
    %% ===========
    subgraph "React SPA (React 19 + Vite) - Client-side"
        direction TB

        subgraph "App Bootstrap"
            direction TB
            MAIN["main.tsx (Entrypoint)"]:::spa
            APP["App.tsx (Routing + Provider composition)"]:::spa
            CSS["index.css (Global styles)"]:::shared
            MAIN -->|"mounts"| APP
            MAIN -->|"imports"| CSS
        end

        subgraph "Presentation Layer (UI Screens / Components)"
            direction TB
            LAYOUT["Layout.tsx (App shell)"]:::ui

            subgraph "Auth & Home"
                direction TB
                LOGIN["Login.tsx"]:::ui
                DASH["Dashboard.tsx (Authorize Google)"]:::ui
            end

            subgraph "Domain Screens"
                direction TB
                CLIENTS["Clients.tsx"]:::ui
                PROJECTS["Projects.tsx"]:::ui
                TASKS["Tasks.tsx"]:::ui
                MSG["Messages.tsx (Notes/Messages)"]:::ui
                REPORTS["Reports.tsx"]:::ui
                USERS["Users.tsx (Admin/Users)"]:::ui
            end
        end

        subgraph "State Management (React Context Providers)"
            direction TB
            AUTHCTX["AuthContext (session + user + role)"]:::context
            DATACTX["DataContext (cache + load + sync)"]:::context
            GMAILCTX["GmailContext (OAuth state + triggers)"]:::context
        end

        subgraph "Service Layer (Integration Gateways)"
            direction TB
            DB["db.ts (Supabase client wrapper)"]:::service
            GMAILSVC["gmail.ts (Google OAuth2 + Gmail API wrapper)"]:::service
        end

        subgraph "Shared Contracts & Utilities"
            direction TB
            TYPES["types/index.ts (Domain models)"]:::shared
            CN["utils/cn.ts (classnames helper)"]:::shared
        end

        %% SPA wiring
        APP -->|"renders"| LAYOUT
        APP -->|"provides"| AUTHCTX
        APP -->|"provides"| DATACTX
        APP -->|"provides"| GMAILCTX

        LAYOUT -->|"routes to"| LOGIN
        LAYOUT -->|"routes to"| DASH
        LAYOUT -->|"routes to"| CLIENTS
        LAYOUT -->|"routes to"| PROJECTS
        LAYOUT -->|"routes to"| TASKS
        LAYOUT -->|"routes to"| MSG
        LAYOUT -->|"routes to"| REPORTS
        LAYOUT -->|"routes to"| USERS

        %% UI -> Context usage
        LOGIN -->|"login/logout"| AUTHCTX
        DASH -->|"authorize / send"| GMAILCTX

        CLIENTS -->|"CRUD actions"| DATACTX
        PROJECTS -->|"CRUD actions"| DATACTX
        TASKS -->|"CRUD actions"| DATACTX
        MSG -->|"CRUD actions"| DATACTX
        REPORTS -->|"query/report"| DATACTX
        USERS -->|"admin queries"| DATACTX

        %% Context -> Services
        AUTHCTX -->|"auth/session ops"| DB
        DATACTX -->|"fetch+mutate (filtered by userId)"| DB
        DATACTX -->|"trigger automations"| GMAILCTX
        GMAILCTX -->|"OAuth+API calls"| GMAILSVC

        %% Shared usage
        AUTHCTX -->|"uses"| TYPES
        DATACTX -->|"uses"| TYPES
        DB -->|"uses"| TYPES
        GMAILSVC -->|"uses"| TYPES
        LAYOUT -->|"uses"| CN
    end

    IDX -->|"loads"| MAIN

    %% ===========
    %% External Services (Backend = BaaS + Google APIs)
    %% ===========
    subgraph "Supabase (External BaaS Backend)"
        direction TB
        SUPA["Supabase Project"]:::external
        SUPA_AUTH["Auth (optional)"]:::external
        SUPA_DB[("Postgres DB\nusers, clients, projects, tasks, notes\n(userId on all tables)")]:::db
        SUPA_RT["Realtime (optional)"]:::external

        SUPA -->|"provides"| SUPA_AUTH
        SUPA -->|"stores"| SUPA_DB
        SUPA -->|"streams"| SUPA_RT
    end

    subgraph "Google APIs (External)"
        direction TB
        GID["Google Identity / OAuth2 Consent"]:::external
        GMAILAPI["Gmail API"]:::external
        GID -->|"issues access tokens"| GMAILAPI
    end

    %% Service layer -> external services
    DB -->|"Supabase SDK calls"| SUPA
    DB -->|"CRUD queries (WHERE userId = currentUser)"| SUPA_DB
    SUPA_RT -->|"realtime events"| DATACTX

    GMAILSVC -->|"OAuth consent flow"| GID
    GMAILSVC -->|"send email / automation"| GMAILAPI

    %% Notes (as nodes to keep Mermaid vertical)
    subgraph "Security / Architecture Notes"
        direction TB
        NOTE1["Multi-tenancy: all entities include userId; isolate data per logged-in user (RLS recommended)"]:::note
        NOTE2["No custom backend in repo: SPA talks directly to Supabase + Google APIs"]:::note
        NOTE3["OAuth tokens handled client-side (browser session/storage)"]:::note
        NOTE4["VITE_* env vars injected at build-time"]:::note
    end

    AUTHCTX -.->|"enforces user scope"| NOTE1
    DATACTX -.->|"queries scoped by userId"| NOTE1
    GMAILCTX -.->|"token handling"| NOTE3
    APP -.->|"SPA+BaaS"| NOTE2

    %% ===========
    %% CI/CD & Deploy (Secondary)
    %% ===========
    subgraph "CI/CD & Deploy"
        direction TB
        DEV["Developer"]:::cicd
        REPO["GitHub Repo"]:::cicd
        GHA["GitHub Actions (deploy workflow)"]:::cicd
        VITE["Vite Build Tooling"]:::cicdArtifact

        DEV -->|"git push"| REPO
        REPO -->|"triggers"| GHA
        GHA -->|"install + build"| VITE
        VITE -->|"build output"| GH
    end

    %% ===========
    %% Click events (component_mapping)
    %% ===========
    click MAIN "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/main.tsx"
    click APP "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/App.tsx"
    click LAYOUT "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Layout.tsx"
    click LOGIN "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Login.tsx"
    click DASH "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Dashboard.tsx"
    click CLIENTS "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Clients.tsx"
    click PROJECTS "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Projects.tsx"
    click TASKS "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Tasks.tsx"
    click MSG "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Messages.tsx"
    click REPORTS "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Reports.tsx"
    click USERS "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/components/Users.tsx"
    click AUTHCTX "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/context/AuthContext.tsx"
    click DATACTX "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/context/DataContext.tsx"
    click GMAILCTX "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/context/GmailContext.tsx"
    click DB "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/services/db.ts"
    click GMAILSVC "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/services/gmail.ts"
    click TYPES "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/types/index.ts"
    click CN "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/utils/cn.ts"
    click GHA "https://github.com/vytor0-ifpi/designgest-o/blob/main/.github/workflows/deploy.yml"
    click VITE "https://github.com/vytor0-ifpi/designgest-o/blob/main/vite.config.ts"
    click IDX "https://github.com/vytor0-ifpi/designgest-o/blob/main/index.html"
    click CSS "https://github.com/vytor0-ifpi/designgest-o/blob/main/src/index.css"

    %% ===========
    %% Styles
    %% ===========
    classDef spa fill:#1e3a8a,stroke:#0b2447,color:#ffffff,stroke-width:1px
    classDef ui fill:#2563eb,stroke:#1e40af,color:#ffffff,stroke-width:1px
    classDef context fill:#7c3aed,stroke:#5b21b6,color:#ffffff,stroke-width:1px
    classDef service fill:#0ea5e9,stroke:#0369a1,color:#ffffff,stroke-width:1px
    classDef shared fill:#0f766e,stroke:#115e59,color:#ffffff,stroke-width:1px

    classDef external fill:#6b7280,stroke:#374151,color:#ffffff,stroke-width:1px
    classDef db fill:#4b5563,stroke:#111827,color:#ffffff,stroke-width:1px

    classDef hosting fill:#64748b,stroke:#334155,color:#ffffff,stroke-width:1px
    classDef artifact fill:#94a3b8,stroke:#475569,color:#0b1220,stroke-width:1px

    classDef cicd fill:#16a34a,stroke:#14532d,color:#ffffff,stroke-width:1px
    classDef cicdArtifact fill:#22c55e,stroke:#166534,color:#052e16,stroke-width:1px

    classDef note fill:#f59e0b,stroke:#92400e,color:#111827,stroke-width:1px
```
