- Cria .env com comentários detalhados (13 variáveis) - Atualiza READMEs com guia completo de instalação - Documenta setup Appwrite Cloud e schemas de collections - Adiciona troubleshooting e guias de deploy - Total: ~1.240 linhas de documentação em português
550 lines
16 KiB
Markdown
550 lines
16 KiB
Markdown
# Core Platform Monorepo
|
|
|
|
> **Plataforma DevOps completa** com Landing Page (Fresh + Deno), Dashboard (React + Vite) e Backend Appwrite Cloud. Sistema integrado com autenticação, banco de dados em tempo real, e funções serverless para gerenciamento de servidores, repositórios GitHub e contas Cloudflare.
|
|
|
|
## 📋 Índice
|
|
|
|
- [Visão Geral](#-visão-geral)
|
|
- [Pré-requisitos](#-pré-requisitos)
|
|
- [Instalação Rápida](#-instalação-rápida)
|
|
- [Configuração Detalhada](#-configuração-detalhada)
|
|
- [Variáveis de Ambiente](#variáveis-de-ambiente)
|
|
- [Setup Appwrite Cloud](#setup-appwrite-cloud)
|
|
- [Executando o Projeto](#-executando-o-projeto)
|
|
- [Estrutura do Projeto](#-estrutura-do-projeto)
|
|
- [Scripts Disponíveis](#-scripts-disponíveis)
|
|
- [Verificação e Testes](#-verificação-e-testes)
|
|
- [Troubleshooting](#-troubleshooting)
|
|
- [Deploy](#-deploy)
|
|
|
|
## 🎯 Visão Geral
|
|
|
|
Este monorepo contém três componentes principais:
|
|
|
|
- **Landing Page**: Interface pública desenvolvida com Fresh (framework Deno) e Tailwind CSS
|
|
- **Dashboard**: Painel administrativo em React + TypeScript + Vite com integração Appwrite
|
|
- **Appwrite Functions**: Três funções serverless (hello-world, sync-github, check-cloudflare-status)
|
|
|
|
**Backend**: Appwrite Cloud - BaaS (Backend as a Service) com:
|
|
- Autenticação (Email/Password)
|
|
- Database com 4 coleções (servers, github_repos, audit_logs, cloud_accounts)
|
|
- Realtime subscriptions para logs ao vivo
|
|
- Functions para automação
|
|
|
|
## 🛠 Pré-requisitos
|
|
|
|
Certifique-se de ter instalado:
|
|
|
|
| Software | Versão Mínima | Como Verificar | Download |
|
|
|----------|---------------|----------------|----------|
|
|
| **Node.js** | 18.x ou superior | `node --version` | [nodejs.org](https://nodejs.org) |
|
|
| **npm** | 9.x ou superior | `npm --version` | Vem com Node.js |
|
|
| **Deno** | 1.40+ | `deno --version` | [deno.land](https://deno.land/manual/getting_started/installation) |
|
|
| **Git** | 2.x | `git --version` | [git-scm.com](https://git-scm.com) |
|
|
|
|
### Conta Appwrite Cloud
|
|
|
|
Você também precisa de uma conta no **[Appwrite Cloud](https://cloud.appwrite.io)** (gratuito):
|
|
|
|
1. Acesse https://cloud.appwrite.io e crie uma conta
|
|
2. Crie um novo projeto
|
|
3. Anote o **Project ID** que será usado nas variáveis de ambiente
|
|
|
|
## 🚀 Instalação Rápida
|
|
|
|
```bash
|
|
# 1. Clone o repositório
|
|
git clone <repository-url>
|
|
cd core
|
|
|
|
# 2. Instale as dependências raiz
|
|
npm install
|
|
|
|
# 3. Instale as dependências do dashboard
|
|
cd dashboard
|
|
npm install
|
|
cd ..
|
|
|
|
# 4. Verifique se o Deno está instalado
|
|
deno --version
|
|
# Se não estiver, instale: curl -fsSL https://deno.land/install.sh | sh
|
|
|
|
# 5. Configure as variáveis de ambiente
|
|
cp .env.example .env
|
|
# Edite o .env com suas credenciais Appwrite (veja seção abaixo)
|
|
|
|
# 6. Configure o Appwrite Cloud (veja seção "Setup Appwrite Cloud")
|
|
|
|
# 7. Execute o projeto
|
|
npm run dev:web
|
|
```
|
|
|
|
## ⚙️ Configuração Detalhada
|
|
|
|
### Variáveis de Ambiente
|
|
|
|
O arquivo `.env` na raiz do projeto contém todas as configurações necessárias. Copie o `.env.example` e preencha os valores:
|
|
|
|
```bash
|
|
cp .env.example .env
|
|
```
|
|
|
|
#### Referência Completa de Variáveis
|
|
|
|
| Variável | Onde Obter | Obrigatória | Descrição |
|
|
|----------|------------|-------------|-----------|
|
|
| **Configuração Server-Side (Scripts Node.js e Functions)** | | | |
|
|
| `APPWRITE_ENDPOINT` | Fixo | ✅ | URL da API Appwrite. Use `https://cloud.appwrite.io/v1` |
|
|
| `APPWRITE_PROJECT_ID` | Console Appwrite | ✅ | ID do projeto. Obtido em: Dashboard → Seu Projeto → Settings |
|
|
| `APPWRITE_API_KEY` | Console Appwrite | ✅ | Chave API com permissões Admin. Criar em: Settings → API Keys → Create API Key → Selecione todos os scopes |
|
|
| `APPWRITE_FUNCTIONS_ENDPOINT` | Opcional | ❌ | Endpoint customizado para Functions. Deixe vazio para usar o mesmo do `APPWRITE_ENDPOINT` |
|
|
| `APPWRITE_FUNCTIONS_API_KEY` | Opcional | ❌ | API Key separada para Functions. Deixe vazio para usar `APPWRITE_API_KEY` |
|
|
| **Configuração Client-Side (React Dashboard - Vite)** | | | |
|
|
| `VITE_APPWRITE_ENDPOINT` | Fixo | ✅ | Mesmo que `APPWRITE_ENDPOINT`. Prefixo `VITE_` expõe no browser |
|
|
| `VITE_APPWRITE_PROJECT_ID` | Console Appwrite | ✅ | Mesmo que `APPWRITE_PROJECT_ID` |
|
|
| `VITE_APPWRITE_DATABASE_ID` | Console Appwrite | ✅ | ID do Database criado. Obtido em: Databases → Seu Database → Settings |
|
|
| `VITE_APPWRITE_COLLECTION_SERVERS_ID` | Console Appwrite | ✅ | ID da coleção `servers`. Obtido em: Databases → Collections → servers → Settings |
|
|
| `VITE_APPWRITE_COLLECTION_GITHUB_REPOS_ID` | Console Appwrite | ✅ | ID da coleção `github_repos` |
|
|
| `VITE_APPWRITE_COLLECTION_AUDIT_LOGS_ID` | Console Appwrite | ✅ | ID da coleção `audit_logs` (usado para Realtime no terminal) |
|
|
| `VITE_APPWRITE_COLLECTION_CLOUDFLARE_ACCOUNTS_ID` | Console Appwrite | ✅ | ID da coleção `cloud_accounts` ou `cloudflare_accounts` |
|
|
|
|
**⚠️ IMPORTANTE**: Variáveis com prefixo `VITE_` são expostas no JavaScript do browser. **NUNCA** coloque informações sensíveis (API Keys) nelas!
|
|
|
|
### Setup Appwrite Cloud
|
|
|
|
Siga este passo a passo para configurar o backend:
|
|
|
|
#### 1. Criar Projeto
|
|
|
|
1. Acesse https://cloud.appwrite.io
|
|
2. Clique em **Create Project**
|
|
3. Dê um nome (ex: "DevOps Platform")
|
|
4. **Copie o Project ID** e salve no `.env`:
|
|
```
|
|
APPWRITE_PROJECT_ID=seu_project_id_aqui
|
|
VITE_APPWRITE_PROJECT_ID=seu_project_id_aqui
|
|
```
|
|
|
|
#### 2. Criar API Key
|
|
|
|
1. No menu lateral, vá em **Settings** → **API Keys**
|
|
2. Clique em **Create API Key**
|
|
3. Nome: "Admin Key" ou "Server Key"
|
|
4. **Scopes**: Marque **todos** (necessário para operações administrativas)
|
|
5. **Copie a API Key** (só aparece uma vez!) e salve no `.env`:
|
|
```
|
|
APPWRITE_API_KEY=sua_api_key_aqui
|
|
```
|
|
|
|
#### 3. Criar Database
|
|
|
|
1. No menu lateral, clique em **Databases**
|
|
2. Clique em **Create Database**
|
|
3. Nome: **DevOpsPlatform** (ou outro de sua escolha)
|
|
4. **Copie o Database ID** e salve no `.env`:
|
|
```
|
|
VITE_APPWRITE_DATABASE_ID=seu_database_id_aqui
|
|
```
|
|
|
|
#### 4. Criar Collections
|
|
|
|
Dentro do Database criado, crie as 4 coleções com os seguintes schemas:
|
|
|
|
##### Collection 1: **servers**
|
|
|
|
| Campo | Tipo | Required | Array | Default |
|
|
|-------|------|----------|-------|---------|
|
|
| `name` | String | Sim | Não | - |
|
|
| `ip` | String | Sim | Não | - |
|
|
| `status` | Enum | Sim | Não | `online` |
|
|
| `region` | String | Não | Não | - |
|
|
|
|
**Enum `status`**: `online`, `offline`
|
|
|
|
ID sugerido: `servers`
|
|
|
|
Após criar, copie o ID:
|
|
```
|
|
VITE_APPWRITE_COLLECTION_SERVERS_ID=servers
|
|
```
|
|
|
|
##### Collection 2: **github_repos**
|
|
|
|
| Campo | Tipo | Required | Array | Default |
|
|
|-------|------|----------|-------|---------|
|
|
| `repo_name` | String | Sim | Não | - |
|
|
| `url` | URL | Sim | Não | - |
|
|
| `last_commit` | String | Não | Não | - |
|
|
| `status` | String | Não | Não | `active` |
|
|
|
|
ID sugerido: `github_repos`
|
|
|
|
```
|
|
VITE_APPWRITE_COLLECTION_GITHUB_REPOS_ID=github_repos
|
|
```
|
|
|
|
##### Collection 3: **audit_logs**
|
|
|
|
| Campo | Tipo | Required | Array | Default |
|
|
|-------|------|----------|-------|---------|
|
|
| `event` | String | Sim | Não | - |
|
|
| `user_id` | String | Sim | Não | - |
|
|
| `timestamp` | DateTime | Sim | Não | - |
|
|
|
|
ID sugerido: `audit_logs`
|
|
|
|
**⚠️ Esta coleção é usada pelo Realtime Subscription no terminal do dashboard!**
|
|
|
|
```
|
|
VITE_APPWRITE_COLLECTION_AUDIT_LOGS_ID=audit_logs
|
|
```
|
|
|
|
##### Collection 4: **cloud_accounts**
|
|
|
|
| Campo | Tipo | Required | Array | Default |
|
|
|-------|------|----------|-------|---------|
|
|
| `provider` | String | Sim | Não | - |
|
|
| `apiKey` | String | Sim | Não | - |
|
|
| `label` | String | Não | Não | - |
|
|
|
|
ID sugerido: `cloud_accounts`
|
|
|
|
```
|
|
VITE_APPWRITE_COLLECTION_CLOUDFLARE_ACCOUNTS_ID=cloud_accounts
|
|
```
|
|
|
|
#### 5. Configurar Autenticação
|
|
|
|
1. No menu lateral, clique em **Auth**
|
|
2. Vá em **Settings**
|
|
3. Ative o provedor **Email/Password**
|
|
4. (Opcional) Configure limites de taxa e outras opções de segurança
|
|
|
|
#### 6. Criar Usuário de Teste
|
|
|
|
1. Em **Auth** → **Users**
|
|
2. Clique em **Create User**
|
|
3. Preencha:
|
|
- Email: `admin@test.com`
|
|
- Password: `admin123` (altere para algo seguro!)
|
|
- Name: `Admin User`
|
|
4. Clique em **Create**
|
|
|
|
#### 7. Implantar Functions (Opcional)
|
|
|
|
As funções estão em `appwrite-functions/`. Para implantá-las:
|
|
|
|
1. Instale a [Appwrite CLI](https://appwrite.io/docs/command-line)
|
|
2. Execute:
|
|
```bash
|
|
appwrite login
|
|
appwrite deploy function
|
|
```
|
|
3. Ou crie manualmente via Console:
|
|
- **Functions** → **Create Function**
|
|
- Faça upload do código de cada pasta em `appwrite-functions/`
|
|
|
|
Funções disponíveis:
|
|
- `hello-world`: Função exemplo
|
|
- `sync-github`: Sincroniza dados de repositórios GitHub
|
|
- `check-cloudflare-status`: Verifica status de contas Cloudflare
|
|
|
|
## 🏃 Executando o Projeto
|
|
|
|
### Desenvolvimento
|
|
|
|
#### Executar Tudo Junto
|
|
|
|
```bash
|
|
npm run dev:web
|
|
```
|
|
|
|
Isso inicia:
|
|
- **Landing** em http://localhost:8000
|
|
- **Dashboard** em http://localhost:5173
|
|
|
|
#### Executar Componentes Separadamente
|
|
|
|
**Landing (Fresh + Deno):**
|
|
```bash
|
|
npm run dev:landing
|
|
# Ou: cd landing && deno task start
|
|
```
|
|
Acesse: http://localhost:8000
|
|
|
|
**Dashboard (React + Vite):**
|
|
```bash
|
|
npm run dev:dashboard
|
|
# Ou: cd dashboard && npm run dev
|
|
```
|
|
Acesse: http://localhost:5173
|
|
|
|
Login no dashboard usa as credenciais criadas no Appwrite (ex: `admin@test.com` / `admin123`).
|
|
|
|
### Build para Produção
|
|
|
|
**Dashboard:**
|
|
```bash
|
|
cd dashboard
|
|
npm run build
|
|
```
|
|
Saída em `dashboard/dist/`
|
|
|
|
**Landing:**
|
|
```bash
|
|
cd landing
|
|
deno task build
|
|
```
|
|
|
|
## 📁 Estrutura do Projeto
|
|
|
|
```
|
|
core/
|
|
├── .env # Variáveis de ambiente (NÃO commitar!)
|
|
├── .env.example # Template de variáveis
|
|
├── package.json # Scripts raiz e npm-run-all
|
|
├── README.md # 📄 Este arquivo
|
|
├── SECURITY.md # Política de segurança
|
|
├── appwrite.json # Configuração Appwrite CLI
|
|
├── appwrite-databases-schema.md # Schema detalhado do banco
|
|
│
|
|
├── dashboard/ # 🎨 Painel React + Vite
|
|
│ ├── src/
|
|
│ │ ├── components/ # Componentes reutilizáveis
|
|
│ │ ├── pages/ # Páginas/rotas
|
|
│ │ ├── lib/ # SDK Appwrite, utilitários
|
|
│ │ ├── App.tsx # Componente raiz
|
|
│ │ └── main.tsx # Entry point
|
|
│ ├── package.json # Dependências do dashboard
|
|
│ ├── vite.config.ts # Configuração Vite
|
|
│ ├── tailwind.config.js # Configuração Tailwind
|
|
│ └── README.md # Documentação específica
|
|
│
|
|
├── landing/ # 🚀 Landing Page (Fresh + Deno)
|
|
│ ├── routes/ # Rotas Fresh
|
|
│ ├── islands/ # Componentes interativos (ilhas)
|
|
│ ├── components/ # Componentes estáticos
|
|
│ ├── static/ # Arquivos estáticos
|
|
│ ├── deno.json # Configuração e tarefas Deno
|
|
│ ├── fresh.config.ts # Configuração Fresh
|
|
│ ├── main.ts # Entry point
|
|
│ └── README.md # Documentação específica
|
|
│
|
|
└── appwrite-functions/ # ⚡ Funções Serverless
|
|
├── hello-world/
|
|
├── sync-github/
|
|
└── check-cloudflare-status/
|
|
```
|
|
|
|
## 📜 Scripts Disponíveis
|
|
|
|
### Raiz
|
|
|
|
| Script | Comando | Descrição |
|
|
|--------|---------|-----------|
|
|
| `dev:dashboard` | `npm run dev:dashboard` | Inicia somente o dashboard |
|
|
| `dev:landing` | `npm run dev:landing` | Inicia somente a landing |
|
|
| `dev:web` | `npm run dev:web` | Inicia dashboard + landing em paralelo |
|
|
| `lint:dashboard` | `npm run lint:dashboard` | Executa ESLint no dashboard |
|
|
|
|
### Dashboard (`cd dashboard`)
|
|
|
|
| Script | Comando | Descrição |
|
|
|--------|---------|-----------|
|
|
| `dev` | `npm run dev` | Inicia dev server Vite (porta 5173) |
|
|
| `build` | `npm run build` | Compila TypeScript + build otimizado |
|
|
| `preview` | `npm run preview` | Testa build de produção localmente |
|
|
| `lint` | `npm run lint` | Verifica código com ESLint |
|
|
|
|
### Landing (`cd landing`)
|
|
|
|
| Script | Comando | Descrição |
|
|
|--------|---------|-----------|
|
|
| `start` | `deno task start` | Inicia dev server Fresh (porta 8000) |
|
|
| `build` | `deno task build` | Gera build de produção |
|
|
| `preview` | `deno task preview` | Serve build de produção |
|
|
| `check` | `deno task check` | Formata, lint e type-check |
|
|
|
|
## ✅ Verificação e Testes
|
|
|
|
### Checklist de Instalação
|
|
|
|
Execute estes comandos para verificar se tudo está configurado corretamente:
|
|
|
|
```bash
|
|
# 1. Verificar versões
|
|
node --version # Deve ser >= 18
|
|
npm --version # Deve ser >= 9
|
|
deno --version # Deve ser >= 1.40
|
|
|
|
# 2. Verificar instalação de dependências
|
|
npm ls npm-run-all # Raiz
|
|
cd dashboard && npm ls appwrite # Dashboard
|
|
cd ../landing && deno info # Landing
|
|
|
|
# 3. Testar build do dashboard
|
|
cd dashboard
|
|
npm run build
|
|
# Deve gerar pasta dist/ sem erros
|
|
|
|
# 4. Testar lint
|
|
npm run lint
|
|
# Deve passar sem erros (warnings ok)
|
|
|
|
# 5. Testar landing page
|
|
cd ../landing
|
|
deno task check
|
|
# Deve passar formatting, linting e type-check
|
|
|
|
# 6. Verificar arquivo .env
|
|
cat ../.env
|
|
# Deve ter todos os IDs preenchidos (não vazios)
|
|
```
|
|
|
|
### Testes Manuais
|
|
|
|
1. **Dashboard (http://localhost:5173)**:
|
|
- Login deve funcionar com usuário criado no Appwrite
|
|
- Overview deve mostrar widgets de servidores, repos e logs
|
|
- Terminal inferior deve conectar ao Realtime (audit_logs)
|
|
|
|
2. **Landing (http://localhost:8000)**:
|
|
- Página deve carregar sem erros
|
|
- Navegação deve funcionar
|
|
- Componentes interativos (Counter, ServerStatus) devem responder
|
|
|
|
## 🔧 Troubleshooting
|
|
|
|
### Erro: "Cannot find module 'appwrite'"
|
|
|
|
**Solução:**
|
|
```bash
|
|
cd dashboard
|
|
npm install
|
|
```
|
|
|
|
### Erro: "deno: command not found"
|
|
|
|
**Solução:**
|
|
```bash
|
|
# Linux/Mac
|
|
curl -fsSL https://deno.land/install.sh | sh
|
|
|
|
# Windows (PowerShell)
|
|
irm https://deno.land/install.ps1 | iex
|
|
|
|
# Adicione ao PATH (Linux/Mac):
|
|
echo 'export PATH="$HOME/.deno/bin:$PATH"' >> ~/.bashrc
|
|
source ~/.bashrc
|
|
```
|
|
|
|
### Dashboard não conecta ao Appwrite
|
|
|
|
**Checklist:**
|
|
1. Arquivo `.env` existe e tem variáveis `VITE_*` preenchidas?
|
|
2. Project ID está correto?
|
|
3. Database existe no Appwrite Cloud?
|
|
4. Collections foram criadas com os IDs corretos?
|
|
5. Usuário de autenticação foi criado?
|
|
|
|
**Debug:**
|
|
```javascript
|
|
// No console do browser (F12)
|
|
console.log(import.meta.env.VITE_APPWRITE_PROJECT_ID)
|
|
// Deve mostrar seu Project ID, não "undefined"
|
|
```
|
|
|
|
### Erro: "Failed to fetch" no dashboard
|
|
|
|
**Possível causa**: CORS ou endpoint incorreto.
|
|
|
|
**Solução:**
|
|
1. Verifique se `VITE_APPWRITE_ENDPOINT` está correto: `https://cloud.appwrite.io/v1`
|
|
2. No Appwrite Console → Settings → Platforms, adicione:
|
|
- **Web Platform** com hostname `localhost`
|
|
|
|
### Landing page não carrega dependências
|
|
|
|
**Solução:**
|
|
```bash
|
|
cd landing
|
|
# Limpar cache do Deno
|
|
deno cache --reload dev.ts
|
|
# Tentar novamente
|
|
deno task start
|
|
```
|
|
|
|
### Build do dashboard falha
|
|
|
|
**Erro comum**: TypeScript errors
|
|
|
|
**Solução:**
|
|
```bash
|
|
cd dashboard
|
|
# Verificar erros de tipo
|
|
npx tsc --noEmit
|
|
# Se muitos erros, verifique versões:
|
|
npm ls typescript
|
|
npm ls @types/react
|
|
```
|
|
|
|
## 🚀 Deploy
|
|
|
|
### Dashboard (Vite App)
|
|
|
|
**Opções recomendadas**:
|
|
- [Vercel](https://vercel.com) (zero config)
|
|
- [Netlify](https://netlify.com)
|
|
- [Cloudflare Pages](https://pages.cloudflare.com)
|
|
|
|
```bash
|
|
cd dashboard
|
|
npm run build
|
|
# Upload da pasta dist/ para seu provider
|
|
```
|
|
|
|
**Importante**: Configure as variáveis `VITE_*` no painel do provider!
|
|
|
|
### Landing (Deno Fresh)
|
|
|
|
**Opções recomendadas**:
|
|
- [Deno Deploy](https://deno.com/deploy) (nativo Fresh)
|
|
- [Fly.io](https://fly.io)
|
|
|
|
```bash
|
|
cd landing
|
|
deno task build
|
|
# Ou deploy direto para Deno Deploy
|
|
```
|
|
|
|
### Appwrite Functions
|
|
|
|
Via Appwrite CLI:
|
|
```bash
|
|
appwrite deploy function
|
|
```
|
|
|
|
Ou manualmente via Appwrite Console → Functions.
|
|
|
|
## 📚 Recursos Adicionais
|
|
|
|
- [Documentação Appwrite](https://appwrite.io/docs)
|
|
- [Documentação Fresh](https://fresh.deno.dev/docs)
|
|
- [Documentação Vite](https://vitejs.dev)
|
|
- [Documentação React](https://react.dev)
|
|
- [Deno Manual](https://deno.land/manual)
|
|
|
|
## 🔐 Segurança
|
|
|
|
- **NUNCA** commite o arquivo `.env`
|
|
- API Keys devem ter scopes mínimos necessários em produção
|
|
- Habilite MFA no Appwrite Console
|
|
- Revise `SECURITY.md` para reportar vulnerabilidades
|
|
|
|
## 📝 Licença
|
|
|
|
Este projeto está sob a licença [MIT](LICENSE) (ou especifique sua licença).
|
|
|
|
---
|
|
|
|
**Desenvolvido com ❤️ usando Appwrite Cloud, Fresh, React e Deno**
|