commit 877eef7f07790f21bd39f1d4c3efea5823bf8475 Author: Davidson Gomes Date: Wed Mar 25 12:40:16 2026 -0300 release: v0.6.1 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8acf18f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,48 @@ +# Git +.git +.gitignore + +# Documentation +README.md +# docs/ - Mantido porque docs/docs.go é necessário para o build (gerado pelo swagger) +docs/wiki/ + +# Logs +logs/ + +# IDE +.vscode/ +.idea/ + +# OS +.DS_Store +Thumbs.db + +# Build artifacts +server +build/ + +# Docker +Dockerfile +.dockerignore +docker/ + +# Scripts +*.sh +Makefile + +# Test files +*_test.go +*.test + +# Manager/dist é necessário - serve arquivos estáticos do frontend React +# Não excluir - precisa estar na imagem final para ser acessado via /manager + +# Keep these important files/folders for build: +# - whatsmeow/ (nossa versão local modificada) +# - go.mod, go.sum (dependências) +# - pkg/, cmd/ (código fonte necessário para compilar) +# - docs/docs.go (gerado pelo swagger, necessário para build) + +# IMPORTANT: O código-fonte (pkg/, cmd/, etc.) é necessário no stage de build +# mas NÃO é copiado para a imagem final - apenas o executável compilado vai. \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..831e431 --- /dev/null +++ b/.env.example @@ -0,0 +1,29 @@ +SERVER_PORT=8080 + +POSTGRES_AUTH_DB=postgresql://postgres:root@localhost:5432/evogo_auth?sslmode=disable +POSTGRES_USERS_DB=postgresql://postgres:root@localhost:5432/evogo_users?sslmode=disable +DATABASE_SAVE_MESSAGES=false +CLIENT_NAME=evolution + +GLOBAL_API_KEY=429683C4C977415CAAFCCE10F7D57E11 + +WADEBUG=DEBUG +LOGTYPE=console +WEBHOOKFILES=true + +CONNECT_ON_STARTUP=true + +OS_NAME=Evolution GO + +AMQP_URL=amqp://admin:admin@localhost:5672/default +AMQP_GLOBAL_ENABLED=false + +WEBHOOK_URL=https://webhook.site/2e6af2fa-6b04-497f-b4a1-13a905728d83 + +# Minio Configuration +MINIO_ENABLED=true +MINIO_ENDPOINT=localhost:9000 +MINIO_ACCESS_KEY=minioadmin +MINIO_SECRET_KEY=minioadmin +MINIO_BUCKET=evolution-media +MINIO_USE_SSL=false \ No newline at end of file diff --git a/.github/workflows/publish_docker_image.yml b/.github/workflows/publish_docker_image.yml new file mode 100644 index 0000000..852fdb5 --- /dev/null +++ b/.github/workflows/publish_docker_image.yml @@ -0,0 +1,55 @@ +name: Build and Publish Docker Image + +on: + push: + branches: + - main + tags: + - "*.*.*" + +jobs: + build_deploy: + name: Build and Deploy + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: evoapicloud/evolution-go + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=raw,value=latest,enable={{is_default_branch}} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Build and push + id: docker_build + uses: docker/build-push-action@v5 + with: + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Image digest + run: echo ${{ steps.docker_build.outputs.digest }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..587b9ae --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.env +logs/* +build/ +*.prof +coverage.* +.air.toml +.idea/ +.vscode/ +.DS_Store +.cursorrules diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..031fa45 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,245 @@ +# Evolution GO - Changelog + +## v0.6.1 + +### 🆕 New Features +- **Group invite info endpoint** — `GET /group/invite-info` to get group details from invite link +- **Enhanced media sending** — GIF playback, video stickers, and transparent sticker support + +### 🐛 Bug Fixes +- **Admin revoke** — Allow deleting messages from others in groups (admin revoke) + +### 🔧 Improvements +- **Version management** — Reads version from `VERSION` file with ldflags fallback +- **CORS global middleware** — Applied before all routes +- **Makefile compatibility** — Fixed `$(shell)` syntax for GNU Make 3.81 (macOS default) +- **CI/CD cleanup** — Removed `develop` branch trigger and `homolog` tag from Docker workflow +- **README updated** — New links, documentation, and hosting info + +## v0.6.0 + +### 🆕 New Features +- **Version from VERSION file** — Reads version from `VERSION` file at startup instead of hardcoded value + +### 🔧 Improvements +- **Makefile compatibility** — Fixed `$(shell)` syntax for GNU Make 3.81 (macOS default) + +## v0.5.4 + +### 🔧 Improvements +- **Update whatsmeow lib** + +## v0.5.3 + +**Docker:** `evoapicloud/evolution-go:0.5.3` + +### 🔧 Improvements + +- **Update context handling in service methods** + - Refactored multiple service methods across various packages to include `context.Background()` as the first argument in client calls. This change ensures that all client interactions are properly context-aware, allowing for better cancellation and timeout management. + - Updated methods in `call_service.go`, `community_service.go`, `group_service.go`, `message_service.go`, `newsletter_service.go`, `send_service.go`, `user_service.go`, and `whatsmeow.go` to enhance consistency and reliability in handling requests. + - This adjustment improves the overall robustness of the API by ensuring that all client calls can leverage context for better control over execution flow and resource management. + +## v0.5.2 + +**Docker:** `evoapicloud/evolution-go:0.5.2` + +### 🆕 New Features +- **SetProxy Endpoint**: New endpoint `POST /instance/proxy/{instanceId}` to configure proxy for instances + - Support for proxy with/without authentication + - Validation of required fields (host, port) + - Automatic cache update via reconnection + - Integrated Swagger documentation + +### 🔧 Improvements +- **CheckUser Fallback Logic**: Implemented intelligent fallback logic + - If `formatJid=true` returns `IsInWhatsapp=false`, automatically retries with `formatJid=false` + - Significant improvement in valid user detection + - Added `RemoteJID` field to use WhatsApp-validated JID +- **LID/WhatsApp JID Swap**: Automatic handling of special cases + - When `Sender` comes as `@lid` and `SenderAlt` comes as `@s.whatsapp.net` + - Automatic inversion: `Sender` and `Chat` receive `@s.whatsapp.net`, `SenderAlt` receives `@lid` + - Detailed logs for tracking swaps + +### 🐛 Bug Fixes +- **SendMessage**: Standardization of WhatsApp-validated `remoteJID` usage +- **User Validation**: Improvement in phone number validation and formatting + +--- + +## v0.5.1 + +**Docker:** `evoapicloud/evolution-go:0.5.1` + +### 🔧 Improvements +- **Instance Deletion**: Enhance instance deletion and media storage path resolution +- **Media Storage**: Improvements in media storage and path resolution + +--- + +## v0.5.0 + +**Docker:** `evoapicloud/evolution-go:0.5.0` + +### 🔧 Improvements +- **Media Storage**: Enhance media storage and logging in Whatsmeow event handling +- **Retry Logic**: Implement retry logic for client connection and message sending +- **Media Handling**: Enhance media handling in event processing + +--- + +## v0.4.9 + +**Docker:** `evoapicloud/evolution-go:0.4.9` + +### 🔧 Improvements +- **Connection Handling**: Add instance update test scenarios and improve connection handling +- **FormatJid Field**: Update FormatJid field to pointer type for better handling in message structures +- **Dependencies**: Update dependencies and fix presence handling in Whatsmeow integration + +--- + +## v0.4.8 + +**Docker:** `evoapicloud/evolution-go:0.4.8` + +### 🔧 Improvements +- **Audio Duration**: Improve audio duration parsing in convertAudioToOpusWithDuration function + +--- + +## v0.4.7 + +**Docker:** `evoapicloud/evolution-go:0.4.7` + +### 🔧 Improvements +- **Phone Number Formatting**: Improve phone number formatting and validation in user service +- **Brazilian/Portuguese Numbers**: Update Brazilian and Portuguese number formatting in utils + +### 🆕 New Features +- **Media Handling**: Enhance media handling in event processing + +--- + +## v0.4.6 + +**Docker:** `evoapicloud/evolution-go:0.4.6` + +### 🆕 New Features +- **User Existence Check**: Add user existence check configuration and JID validation middleware + +--- + +## v0.4.5 + +**Docker:** `evoapicloud/evolution-go:0.4.5` + +### 🔧 Improvements +- **Dependencies**: Update dependencies and enhance audio conversion functionality + +--- + +## v0.4.4 + +**Docker:** `evoapicloud/evolution-go:0.4.4` + +### 🆕 New Features +- **CLAUDE.md**: Add CLAUDE.md for project documentation and enhance RabbitMQ connection handling + +--- + +## v0.4.3 + +**Docker:** `evoapicloud/evolution-go:0.4.3` + +### 🔧 Improvements +- **PostgreSQL Connection**: Fix in PostgreSQL connection configuration for session auth + - Controlled configuration of pool, idle, etc. + - Adjustment on top of whatsmeow lib +- **User Endpoints**: Fix in 'User Info' and 'Check User' endpoints + - Now return with contact's LID information + +--- + +## v0.3.0 + +### 🆕 New Features +- **Own Message Reactions**: Additional 'fromMe' parameter using Chat id +- **CreatedAt Field**: CreatedAt field added to instances table + +--- + +## v0.2.0 + +### 🆕 New Features +- **Advanced Settings**: Advanced configurations in instance creation + - `alwaysOnline` (still to be implemented) + - `rejectCall` - Automatically reject calls + - `msgRejectCall` - Call rejection message + - `readMessages` - Automatically mark messages as read + - `ignoreGroups` - Ignore group messages + - `ignoreStatus` - Ignore status messages +- **Advanced Settings Routes**: New routes for get and update of advanced settings +- **QR Code Control**: `QRCODE_MAX_COUNT` variable to control how many QR codes to generate before timeout +- **AMQP Events**: `AMQP_SPECIFIC_EVENTS` variable to individually select which events to receive in RabbitMQ + +### 🔧 Improvements +- **Reconnect Endpoint**: Fix in reconnect endpoint +- **Sender Info**: `Sender` and `SenderAlt` no longer come with session id, only the id + +### 🐛 Bug Fixes +- **QR Code Generation**: Fix to not generate QR code automatically after disconnection or logout + +--- + +## v0.1.0 + +### 🆕 Initial Features +- Base implementation of Evolution API in Go +- WhatsApp integration via whatsmeow +- Instance system +- Basic message sending endpoints +- Webhook support +- RabbitMQ and NATS integration +- Authentication system +- Swagger documentation + +--- + +## 📋 Migration Notes + +### v0.5.2 +- The new `SetProxy` endpoint requires admin permissions (`AuthAdmin`) +- The `CheckUser` fallback logic is automatic and transparent +- LID/WhatsApp JID handling is automatic + +### v0.4.3 +- Check PostgreSQL connection settings if using postgres auth + +### v0.2.0 +- Review advanced settings configurations if necessary +- Configure `QRCODE_MAX_COUNT` if you want to limit QR codes +- Configure `AMQP_SPECIFIC_EVENTS` for specific RabbitMQ events + +--- + +## 🔗 Useful Links + +- **Docker Hub**: `evoapicloud/evolution-go` +- **Documentation**: Swagger available at `/swagger/` +- **GitHub**: [Evolution API Go](https://github.com/EvolutionAPI/evolution-go) + +--- + +## 🤝 Contributing + +To contribute to the project: +1. Fork the repository +2. Create a branch for your feature +3. Commit your changes +4. Open a Pull Request + +--- + +*Last updated: October 2025* + diff --git a/COMMANDS.md b/COMMANDS.md new file mode 100644 index 0000000..4da3244 --- /dev/null +++ b/COMMANDS.md @@ -0,0 +1,265 @@ +# 🚀 Guia Rápido de Comandos + +Comandos mais usados no dia a dia de desenvolvimento do Evolution GO. + +## 📋 Comandos Essenciais + +### Desenvolvimento + +```bash +# Ver todos os comandos disponíveis +make help + +# Rodar em modo desenvolvimento +make dev + +# Rodar com hot reload (recarrega automaticamente ao salvar) +make watch +``` + +### Build e Instalação + +```bash +# Compilar a aplicação +make build + +# Compilar para todas as plataformas (Linux, Windows, macOS) +make build-all + +# Instalar no GOPATH +make install +``` + +### Testes + +```bash +# Rodar todos os testes +make test + +# Rodar testes com relatório de cobertura +make test-coverage + +# Rodar testes com verificação de race conditions +make test-race + +# Rodar benchmarks +make bench +``` + +### Qualidade de Código + +```bash +# Formatar código +make fmt + +# Executar linter +make lint + +# Executar go vet +make vet + +# Executar todas as verificações (fmt + vet + lint + test) +make check +``` + +### Docker + +```bash +# Build da imagem Docker +make docker-build + +# Rodar container Docker +make docker-run + +# Iniciar todos os serviços com docker-compose +make docker-compose-up + +# Parar todos os serviços +make docker-compose-down + +# Ver logs do docker-compose +make docker-compose-logs +``` + +### Banco de Dados + +```bash +# Executar migrations +make migrate-up + +# Reverter migrations +make migrate-down +``` + +### Documentação + +```bash +# Gerar documentação Swagger +make swagger + +# Abrir documentação local +make docs +``` + +### Dependências + +```bash +# Instalar dependências +make deps + +# Atualizar dependências +make deps-update + +# Limpar dependências não utilizadas +make deps-clean +``` + +### Limpeza + +```bash +# Remover arquivos de build +make clean + +# Limpeza completa (incluindo cache do Go) +make clean-all +``` + +## 🎯 Workflows Comuns + +### Setup Inicial + +```bash +# 1. Clone o repositório +git clone https://git.evoai.app/Evolution/evolution-go.git +cd evolution-go + +# 2. Setup completo do ambiente +make setup + +# 3. Configure o .env +cp .env.example .env +# Edite o .env com suas configurações + +# 4. Rode em modo desenvolvimento +make dev +``` + +### Desenvolvimento Diário + +```bash +# Rodar com hot reload +make watch + +# Em outro terminal, rodar testes em watch mode +# (requer: go install github.com/cespare/reflex@latest) +reflex -r '\.go$' -s -- make test +``` + +### Antes de Fazer Commit + +```bash +# Executar todas as verificações +make check + +# Se tudo passar, commit e push +git add . +git commit -m "feat: sua feature" +git push +``` + +### Preparar para Deploy + +```bash +# 1. Rodar todos os testes +make test + +# 2. Build da imagem Docker +make docker-build + +# 3. Testar localmente +make docker-run + +# 4. Se tudo ok, fazer tag e push +docker tag evolution-go:latest seu-registry/evolution-go:v1.0.0 +docker push seu-registry/evolution-go:v1.0.0 +``` + +### Debug e Profiling + +```bash +# Ver status da aplicação +make status + +# Ver logs em tempo real +make logs + +# Profile de CPU (aplicação deve estar rodando) +make profile-cpu + +# Profile de memória (aplicação deve estar rodando) +make profile-mem + +# Ver informações de versão +make version +``` + +## 🔧 Ferramentas Opcionais + +Instale estas ferramentas para habilitar recursos adicionais: + +```bash +# Hot reload +go install github.com/cosmtrek/air@latest + +# Linter +go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest + +# Swagger generator +go install github.com/swaggo/swag/cmd/swag@latest + +# Watch mode para testes +go install github.com/cespare/reflex@latest +``` + +## 💡 Dicas + +1. **Use `make help`** sempre que esquecer um comando +2. **Use `make watch`** durante desenvolvimento para hot reload automático +3. **Use `make check`** antes de fazer commit +4. **Use `make setup`** em uma nova máquina para configurar tudo de uma vez +5. **Configure seu IDE** para rodar `make fmt` ao salvar arquivos + +## 📚 Documentação Completa + +Para documentação completa da API e guias detalhados: + +- **[Documentação Oficial](./docs/wiki/README.md)** - Guias, tutoriais e referência +- **[API Swagger](http://localhost:4000/swagger/index.html)** - Documentação interativa (quando servidor estiver rodando) + +## ❓ Problemas Comuns + +### "make: command not found" +- **macOS**: `xcode-select --install` +- **Ubuntu/Debian**: `sudo apt-get install build-essential` +- **Windows**: Use WSL ou instale Make para Windows + +### "air: command not found" ao usar `make watch` +```bash +go install github.com/cosmtrek/air@latest +``` + +### "golangci-lint: command not found" ao usar `make lint` +```bash +go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest +``` + +### Porta 4000 já em uso +```bash +# Mude a porta no .env +SERVER_PORT=8080 +``` + +--- + +**Dica Final**: Rode `make help` para ver a lista completa e atualizada de comandos! + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..8ad0e7a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,33 @@ +FROM golang:1.25.0-alpine AS build + +RUN apk update && apk add --no-cache git build-base libjpeg-turbo-dev libwebp-dev + +WORKDIR /build + +# Copiar apenas arquivos de dependências primeiro para cachear o download +COPY go.mod go.sum ./ + +# Copiar whatsmeow-lib que é uma dependência local +COPY whatsmeow-lib/ ./whatsmeow-lib/ + +# Agora fazer download das dependências (com replace funcionando) +RUN go mod download + +# Copiar o restante do código +COPY . . + +ARG VERSION=dev +RUN CGO_ENABLED=1 go build -ldflags "-X main.version=${VERSION}" -o server ./cmd/evolution-go + +FROM alpine:3.19.1 AS final + +RUN apk update && apk add --no-cache tzdata ffmpeg libjpeg-turbo libwebp + +WORKDIR /app + +COPY --from=build /build/server . +COPY --from=build /build/manager/dist ./manager/dist + +ENV TZ=America/Sao_Paulo + +ENTRYPOINT ["/app/server"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2eb13cb --- /dev/null +++ b/LICENSE @@ -0,0 +1,222 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (which shall not include communications that are solely written + by copyright holders to be excluded from the License). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based upon (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and derivative works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control + systems, and issue tracking systems that are managed by, or on behalf + of, the Licensor for the purpose of discussing and improving the Work, + but excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to use, reproduce, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Work, and to + permit persons to whom the Work is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Work. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright notice to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Support. You may choose to offer, and to + charge a fee for, warranty, support, indemnity or other liability + obligations and/or rights consistent with this License. However, in + accepting such obligations, You may act only on Your own behalf and + on Your sole responsibility, not on behalf of any other Contributor, + and only if You agree to indemnify, defend, and hold each Contributor + harmless for any liability incurred by, or claims asserted against, + such Contributor by reason of your accepting any such warranty or support. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same page as the copyright notice for easier identification within + third-party archives. + + Copyright 2025 Evolution API + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +ADDITIONAL CONDITIONS: + +1. LOGO and copyright information: In the process of using Evolution Go API's + frontend components, you may not remove or modify the LOGO or copyright + information in the Evolution API console or applications. This restriction + is inapplicable to uses of Evolution Go API that do not involve its frontend + components. + +2. Usage Notification Requirement: If Evolution Go API is used as part of any + project, including closed-source systems (e.g., proprietary software), the + user is required to display a clear notification within the system that + Evolution Go API is being utilized. This notification should be visible to + system administrators and accessible from the system's documentation or + settings page. Failure to comply with this requirement may result in the + necessity for a commercial license, as determined by the producer. + +Please contact contato@evolution-api.com to inquire about licensing matters. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1134d2d --- /dev/null +++ b/Makefile @@ -0,0 +1,268 @@ +.PHONY: help dev run build test clean swagger deps docker-build docker-run install setup migrate-up migrate-down logs + +# Configurações +APP_NAME=evolution-go +MAIN_PATH=cmd/evolution-go/main.go +BUILD_DIR=build +GO=go +VERSION=$(shell grep -om1 "v[0-9].*" CHANGELOG.md) +LDFLAGS=-ldflags "-X main.version=$(VERSION)" +GOFLAGS=-v + +# Cores para output +GREEN=\033[0;32m +YELLOW=\033[0;33m +RED=\033[0;31m +NC=\033[0m # No Color + +##@ Ajuda + +help: ## Exibe esta mensagem de ajuda + @echo "$(GREEN)Evolution GO - Makefile$(NC)" + @echo "" + @awk 'BEGIN {FS = ":.*##"; printf "\nUso:\n make $(YELLOW)$(NC)\n"} /^[a-zA-Z_-]+:.*?##/ { printf " $(GREEN)%-15s$(NC) %s\n", $$1, $$2 } /^##@/ { printf "\n$(YELLOW)%s$(NC)\n", substr($$0, 5) } ' $(MAKEFILE_LIST) + +##@ Desenvolvimento + +dev: ## Roda a aplicação em modo desenvolvimento + @echo "$(GREEN)🚀 Rodando Evolution GO em modo desenvolvimento...$(NC)" + $(GO) run $(LDFLAGS) $(MAIN_PATH) -dev + +run: ## Roda a aplicação em modo produção + @echo "$(GREEN)🚀 Rodando Evolution GO...$(NC)" + $(GO) run $(MAIN_PATH) + +watch: ## Roda a aplicação com hot reload (requer air) + @if command -v air > /dev/null; then \ + echo "$(GREEN)🔥 Rodando com hot reload...$(NC)"; \ + air; \ + else \ + echo "$(RED)❌ Air não instalado. Instale com: go install github.com/cosmtrek/air@latest$(NC)"; \ + exit 1; \ + fi + +##@ Build + +build: ## Compila a aplicação + @echo "$(GREEN)🔨 Compilando $(APP_NAME)...$(NC)" + @mkdir -p $(BUILD_DIR) + $(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME) $(MAIN_PATH) + @echo "$(GREEN)✅ Build completo: $(BUILD_DIR)/$(APP_NAME)$(NC)" + +build-linux: ## Compila para Linux + @echo "$(GREEN)🔨 Compilando para Linux...$(NC)" + @mkdir -p $(BUILD_DIR) + GOOS=linux GOARCH=amd64 $(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-linux-amd64 $(MAIN_PATH) + @echo "$(GREEN)✅ Build Linux completo$(NC)" + +build-windows: ## Compila para Windows + @echo "$(GREEN)🔨 Compilando para Windows...$(NC)" + @mkdir -p $(BUILD_DIR) + GOOS=windows GOARCH=amd64 $(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-windows-amd64.exe $(MAIN_PATH) + @echo "$(GREEN)✅ Build Windows completo$(NC)" + +build-all: build build-linux build-windows ## Compila para todas as plataformas + @echo "$(GREEN)✅ Todos os builds completos$(NC)" + +install: build ## Compila e instala no GOPATH + @echo "$(GREEN)📦 Instalando $(APP_NAME)...$(NC)" + $(GO) install $(MAIN_PATH) + @echo "$(GREEN)✅ Instalado com sucesso$(NC)" + +##@ Testes + +test: ## Roda todos os testes + @echo "$(GREEN)🧪 Rodando testes...$(NC)" + $(GO) test -v ./... + +test-coverage: ## Roda testes com cobertura + @echo "$(GREEN)🧪 Rodando testes com cobertura...$(NC)" + $(GO) test -v -coverprofile=coverage.out ./... + $(GO) tool cover -html=coverage.out -o coverage.html + @echo "$(GREEN)✅ Cobertura gerada: coverage.html$(NC)" + +test-race: ## Roda testes verificando race conditions + @echo "$(GREEN)🧪 Rodando testes com race detector...$(NC)" + $(GO) test -race -v ./... + +bench: ## Roda benchmarks + @echo "$(GREEN)⚡ Rodando benchmarks...$(NC)" + $(GO) test -bench=. -benchmem ./... + +##@ Dependências + +deps: ## Instala dependências + @echo "$(GREEN)📦 Instalando dependências...$(NC)" + $(GO) mod download + $(GO) mod verify + @echo "$(GREEN)✅ Dependências instaladas$(NC)" + +deps-update: ## Atualiza dependências + @echo "$(GREEN)📦 Atualizando dependências...$(NC)" + $(GO) get -u ./... + $(GO) mod tidy + @echo "$(GREEN)✅ Dependências atualizadas$(NC)" + +deps-clean: ## Limpa dependências não utilizadas + @echo "$(GREEN)🧹 Limpando dependências...$(NC)" + $(GO) mod tidy + @echo "$(GREEN)✅ Dependências limpas$(NC)" + +deps-reset: ## Limpa cache e reinstala dependências (força uso do código local) + @echo "$(GREEN)🔄 Resetando dependências e cache...$(NC)" + @echo "$(YELLOW)Limpeza de cache e módulos...$(NC)" + $(GO) clean -cache -modcache -i -r + @echo "$(YELLOW)Download de módulos...$(NC)" + $(GO) mod download + @echo "$(YELLOW)Organizando módulos...$(NC)" + $(GO) mod tidy + @echo "$(GREEN)✅ Dependências resetadas e atualizadas$(NC)" + +##@ Documentação + +swagger: ## Gera documentação Swagger + @echo "$(GREEN)📚 Gerando documentação Swagger...$(NC)" + @if command -v swag > /dev/null; then \ + swag init -g $(MAIN_PATH) -o ./docs; \ + echo "$(GREEN)✅ Swagger gerado com sucesso$(NC)"; \ + else \ + echo "$(RED)❌ Swag não instalado. Instale com: go install github.com/swaggo/swag/cmd/swag@latest$(NC)"; \ + exit 1; \ + fi + +docs: ## Abre a documentação local + @echo "$(GREEN)📖 Abrindo documentação...$(NC)" + @if [ -f "docs/wiki/README.md" ]; then \ + echo "Documentação disponível em: docs/wiki/README.md"; \ + else \ + echo "$(RED)❌ Documentação não encontrada$(NC)"; \ + fi + +##@ Database + +migrate-up: ## Executa migrations do banco de dados + @echo "$(GREEN)🗃️ Executando migrations...$(NC)" + @if [ -d "migrations" ]; then \ + $(GO) run $(MAIN_PATH) migrate up; \ + else \ + echo "$(YELLOW)⚠️ Diretório migrations não encontrado$(NC)"; \ + fi + +migrate-down: ## Reverte migrations do banco de dados + @echo "$(YELLOW)⚠️ Revertendo migrations...$(NC)" + @if [ -d "migrations" ]; then \ + $(GO) run $(MAIN_PATH) migrate down; \ + else \ + echo "$(YELLOW)⚠️ Diretório migrations não encontrado$(NC)"; \ + fi + +##@ Docker + +docker-build: ## Build da imagem Docker + @echo "$(GREEN)🐳 Construindo imagem Docker...$(NC)" + docker build --build-arg VERSION=$(VERSION) -t $(APP_NAME):latest . + @echo "$(GREEN)✅ Imagem Docker construída$(NC)" + +docker-run: ## Roda container Docker + @echo "$(GREEN)🐳 Iniciando container...$(NC)" + docker run -p 4000:4000 --env-file .env $(APP_NAME):latest + +docker-compose-up: ## Sobe todos os serviços com docker-compose + @echo "$(GREEN)🐳 Iniciando serviços com docker-compose...$(NC)" + docker-compose up -d + +docker-compose-down: ## Para todos os serviços do docker-compose + @echo "$(YELLOW)🐳 Parando serviços...$(NC)" + docker-compose down + +docker-compose-logs: ## Exibe logs do docker-compose + docker-compose logs -f + +##@ Linting e Formatação + +fmt: ## Formata o código + @echo "$(GREEN)✨ Formatando código...$(NC)" + $(GO) fmt ./... + @echo "$(GREEN)✅ Código formatado$(NC)" + +lint: ## Executa linter (requer golangci-lint) + @echo "$(GREEN)🔍 Executando linter...$(NC)" + @if command -v golangci-lint > /dev/null; then \ + golangci-lint run ./...; \ + echo "$(GREEN)✅ Lint completo$(NC)"; \ + else \ + echo "$(RED)❌ golangci-lint não instalado. Instale com: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest$(NC)"; \ + exit 1; \ + fi + +vet: ## Executa go vet + @echo "$(GREEN)🔍 Executando go vet...$(NC)" + $(GO) vet ./... + @echo "$(GREEN)✅ Vet completo$(NC)" + +check: fmt vet lint test ## Executa todas as verificações + +##@ Limpeza + +clean: ## Remove arquivos de build + @echo "$(YELLOW)🧹 Limpando arquivos de build...$(NC)" + @rm -rf $(BUILD_DIR) + @rm -f coverage.out coverage.html + @echo "$(GREEN)✅ Limpeza completa$(NC)" + +clean-all: clean ## Remove arquivos de build e cache + @echo "$(YELLOW)🧹 Limpeza completa (incluindo cache)...$(NC)" + $(GO) clean -cache -testcache -modcache + @echo "$(GREEN)✅ Limpeza completa$(NC)" + +##@ Utilitários + +setup: deps swagger ## Setup completo do ambiente de desenvolvimento + @echo "$(GREEN)🎉 Setup completo!$(NC)" + @echo "" + @echo "Para começar a desenvolver, rode:" + @echo " $(YELLOW)make dev$(NC)" + @echo "" + @echo "Outros comandos úteis:" + @echo " $(YELLOW)make help$(NC) - Ver todos os comandos" + @echo " $(YELLOW)make test$(NC) - Rodar testes" + @echo " $(YELLOW)make build$(NC) - Compilar a aplicação" + +logs: ## Exibe logs da aplicação (se estiver rodando) + @echo "$(GREEN)📋 Exibindo logs...$(NC)" + @if [ -f "logs/app.log" ]; then \ + tail -f logs/app.log; \ + else \ + echo "$(YELLOW)⚠️ Arquivo de log não encontrado$(NC)"; \ + fi + +version: ## Exibe versão do Go e dependências + @echo "$(GREEN)📌 Versões:$(NC)" + @$(GO) version + @echo "" + @echo "$(GREEN)Dependências principais:$(NC)" + @$(GO) list -m all | grep -E '(whatsmeow|postgres|minio)' + +status: ## Verifica status da aplicação + @echo "$(GREEN)🔍 Verificando status...$(NC)" + @curl -s http://localhost:4000/health || echo "$(RED)❌ Aplicação não está rodando$(NC)" + +##@ Desenvolvimento Avançado + +profile-cpu: ## Profile de CPU (requer aplicação rodando) + @echo "$(GREEN)📊 Capturando profile de CPU...$(NC)" + curl http://localhost:4000/debug/pprof/profile?seconds=30 > cpu.prof + $(GO) tool pprof -http=:8080 cpu.prof + +profile-mem: ## Profile de memória (requer aplicação rodando) + @echo "$(GREEN)📊 Capturando profile de memória...$(NC)" + curl http://localhost:4000/debug/pprof/heap > mem.prof + $(GO) tool pprof -http=:8080 mem.prof + +generate: ## Roda go generate + @echo "$(GREEN)⚙️ Executando go generate...$(NC)" + $(GO) generate ./... + +mod-graph: ## Exibe gráfico de dependências + @echo "$(GREEN)📊 Gráfico de dependências:$(NC)" + $(GO) mod graph diff --git a/README.md b/README.md new file mode 100644 index 0000000..bc89966 --- /dev/null +++ b/README.md @@ -0,0 +1,224 @@ +

Evolution Go

+ +
+ +[![Docker Image](https://img.shields.io/badge/Docker-image-blue)](https://hub.docker.com/r/evoapicloud/evolution-go) +[![License](https://img.shields.io/badge/license-Apache--2.0-blue)](./LICENSE) +[![Go Version](https://img.shields.io/badge/Go-1.24+-00ADD8?logo=go)](https://golang.org/) +[![GitHub Stars](https://img.shields.io/github/stars/EvolutionAPI/evolution-go)](https://github.com/EvolutionAPI/evolution-go/stargazers) +[![Documentation](https://img.shields.io/badge/Documentation-Official-green)](https://docs.evolutionfoundation.com.br) + +
+ +
+ +## About + +Evolution Go is a high-performance WhatsApp API built in Go, part of the [Evolution](https://evolutionfoundation.com.br/) ecosystem. It provides a robust, lightweight solution for WhatsApp integration using the [whatsmeow](https://github.com/tulir/whatsmeow) library. + +## Features + +- **High Performance** — Built with Go for minimal resource usage +- **RESTful API** — Clean, well-documented REST endpoints with Swagger +- **Real-time Events** — WebSocket, Webhook, AMQP/RabbitMQ and NATS support +- **Media Support** — Images, videos, audio, documents with MinIO/S3 storage +- **Message Storage** — Optional PostgreSQL persistence +- **QR Code Pairing** — Built-in QR code generation for device linking +- **License Management** — Built-in licensing with registration, activation, and heartbeat +- **Docker Ready** — Production-ready Docker configuration + +## Quick Start + +### Docker (Recommended) + +```bash +git clone https://github.com/EvolutionAPI/evolution-go.git +cd evolution-go +make docker-build +make docker-run +``` + +### Local Development + +```bash +git clone https://github.com/EvolutionAPI/evolution-go.git +cd evolution-go + +# Clone whatsmeow dependency +git clone git@github.com:EvolutionAPI/whatsmeow.git whatsmeow-lib + +# Setup, configure and run +make setup +cp .env.example .env +make dev +``` + +> Run `make help` to see all available commands. See [COMMANDS.md](./COMMANDS.md) for detailed workflows. + +## Configuration + +Create a `.env` file: + +```env +# Server +SERVER_PORT=8080 +CLIENT_NAME=evolution + +# Security +GLOBAL_API_KEY=your-secure-api-key-here + +# Database +POSTGRES_AUTH_DB=postgresql://postgres:password@localhost:5432/evogo_auth?sslmode=disable +POSTGRES_USERS_DB=postgresql://postgres:password@localhost:5432/evogo_users?sslmode=disable +DATABASE_SAVE_MESSAGES=false + +# Logging +WADEBUG=DEBUG +LOGTYPE=console + +# Optional +# AMQP_URL=amqp://guest:guest@localhost:5672/ +# NATS_URL=nats://localhost:4222 +# WEBHOOK_URL=https://your-webhook-url.com/webhook +# MINIO_ENABLED=true +# MINIO_ENDPOINT=localhost:9000 +# MINIO_ACCESS_KEY=minioadmin +# MINIO_SECRET_KEY=minioadmin +``` + +| Variable | Description | Default | +|----------|-------------|---------| +| `SERVER_PORT` | Server port | `8080` | +| `CLIENT_NAME` | Client identifier | `evolution` | +| `GLOBAL_API_KEY` | API authentication key | **Required** | +| `DATABASE_SAVE_MESSAGES` | Enable message storage | `false` | +| `WADEBUG` | WhatsApp debug level | `INFO` | + +## License Activation + +Evolution Go requires a license to operate. On first run: + +1. Start the server — API endpoints return `503` until activated +2. Open the **Manager** at `http://localhost:8080/manager/login` +3. Enter your API URL and `GLOBAL_API_KEY` +4. Complete the license registration flow +5. Once activated, the API is fully operational + +The license status persists in the database (`runtime_configs` table). Heartbeats are sent periodically to maintain activation. + +## API Documentation + +Swagger UI available at: + +``` +http://localhost:8080/swagger/index.html +``` + +### Key Endpoints + +| Method | Endpoint | Description | +|--------|----------|-------------| +| `POST` | `/instance/create` | Create WhatsApp instance | +| `GET` | `/instance/{name}/qrcode` | Get QR code for pairing | +| `POST` | `/message/sendText` | Send text message | +| `POST` | `/message/sendMedia` | Send media message | +| `GET` | `/instance/{name}/status` | Get instance status | +| `DELETE` | `/instance/{name}` | Delete instance | + +## Project Structure + +``` +evolution-go/ +├── cmd/evolution-go/ # Application entry point +├── pkg/ +│ ├── core/ # License management & middleware +│ ├── instance/ # Instance management +│ ├── message/ # Message handling +│ ├── sendMessage/ # Message sending +│ ├── routes/ # HTTP routes +│ ├── middleware/ # Auth & validation middleware +│ ├── config/ # Configuration +│ ├── events/ # Event producers (AMQP, NATS, Webhook, WS) +│ └── storage/ # Media storage (MinIO) +├── whatsmeow-lib/ # WhatsApp protocol library +├── docs/ # Swagger documentation +├── Dockerfile +├── Makefile +└── VERSION +``` + +## Technology Stack + +| Component | Technology | +|-----------|-----------| +| Language | Go 1.24+ | +| HTTP Framework | Gin | +| WhatsApp | [whatsmeow](https://github.com/tulir/whatsmeow) | +| Database | PostgreSQL | +| ORM | GORM | +| Message Queue | RabbitMQ, NATS | +| Object Storage | MinIO/S3 | +| Documentation | Swagger/OpenAPI | +| Container | Docker | + +## Documentation & Support + +| Resource | Link | +|----------|------| +| Website | [evolutionfoundation.com.br](https://evolutionfoundation.com.br/) | +| Documentation | [docs.evolutionfoundation.com.br](https://docs.evolutionfoundation.com.br/) | +| Community | [evolutionfoundation.com.br/community](https://evolutionfoundation.com.br/community) | +| WhatsApp Support | [+55 31 7503-8350](https://wa.me/553175038350) | +| GitHub Issues | [evolution-go/issues](https://github.com/EvolutionAPI/evolution-go/issues) | + +## Hosting + +Deploy Evolution Go with optimized infrastructure: + +| Product | Link | +|---------|------| +| Evolution Go VPS | [Hostgator - Evo Go](https://www.hostgator.com.br/52579-144-3-55.html) | +| Evolution API VPS | [Hostgator - Evo API](https://www.hostgator.com.br/servidor-vps/hospedagem-evo-api/lp-afiliado) | + +## Contributing + +1. Fork the repository +2. Create your feature branch (`git checkout -b feature/amazing-feature`) +3. Commit your changes (`git commit -m 'Add some amazing feature'`) +4. Push to the branch (`git push origin feature/amazing-feature`) +5. Open a Pull Request + +## Security + +For security concerns, please email: contato@evolution-api.com + +## License + +Evolution Go is licensed under the Apache License 2.0, with the following additional conditions: + +1. **Logo and copyright**: You may not remove or modify the logo or copyright information in the Evolution console or applications when using frontend components. + +2. **Usage notification**: If Evolution Go is used as part of any project (including closed-source), a clear notification that Evolution Go is being utilized must be visible to system administrators. + +Please contact contato@evolution-api.com for licensing inquiries. Full license details at [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0). + +## Acknowledgments + +- [whatsmeow](https://github.com/tulir/whatsmeow) by [tulir](https://github.com/tulir) +- [Evolution API](https://github.com/EvolutionAPI/evolution-api) + +## Telemetry + +Evolution Go collects anonymous telemetry data (routes used, API version) to improve the service. No sensitive or personal data is collected. + +--- + +
+ +**Evolution Go** — High-Performance WhatsApp API + +Made with ❤️ by the [Evolution Team](https://evolutionfoundation.com.br/) + +© 2025 Evolution Foundation + +
diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..ee6cdce --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.6.1 diff --git a/cmd/evolution-go/main.go b/cmd/evolution-go/main.go new file mode 100644 index 0000000..3eccf86 --- /dev/null +++ b/cmd/evolution-go/main.go @@ -0,0 +1,443 @@ +package main + +import ( + "context" + "database/sql" + "flag" + "fmt" + "log" + "net/http" + "os" + "os/signal" + "strings" + "path/filepath" + "syscall" + "time" + + "github.com/gin-gonic/gin" + "github.com/gomessguii/logger" + "github.com/joho/godotenv" + "go.mau.fi/whatsmeow" + "gorm.io/gorm" + _ "modernc.org/sqlite" + + call_handler "github.com/EvolutionAPI/evolution-go/pkg/call/handler" + call_service "github.com/EvolutionAPI/evolution-go/pkg/call/service" + chat_handler "github.com/EvolutionAPI/evolution-go/pkg/chat/handler" + chat_service "github.com/EvolutionAPI/evolution-go/pkg/chat/service" + community_handler "github.com/EvolutionAPI/evolution-go/pkg/community/handler" + community_service "github.com/EvolutionAPI/evolution-go/pkg/community/service" + config "github.com/EvolutionAPI/evolution-go/pkg/config" + "github.com/EvolutionAPI/evolution-go/pkg/core" + producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces" + nats_producer "github.com/EvolutionAPI/evolution-go/pkg/events/nats" + rabbitmq_producer "github.com/EvolutionAPI/evolution-go/pkg/events/rabbitmq" + webhook_producer "github.com/EvolutionAPI/evolution-go/pkg/events/webhook" + websocket_producer "github.com/EvolutionAPI/evolution-go/pkg/events/websocket" + group_handler "github.com/EvolutionAPI/evolution-go/pkg/group/handler" + group_service "github.com/EvolutionAPI/evolution-go/pkg/group/service" + instance_handler "github.com/EvolutionAPI/evolution-go/pkg/instance/handler" + instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model" + instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository" + instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service" + label_handler "github.com/EvolutionAPI/evolution-go/pkg/label/handler" + label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model" + label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository" + label_service "github.com/EvolutionAPI/evolution-go/pkg/label/service" + logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger" + message_handler "github.com/EvolutionAPI/evolution-go/pkg/message/handler" + message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model" + message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository" + message_service "github.com/EvolutionAPI/evolution-go/pkg/message/service" + auth_middleware "github.com/EvolutionAPI/evolution-go/pkg/middleware" + newsletter_handler "github.com/EvolutionAPI/evolution-go/pkg/newsletter/handler" + newsletter_service "github.com/EvolutionAPI/evolution-go/pkg/newsletter/service" + poll_handler "github.com/EvolutionAPI/evolution-go/pkg/poll/handler" + routes "github.com/EvolutionAPI/evolution-go/pkg/routes" + send_handler "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/handler" + send_service "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/service" + server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler" + storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces" + minio_storage "github.com/EvolutionAPI/evolution-go/pkg/storage/minio" + "github.com/EvolutionAPI/evolution-go/pkg/telemetry" + user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler" + user_service "github.com/EvolutionAPI/evolution-go/pkg/user/service" + whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service" + amqp "github.com/rabbitmq/amqp091-go" +) + +var devMode = flag.Bool("dev", false, "Enable development mode") + +var version = "dev" + +func init() { + if version == "dev" { + if v, err := os.ReadFile("VERSION"); err == nil { + version = strings.TrimSpace(string(v)) + } + } +} + +func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.Config, conn *amqp.Connection, exPath string, runtimeCtx *core.RuntimeContext) *gin.Engine { + killChannel := make(map[string](chan bool)) + clientPointer := make(map[string]*whatsmeow.Client) + + loggerWrapper := logger_wrapper.NewLoggerManager(config) + + var rabbitmqProducer producer_interfaces.Producer + if conn != nil { + logger.LogInfo("RabbitMQ enabled") + rabbitmqProducer = rabbitmq_producer.NewRabbitMQProducer( + conn, + config.AmqpGlobalEnabled, + config.AmqpGlobalEvents, + config.AmqpSpecificEvents, + config.AmqpUrl, + loggerWrapper, + ) + } else { + // Even if initial connection failed, pass the URL so reconnection can work + rabbitmqProducer = rabbitmq_producer.NewRabbitMQProducer( + nil, + config.AmqpGlobalEnabled, + config.AmqpGlobalEvents, + config.AmqpSpecificEvents, + config.AmqpUrl, // Keep the URL for reconnection attempts + loggerWrapper, + ) + } + + var natsProducer producer_interfaces.Producer + if config.NatsUrl != "" { + logger.LogInfo("NATS enabled") + natsProducer = nats_producer.NewNatsProducer( + config.NatsUrl, + config.NatsGlobalEnabled, + config.NatsGlobalEvents, + loggerWrapper, + ) + } else { + natsProducer = nats_producer.NewNatsProducer( + "", + false, + nil, + loggerWrapper, + ) + } + + webhookProducer := webhook_producer.NewWebhookProducer(config.WebhookUrl, loggerWrapper) + websocketProducer := websocket_producer.NewWebsocketProducer(loggerWrapper) + + // Cria filas globais se o RabbitMQ global estiver habilitado + if config.AmqpGlobalEnabled && conn != nil { + logger.LogInfo("Creating global RabbitMQ queues...") + if err := rabbitmqProducer.CreateGlobalQueues(); err != nil { + logger.LogError("Failed to create global RabbitMQ queues: %v", err) + } else { + logger.LogInfo("Global RabbitMQ queues created successfully") + } + } + + var mediaStorage storage_interfaces.MediaStorage + var err error + if config.MinioEnabled { + mediaStorage, err = minio_storage.NewMinioMediaStorage( + config.MinioEndpoint, + config.MinioAccessKey, + config.MinioSecretKey, + config.MinioBucket, + config.MinioRegion, + config.MinioUseSSL, + ) + if err != nil { + log.Fatal(err) + } + } + + instanceRepository := instance_repository.NewInstanceRepository(db) + messageRepository := message_repository.NewMessageRepository(db) + labelRepository := label_repository.NewLabelRepository(db) + + whatsmeowService := whatsmeow_service.NewWhatsmeowService( + instanceRepository, + authDB, + message_repository.NewMessageRepository(db), + labelRepository, + config, + killChannel, + clientPointer, + rabbitmqProducer, + webhookProducer, + websocketProducer, + sqliteDB, + exPath, + mediaStorage, + natsProducer, + loggerWrapper, + ) + instanceService := instance_service.NewInstanceService( + instanceRepository, + killChannel, + clientPointer, + whatsmeowService, + config, + loggerWrapper, + ) + sendMessageService := send_service.NewSendService(clientPointer, whatsmeowService, config, loggerWrapper) + userService := user_service.NewUserService(clientPointer, whatsmeowService, loggerWrapper) + messageService := message_service.NewMessageService(clientPointer, messageRepository, whatsmeowService, loggerWrapper) + chatService := chat_service.NewChatService(clientPointer, whatsmeowService, loggerWrapper) + groupService := group_service.NewGroupService(clientPointer, whatsmeowService, loggerWrapper) + callService := call_service.NewCallService(clientPointer, whatsmeowService, loggerWrapper) + communityService := community_service.NewCommunityService(clientPointer, whatsmeowService, loggerWrapper) + labelService := label_service.NewLabelService(clientPointer, whatsmeowService, labelRepository, loggerWrapper) + newsletterService := newsletter_service.NewNewsletterService(clientPointer, whatsmeowService, loggerWrapper) + + // NOVO: PollHandler usando PollService já inicializado no whatsmeowService (evita dupla inicialização) + pollHandler := poll_handler.NewPollHandler(whatsmeowService.GetPollService(), loggerWrapper) + + telemetry := telemetry.NewTelemetryService() + + r := gin.Default() + + // CORS middleware — must be before everything else + r.Use(func(c *gin.Context) { + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") + c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") + c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") + c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Cache-Control, X-Requested-With, apikey, ApiKey") + c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length") + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(200) + return + } + c.Next() + }) + + r.Use(telemetry.TelemetryMiddleware()) + + r.Use(core.GateMiddleware(runtimeCtx)) + + // License routes (always accessible, even without license) + core.LicenseRoutes(r, runtimeCtx) + + routes.NewRouter( + auth_middleware.NewMiddleware(config, instanceService), + instance_handler.NewInstanceHandler(instanceService, config), + user_handler.NewUserHandler(userService), + send_handler.NewSendHandler(sendMessageService), + message_handler.NewMessageHandler(messageService), + chat_handler.NewChatHandler(chatService), + group_handler.NewGroupHandler(groupService), + call_handler.NewCallHandler(callService), + community_handler.NewCommunityHandler(communityService), + label_handler.NewLabelHandler(labelService), + newsletter_handler.NewNewsletterHandler(newsletterService), + pollHandler, + server_handler.NewServerHandler(), + ).AssignRoutes(r) + + if config.ConnectOnStartup { + go whatsmeowService.ConnectOnStartup(config.ClientName) + } + + r.GET("/ws", func(c *gin.Context) { + token := c.Query("token") + instanceId := c.Query("instanceId") + + if token != config.GlobalApiKey { + logger.LogError("Token inválido: %s", token) + c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido"}) + return + } + + websocket_producer.ServeWs(c.Writer, c.Request, instanceId, websocketProducer) + }) + + return r +} + +func migrate(db *gorm.DB) { + err := db.AutoMigrate(&instance_model.Instance{}, &message_model.Message{}, &label_model.Label{}) + + if err != nil { + log.Fatal(err) + } +} + +func initAuthDB(config *config.Config) (*sql.DB, string, error) { + if config.PostgresAuthDB != "" { + return nil, "", nil + } + + ex, err := os.Executable() + if err != nil { + panic(err) + } + exPath := filepath.Dir(ex) + + dbDirectory := exPath + "/dbdata" + _, err = os.Stat(dbDirectory) + if os.IsNotExist(err) { + errDir := os.MkdirAll(dbDirectory, 0751) + if errDir != nil { + panic("Could not create dbdata directory") + } + } + + db, err := sql.Open("sqlite", exPath+"/dbdata/users.db?_pragma=foreign_keys(1)&_busy_timeout=3000") + if err != nil { + return nil, "", err + } + + return db, exPath, nil +} + +func initPostgresAuthDB(config *config.Config) (*sql.DB, error) { + if config.PostgresAuthDB == "" { + return nil, nil + } + + if err := config.EnsureDBExists(config.PostgresAuthDB); err != nil { + logger.LogWarn("Auto-setup auth DB failed (will try connecting anyway): %v", err) + } + + db, err := sql.Open("postgres", config.PostgresAuthDB) + if err != nil { + return nil, fmt.Errorf("erro ao conectar ao banco AUTH PostgreSQL: %v", err) + } + + // Configurar pool de conexões para evitar conexões ociosas não fechadas + db.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente + db.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool + db.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts + db.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto + + err = db.Ping() + if err != nil { + return nil, fmt.Errorf("erro ao pingar banco AUTH PostgreSQL: %v", err) + } + + logger.LogInfo("Conectado ao banco AUTH PostgreSQL com pool configurado") + return db, nil +} + +// @title Evolution GO +// @version 1.0 +// @description Evolution GO - whatsmeow +func main() { + flag.Parse() + if *devMode { + err := godotenv.Load(".env") + if err != nil { + log.Fatal(err) + } + } + + cfg := config.Load() + + logger.LogInfo("Starting Evolution GO version %s", version) + + startTime := time.Now() + + db, err := cfg.CreateUsersDB() + if err != nil { + log.Fatal(err) + } + + // Inicializar PostgreSQL AUTH + authDB, err := initPostgresAuthDB(cfg) + if err != nil { + log.Fatal(err) + } + if authDB != nil { + defer authDB.Close() + } + + // Manter inicialização do SQLite + sqliteDB, exPath, err := initAuthDB(cfg) + if err != nil { + log.Fatal(err) + } + if sqliteDB != nil { + defer sqliteDB.Close() + } + + migrate(db) + + // Initialize core DB + license runtime + core.SetDB(db) + if err := core.MigrateDB(); err != nil { + log.Fatal("Failed to migrate runtime_configs: ", err) + } + tier := "evolution-go" + runtimeCtx := core.InitializeRuntime(tier, version, cfg.GlobalApiKey) + + var conn *amqp.Connection + + if cfg.AmqpUrl != "" { + logger.LogInfo("Attempting to connect to RabbitMQ...") + + // Create connection with heartbeat to prevent timeouts + amqpConfig := amqp.Config{ + Heartbeat: 30 * time.Second, // Send heartbeat every 30 seconds + Locale: "en_US", + } + + conn, err = amqp.DialConfig(cfg.AmqpUrl, amqpConfig) + if err != nil { + logger.LogError("Failed to connect to RabbitMQ, err: %v", err) + logger.LogInfo("RabbitMQ producer will be created with reconnection capability") + } else { + logger.LogInfo("Successfully connected to RabbitMQ with heartbeat enabled") + defer func(conn *amqp.Connection) { + err := conn.Close() + if err != nil { + logger.LogError("Failed to close RabbitMQ connection, err: %v", err) + } + }(conn) + } + } else { + logger.LogInfo("RabbitMQ URL not configured, skipping RabbitMQ connection") + } + + r := setupRouter(db, authDB, sqliteDB, cfg, conn, exPath, runtimeCtx) + + // Graceful shutdown with heartbeat + heartbeatCtx, heartbeatCancel := context.WithCancel(context.Background()) + defer heartbeatCancel() + + core.StartHeartbeat(heartbeatCtx, runtimeCtx, startTime) + + srv := &http.Server{ + Addr: ":" + os.Getenv("SERVER_PORT"), + Handler: r, + } + + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + + go func() { + logger.LogInfo("Iniciando servidor na porta %s", os.Getenv("SERVER_PORT")) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("server error: %v", err) + } + }() + + <-quit + logger.LogInfo("[SHUTDOWN] Signal received, shutting down...") + + // Stop heartbeat loop + heartbeatCancel() + + core.Shutdown(runtimeCtx) + + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownCancel() + + if err := srv.Shutdown(shutdownCtx); err != nil { + logger.LogError("[SHUTDOWN] Server forced to shutdown: %v", err) + } + + logger.LogInfo("[SHUTDOWN] Server exited") +} diff --git a/docker/examples/.env.example b/docker/examples/.env.example new file mode 100644 index 0000000..a72c0b4 --- /dev/null +++ b/docker/examples/.env.example @@ -0,0 +1,128 @@ +# Evolution GO - Configuração de Ambiente +# Copie este arquivo para .env e ajuste conforme necessário + +# ======================================== +# CONFIGURAÇÕES OBRIGATÓRIAS +# ======================================== + +# Porta do servidor +SERVER_PORT=4000 + +# Nome do cliente/instância +CLIENT_NAME=evolution + +# Chave de API (OBRIGATÓRIO - Use uma chave forte e única) +GLOBAL_API_KEY=sua-chave-api-segura-aqui-uuid-recomendado + +# ======================================== +# BANCO DE DADOS +# ======================================== + +# PostgreSQL (RECOMENDADO para produção) +POSTGRES_AUTH_DB=postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable +POSTGRES_USERS_DB=postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable + +# Salvar mensagens no banco de dados +DATABASE_SAVE_MESSAGES=false + +# ======================================== +# LOGS E DEBUG +# ======================================== + +# Nível de debug do WhatsApp (INFO, DEBUG, ERROR) +WADEBUG=INFO + +# Tipo de log (console, file) +LOGTYPE=console + +# Diretório de logs +LOG_DIRECTORY=/app/logs + +# Tamanho máximo do arquivo de log em MB +LOG_MAX_SIZE=100 + +# Número máximo de arquivos de backup +LOG_MAX_BACKUPS=5 + +# Dias de retenção dos logs +LOG_MAX_AGE=30 + +# Comprimir logs antigos +LOG_COMPRESS=true + +# ======================================== +# CONEXÃO +# ======================================== + +# Conectar automaticamente ao iniciar +CONNECT_ON_STARTUP=false + +# Enviar arquivos via webhook +WEBHOOKFILES=true + +# Nome do sistema operacional +OS_NAME=Linux + +# ======================================== +# EVENTOS E WEBHOOKS +# ======================================== + +# URL do webhook para receber eventos +WEBHOOK_URL= + +# RabbitMQ +AMQP_URL= +AMQP_GLOBAL_ENABLED=false +AMQP_GLOBAL_EVENTS= +AMQP_SPECIFIC_EVENTS= + +# NATS +NATS_URL= +NATS_GLOBAL_ENABLED=false +NATS_GLOBAL_EVENTS= + +# Ignorar eventos de grupos +EVENT_IGNORE_GROUP=false + +# Ignorar eventos de status +EVENT_IGNORE_STATUS=true + +# ======================================== +# ARMAZENAMENTO DE MÍDIA (MinIO/S3) +# ======================================== + +MINIO_ENABLED=false +MINIO_ENDPOINT= +MINIO_ACCESS_KEY= +MINIO_SECRET_KEY= +MINIO_BUCKET= +MINIO_USE_SSL=false +MINIO_REGION= + +# ======================================== +# PROXY (Opcional) +# ======================================== + +PROXY_HOST= +PROXY_PORT= +PROXY_USERNAME= +PROXY_PASSWORD= + +# ======================================== +# RECURSOS ADICIONAIS +# ======================================== + +# API de conversão de áudio +API_AUDIO_CONVERTER= +API_AUDIO_CONVERTER_KEY= + +# Número máximo de tentativas de QR Code +QRCODE_MAX_COUNT=5 + +# Verificar se o usuário existe antes de enviar mensagem +CHECK_USER_EXISTS=true + +# Versão do WhatsApp (opcional - deixe vazio para usar a padrão) +WHATSAPP_VERSION_MAJOR= +WHATSAPP_VERSION_MINOR= +WHATSAPP_VERSION_PATCH= diff --git a/docker/examples/docker-compose.full.yml b/docker/examples/docker-compose.full.yml new file mode 100644 index 0000000..31c36f7 --- /dev/null +++ b/docker/examples/docker-compose.full.yml @@ -0,0 +1,144 @@ +version: '3.8' + +services: + evolution-go: + image: evoapicloud/evolution-go:latest + container_name: evolution-go + restart: unless-stopped + ports: + - "4000:4000" + environment: + # Servidor + SERVER_PORT: 4000 + CLIENT_NAME: "evolution" + + # Segurança + GLOBAL_API_KEY: "sua-chave-api-segura-aqui" + + # Banco de Dados PostgreSQL + POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable" + POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable" + DATABASE_SAVE_MESSAGES: "true" + + # Logs e Debug + WADEBUG: "DEBUG" + LOGTYPE: "console" + LOG_DIRECTORY: "/app/logs" + LOG_MAX_SIZE: "100" + LOG_MAX_BACKUPS: "5" + LOG_MAX_AGE: "30" + LOG_COMPRESS: "true" + + # Conexão + CONNECT_ON_STARTUP: "false" + WEBHOOKFILES: "true" + + # Sistema + OS_NAME: "Linux" + + # Webhook + WEBHOOK_URL: "https://seu-webhook.com/endpoint" + + # RabbitMQ + AMQP_URL: "amqp://admin:admin@rabbitmq:5672/default" + AMQP_GLOBAL_ENABLED: "true" + AMQP_GLOBAL_EVENTS: "messages.upsert,messages.update,connection.update" + AMQP_SPECIFIC_EVENTS: "" + + # NATS + NATS_URL: "nats://nats:4222" + NATS_GLOBAL_ENABLED: "false" + NATS_GLOBAL_EVENTS: "" + + # MinIO + MINIO_ENABLED: "true" + MINIO_ENDPOINT: "minio:9000" + MINIO_ACCESS_KEY: "minioadmin" + MINIO_SECRET_KEY: "minioadmin" + MINIO_BUCKET: "evolution-media" + MINIO_USE_SSL: "false" + MINIO_REGION: "us-east-1" + + # Eventos + EVENT_IGNORE_GROUP: "false" + EVENT_IGNORE_STATUS: "true" + + # QR Code + QRCODE_MAX_COUNT: "5" + + # Verificação de Usuário + CHECK_USER_EXISTS: "true" + + volumes: + - evolution_data:/app/dbdata + - evolution_logs:/app/logs + networks: + - evolution_network + depends_on: + - postgres + - rabbitmq + - minio + + postgres: + image: postgres:15-alpine + container_name: evolution-postgres + restart: unless-stopped + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: postgres + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + - ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql + networks: + - evolution_network + + rabbitmq: + image: rabbitmq:3-management-alpine + container_name: evolution-rabbitmq + restart: unless-stopped + environment: + RABBITMQ_DEFAULT_USER: admin + RABBITMQ_DEFAULT_PASS: admin + RABBITMQ_DEFAULT_VHOST: default + ports: + - "5672:5672" + - "15672:15672" + volumes: + - rabbitmq_data:/var/lib/rabbitmq + networks: + - evolution_network + + minio: + image: minio/minio:latest + container_name: evolution-minio + restart: unless-stopped + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER: minioadmin + MINIO_ROOT_PASSWORD: minioadmin + ports: + - "9000:9000" + - "9001:9001" + volumes: + - minio_data:/data + networks: + - evolution_network + +volumes: + evolution_data: + driver: local + evolution_logs: + driver: local + postgres_data: + driver: local + rabbitmq_data: + driver: local + minio_data: + driver: local + +networks: + evolution_network: + driver: bridge diff --git a/docker/examples/docker-compose.swarm.yml b/docker/examples/docker-compose.swarm.yml new file mode 100644 index 0000000..b764f28 --- /dev/null +++ b/docker/examples/docker-compose.swarm.yml @@ -0,0 +1,102 @@ +version: '3.8' + +services: + evolution_go: + image: evoapicloud/evolution-go:latest + networks: + - network_public + environment: + # Servidor + SERVER_PORT: 4000 + CLIENT_NAME: "evolution" + + # Segurança (OBRIGATÓRIO) + GLOBAL_API_KEY: "sua-chave-api-segura-aqui" + + # Banco de Dados PostgreSQL (RECOMENDADO) + POSTGRES_AUTH_DB: "postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable" + POSTGRES_USERS_DB: "postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable" + DATABASE_SAVE_MESSAGES: "false" + + # Logs e Debug + WADEBUG: "INFO" + LOGTYPE: "console" + LOG_DIRECTORY: "/app/logs" + LOG_MAX_SIZE: "100" + LOG_MAX_BACKUPS: "5" + LOG_MAX_AGE: "30" + LOG_COMPRESS: "true" + + # Conexão + CONNECT_ON_STARTUP: "true" + WEBHOOKFILES: "true" + + # Sistema + OS_NAME: "Linux" + + # Conversor de Áudio (Opcional) + API_AUDIO_CONVERTER: "" + API_AUDIO_CONVERTER_KEY: "" + + # Proxy (Opcional) + PROXY_HOST: "" + PROXY_PORT: "" + PROXY_USERNAME: "" + PROXY_PASSWORD: "" + + # RabbitMQ (Opcional) + AMQP_URL: "" + AMQP_GLOBAL_ENABLED: "false" + AMQP_GLOBAL_EVENTS: "" + + # NATS (Opcional) + NATS_URL: "" + NATS_GLOBAL_ENABLED: "false" + + # Eventos + EVENT_IGNORE_GROUP: "false" + EVENT_IGNORE_STATUS: "true" + + # MinIO/S3 (Opcional) + MINIO_ENABLED: "false" + MINIO_ENDPOINT: "" + MINIO_ACCESS_KEY: "" + MINIO_SECRET_KEY: "" + MINIO_BUCKET: "" + MINIO_USE_SSL: "false" + + volumes: + - evolution_go_data:/app/dbdata + - evolution_go_logs:/app/logs + + deploy: + replicas: 1 + placement: + constraints: + - node.role == manager + restart_policy: + condition: on-failure + delay: 5s + max_attempts: 3 + labels: + # Traefik Labels (ajuste conforme necessário) + - traefik.enable=true + - traefik.http.routers.evolution_go.rule=Host(`evolution.seudominio.com`) + - traefik.http.routers.evolution_go.entrypoints=websecure + - traefik.http.routers.evolution_go.tls.certresolver=letsencryptresolver + - traefik.http.routers.evolution_go.service=evolution_go + - traefik.http.services.evolution_go.loadbalancer.server.port=4000 + - traefik.http.services.evolution_go.loadbalancer.passHostHeader=true + +volumes: + evolution_go_data: + external: true + name: evolution_go_data + evolution_go_logs: + external: true + name: evolution_go_logs + +networks: + network_public: + external: true + name: network_public diff --git a/docker/examples/docker-compose.yml b/docker/examples/docker-compose.yml new file mode 100644 index 0000000..2714e16 --- /dev/null +++ b/docker/examples/docker-compose.yml @@ -0,0 +1,96 @@ +version: '3.8' + +services: + evolution-go: + image: evoapicloud/evolution-go:latest + container_name: evolution-go + restart: unless-stopped + ports: + - "4000:4000" + environment: + # Servidor + SERVER_PORT: 4000 + CLIENT_NAME: "evolution" + + # Segurança (OBRIGATÓRIO) + GLOBAL_API_KEY: "sua-chave-api-segura-aqui" + + # Banco de Dados PostgreSQL (RECOMENDADO) + POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable" + POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable" + DATABASE_SAVE_MESSAGES: "false" + + # Logs e Debug + WADEBUG: "INFO" + LOGTYPE: "console" + LOG_DIRECTORY: "/app/logs" + LOG_MAX_SIZE: "100" + LOG_MAX_BACKUPS: "5" + LOG_MAX_AGE: "30" + LOG_COMPRESS: "true" + + # Conexão + CONNECT_ON_STARTUP: "false" + WEBHOOKFILES: "true" + + # Sistema + OS_NAME: "Linux" + + # Eventos (Opcionais) + WEBHOOK_URL: "" + AMQP_URL: "" + AMQP_GLOBAL_ENABLED: "false" + NATS_URL: "" + NATS_GLOBAL_ENABLED: "false" + + # Armazenamento de Mídia (Opcional) + MINIO_ENABLED: "false" + + # Proxy (Opcional) + PROXY_HOST: "" + PROXY_PORT: "" + PROXY_USERNAME: "" + PROXY_PASSWORD: "" + + # Eventos + EVENT_IGNORE_GROUP: "false" + EVENT_IGNORE_STATUS: "true" + + # QR Code + QRCODE_MAX_COUNT: "5" + + volumes: + - evolution_data:/app/dbdata + - evolution_logs:/app/logs + networks: + - evolution_network + depends_on: + - postgres + + postgres: + image: postgres:15-alpine + container_name: evolution-postgres + restart: unless-stopped + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: postgres + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + - ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql + networks: + - evolution_network + +volumes: + evolution_data: + driver: local + evolution_logs: + driver: local + postgres_data: + driver: local + +networks: + evolution_network: + driver: bridge diff --git a/docker/examples/init-db.sql b/docker/examples/init-db.sql new file mode 100644 index 0000000..b623573 --- /dev/null +++ b/docker/examples/init-db.sql @@ -0,0 +1,10 @@ +-- Script de inicialização dos bancos de dados Evolution GO + +-- Criar database para autenticação +CREATE DATABASE evogo_auth; + +-- Criar database para dados de usuários +CREATE DATABASE evogo_users; + +-- Mensagem de confirmação +SELECT 'Databases evogo_auth e evogo_users criados com sucesso!' as message; diff --git a/docs/docs.go b/docs/docs.go new file mode 100644 index 0000000..0843d82 --- /dev/null +++ b/docs/docs.go @@ -0,0 +1,3299 @@ +// Package docs Code generated by swaggo/swag. DO NOT EDIT +package docs + +import "github.com/swaggo/swag" + +const docTemplate = `{ + "schemes": {{ marshal .Schemes }}, + "swagger": "2.0", + "info": { + "description": "{{escape .Description}}", + "title": "{{.Title}}", + "contact": {}, + "version": "{{.Version}}" + }, + "host": "{{.Host}}", + "basePath": "{{.BasePath}}", + "paths": { + "/chat/archive": { + "post": { + "description": "Archive a chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Chat" + ], + "summary": "Archive a chat", + "parameters": [ + { + "description": "Chat", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/chat/mute": { + "post": { + "description": "Mute a chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Chat" + ], + "summary": "Mute a chat", + "parameters": [ + { + "description": "Chat", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/chat/pin": { + "post": { + "description": "Pin a chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Chat" + ], + "summary": "Pin a chat", + "parameters": [ + { + "description": "Chat", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/chat/unpin": { + "post": { + "description": "Unpin a chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Chat" + ], + "summary": "Unpin a chat", + "parameters": [ + { + "description": "Chat", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/community/add": { + "post": { + "description": "Add participant to community", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Community" + ], + "summary": "Add participant to community", + "parameters": [ + { + "description": "Participant data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/community/create": { + "post": { + "description": "Create community", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Community" + ], + "summary": "Create community", + "parameters": [ + { + "description": "Community data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/community/remove": { + "post": { + "description": "Remove participant from community", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Community" + ], + "summary": "Remove participant from community", + "parameters": [ + { + "description": "Participant data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/create": { + "post": { + "description": "Create group", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Create group", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/info": { + "post": { + "description": "Get group info", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Get group info", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/invitelink": { + "post": { + "description": "Get group invite link", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Get group invite link", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/join": { + "post": { + "description": "Join group link", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Join group link", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/list": { + "get": { + "description": "List groups", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "List groups", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/myall": { + "get": { + "description": "Get my groups", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Get my groups", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/name": { + "post": { + "description": "Set group name", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Set group name", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/participant": { + "post": { + "description": "Update participant", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Update participant", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/photo": { + "post": { + "description": "Set group photo", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Set group photo", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/all": { + "get": { + "description": "Get all instances", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Get all instances", + "responses": { + "200": { + "description": "All instances", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/connect": { + "post": { + "description": "Connect to instance with the provided data", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Connect to instance", + "parameters": [ + { + "description": "Instance data", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct" + } + } + ], + "responses": { + "200": { + "description": "Instance connected successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/create": { + "post": { + "description": "Creates a new instance with the provided data", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Create a new instance", + "parameters": [ + { + "description": "Instance data", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct" + } + } + ], + "responses": { + "200": { + "description": "Instance created successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/delete/{instanceId}": { + "delete": { + "description": "Delete instance", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Delete instance", + "parameters": [ + { + "type": "string", + "description": "Instance Id", + "name": "instanceId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Instance deleted successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/disconnect": { + "post": { + "description": "Disconnect from instance", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Disconnect from instance", + "responses": { + "200": { + "description": "Instance disconnected successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/logout": { + "delete": { + "description": "Logout from instance", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Logout from instance", + "responses": { + "200": { + "description": "Instance logged out successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/pair": { + "post": { + "description": "Request pairing code", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Request pairing code", + "parameters": [ + { + "description": "Instance data", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct" + } + } + ], + "responses": { + "200": { + "description": "Pairing code", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/proxy/{instanceId}": { + "delete": { + "description": "Delete proxy", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Delete proxy", + "parameters": [ + { + "type": "string", + "description": "Instance id", + "name": "instanceId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Proxy deleted successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/qr": { + "get": { + "description": "Get instance QR code", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Get instance QR code", + "responses": { + "200": { + "description": "Instance QR code", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/status": { + "get": { + "description": "Get instance status", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Get instance status", + "responses": { + "200": { + "description": "Instance status", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/label/chat": { + "post": { + "description": "Add label to chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Add label to chat", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/label/edit": { + "post": { + "description": "Edit label", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Edit label", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/label/message": { + "post": { + "description": "Add label to message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Add label to message", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/delete": { + "post": { + "description": "Delete a message for everyone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Delete a message for everyone", + "parameters": [ + { + "description": "Delete a message for everyone", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/downloadimage": { + "post": { + "description": "Download an image", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Download an image", + "parameters": [ + { + "description": "Download an image", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/edit": { + "post": { + "description": "Edit a message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Edit a message", + "parameters": [ + { + "description": "Edit a message", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/markread": { + "post": { + "description": "Mark a message as read", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Mark a message as read", + "parameters": [ + { + "description": "Mark a message as read", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/presence": { + "post": { + "description": "Set chat presence", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Set chat presence", + "parameters": [ + { + "description": "Set chat presence", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/react": { + "post": { + "description": "React a message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "React a message", + "parameters": [ + { + "description": "React a message", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/status": { + "post": { + "description": "Get message status", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Get message status", + "parameters": [ + { + "description": "Get message status", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/create": { + "post": { + "description": "Create newsletter", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Create newsletter", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/info": { + "post": { + "description": "Get newsletter", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Get newsletter", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/link": { + "post": { + "description": "Get newsletter invite", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Get newsletter invite", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/list": { + "get": { + "description": "List newsletters", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "List newsletters", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/messages": { + "post": { + "description": "Get newsletter messages", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Get newsletter messages", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/subscribe": { + "post": { + "description": "Subscribe newsletter", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Subscribe newsletter", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/contact": { + "post": { + "description": "Send a contact message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a contact message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/link": { + "post": { + "description": "Send a link message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a link message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/location": { + "post": { + "description": "Send a location message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a location message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/media": { + "post": { + "description": "Send a media message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a media message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/poll": { + "post": { + "description": "Send a poll message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a poll message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/sticker": { + "post": { + "description": "Send a sticker message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a sticker message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/text": { + "post": { + "description": "Send a text message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a text message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/unlabel/chat": { + "post": { + "description": "Remove label from chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Remove label from chat", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/unlabel/message": { + "post": { + "description": "Remove label from message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Remove label from message", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/avatar": { + "post": { + "description": "Get a user's avatar", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user's avatar", + "parameters": [ + { + "description": "Avatar data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/block": { + "post": { + "description": "Block a contact", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Block a contact", + "parameters": [ + { + "description": "Block data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/blocklist": { + "get": { + "description": "Get a user's block list", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user's block list", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/check": { + "post": { + "description": "Check a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Check a user", + "parameters": [ + { + "description": "User data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/contacts": { + "get": { + "description": "Get a user's contacts", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user's contacts", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/info": { + "post": { + "description": "Get a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user", + "parameters": [ + { + "description": "User data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/privacy": { + "get": { + "description": "Get a user's privacy settings", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user's privacy settings", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/profile": { + "post": { + "description": "Set a user's profile picture", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Set a user's profile picture", + "parameters": [ + { + "description": "Profile picture data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/unblock": { + "post": { + "description": "Unblock a contact", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Unblock a contact", + "parameters": [ + { + "description": "Block data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + } + }, + "definitions": { + "gin.H": { + "type": "object", + "additionalProperties": {} + }, + "github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct": { + "type": "object", + "properties": { + "chat": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct": { + "type": "object", + "properties": { + "communityJid": { + "type": "string" + }, + "groupJid": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct": { + "type": "object", + "properties": { + "communityName": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct": { + "type": "object", + "properties": { + "action": { + "$ref": "#/definitions/whatsmeow.ParticipantChange" + }, + "groupJid": { + "$ref": "#/definitions/types.JID" + }, + "participants": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct": { + "type": "object", + "properties": { + "groupName": { + "type": "string" + }, + "participants": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct": { + "type": "object", + "properties": { + "groupJid": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct": { + "type": "object", + "properties": { + "groupJid": { + "type": "string" + }, + "reset": { + "type": "boolean" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct": { + "type": "object", + "properties": { + "code": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct": { + "type": "object", + "properties": { + "groupJid": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct": { + "type": "object", + "properties": { + "groupJid": { + "type": "string" + }, + "image": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct": { + "type": "object", + "properties": { + "immediate": { + "type": "boolean" + }, + "phone": { + "type": "string" + }, + "subscribe": { + "type": "array", + "items": { + "type": "string" + } + }, + "webhookUrl": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "proxy": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig" + }, + "token": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct": { + "type": "object", + "properties": { + "phone": { + "type": "string" + }, + "subscribe": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig": { + "type": "object", + "properties": { + "address": { + "type": "string" + }, + "password": { + "type": "string" + }, + "port": { + "type": "string" + }, + "username": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct": { + "type": "object", + "properties": { + "jid": { + "type": "string" + }, + "labelId": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct": { + "type": "object", + "properties": { + "color": { + "type": "integer" + }, + "deleted": { + "type": "boolean" + }, + "labelId": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct": { + "type": "object", + "properties": { + "jid": { + "type": "string" + }, + "labelId": { + "type": "string" + }, + "messageId": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct": { + "type": "object", + "properties": { + "isAudio": { + "type": "boolean" + }, + "number": { + "type": "string" + }, + "state": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct": { + "type": "object", + "properties": { + "directPath": { + "type": "string" + }, + "fileEncSHA256": { + "type": "array", + "items": { + "type": "integer" + } + }, + "fileLength": { + "type": "integer" + }, + "fileSHA256": { + "type": "array", + "items": { + "type": "integer" + } + }, + "mediaKey": { + "type": "array", + "items": { + "type": "integer" + } + }, + "mimetype": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct": { + "type": "object", + "properties": { + "chat": { + "type": "string" + }, + "message": { + "type": "string" + }, + "messageId": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct": { + "type": "object", + "properties": { + "id": { + "type": "array", + "items": { + "type": "string" + } + }, + "number": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct": { + "type": "object", + "properties": { + "chat": { + "type": "string" + }, + "messageId": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "number": { + "type": "string" + }, + "reaction": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct": { + "type": "object", + "properties": { + "key": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct": { + "type": "object", + "properties": { + "before_id": { + "type": "integer" + }, + "count": { + "type": "integer" + }, + "jid": { + "$ref": "#/definitions/types.JID" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct": { + "type": "object", + "properties": { + "jid": { + "$ref": "#/definitions/types.JID" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "vcard": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "imgUrl": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "text": { + "type": "string" + }, + "title": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct": { + "type": "object", + "properties": { + "address": { + "type": "string" + }, + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "latitude": { + "type": "number" + }, + "longitude": { + "type": "number" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct": { + "type": "object", + "properties": { + "caption": { + "type": "string" + }, + "delay": { + "type": "integer" + }, + "filename": { + "type": "string" + }, + "id": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "type": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "maxAnswer": { + "type": "integer" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "string" + } + }, + "question": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct": { + "type": "object", + "properties": { + "messageId": { + "type": "string" + }, + "participant": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "sticker": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "text": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct": { + "type": "object", + "properties": { + "number": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct": { + "type": "object", + "properties": { + "number": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct": { + "type": "object", + "properties": { + "number": { + "type": "string" + }, + "preview": { + "type": "boolean" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct": { + "type": "object", + "properties": { + "image": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct": { + "type": "object", + "properties": { + "fullName": { + "type": "string" + }, + "organization": { + "type": "string" + }, + "phone": { + "type": "string" + } + } + }, + "types.JID": { + "type": "object", + "properties": { + "device": { + "type": "integer" + }, + "integrator": { + "type": "integer" + }, + "rawAgent": { + "type": "integer" + }, + "server": { + "type": "string" + }, + "user": { + "type": "string" + } + } + }, + "whatsmeow.ParticipantChange": { + "type": "string", + "enum": [ + "add", + "remove", + "promote", + "demote" + ], + "x-enum-varnames": [ + "ParticipantChangeAdd", + "ParticipantChangeRemove", + "ParticipantChangePromote", + "ParticipantChangeDemote" + ] + } + } +}` + +// SwaggerInfo holds exported Swagger Info so clients can modify it +var SwaggerInfo = &swag.Spec{ + Version: "1.0", + Host: "", + BasePath: "", + Schemes: []string{}, + Title: "Evolution GO", + Description: "Evolution GO - whatsmeow", + InfoInstanceName: "swagger", + SwaggerTemplate: docTemplate, + LeftDelim: "{{", + RightDelim: "}}", +} + +func init() { + swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) +} diff --git a/docs/swagger.json b/docs/swagger.json new file mode 100644 index 0000000..b264746 --- /dev/null +++ b/docs/swagger.json @@ -0,0 +1,3273 @@ +{ + "swagger": "2.0", + "info": { + "description": "Evolution GO - whatsmeow", + "title": "Evolution GO", + "contact": {}, + "version": "1.0" + }, + "paths": { + "/chat/archive": { + "post": { + "description": "Archive a chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Chat" + ], + "summary": "Archive a chat", + "parameters": [ + { + "description": "Chat", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/chat/mute": { + "post": { + "description": "Mute a chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Chat" + ], + "summary": "Mute a chat", + "parameters": [ + { + "description": "Chat", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/chat/pin": { + "post": { + "description": "Pin a chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Chat" + ], + "summary": "Pin a chat", + "parameters": [ + { + "description": "Chat", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/chat/unpin": { + "post": { + "description": "Unpin a chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Chat" + ], + "summary": "Unpin a chat", + "parameters": [ + { + "description": "Chat", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/community/add": { + "post": { + "description": "Add participant to community", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Community" + ], + "summary": "Add participant to community", + "parameters": [ + { + "description": "Participant data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/community/create": { + "post": { + "description": "Create community", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Community" + ], + "summary": "Create community", + "parameters": [ + { + "description": "Community data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/community/remove": { + "post": { + "description": "Remove participant from community", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Community" + ], + "summary": "Remove participant from community", + "parameters": [ + { + "description": "Participant data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/create": { + "post": { + "description": "Create group", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Create group", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/info": { + "post": { + "description": "Get group info", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Get group info", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/invitelink": { + "post": { + "description": "Get group invite link", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Get group invite link", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/join": { + "post": { + "description": "Join group link", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Join group link", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/list": { + "get": { + "description": "List groups", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "List groups", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/myall": { + "get": { + "description": "Get my groups", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Get my groups", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/name": { + "post": { + "description": "Set group name", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Set group name", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/participant": { + "post": { + "description": "Update participant", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Update participant", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/group/photo": { + "post": { + "description": "Set group photo", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Group" + ], + "summary": "Set group photo", + "parameters": [ + { + "description": "Group data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/all": { + "get": { + "description": "Get all instances", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Get all instances", + "responses": { + "200": { + "description": "All instances", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/connect": { + "post": { + "description": "Connect to instance with the provided data", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Connect to instance", + "parameters": [ + { + "description": "Instance data", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct" + } + } + ], + "responses": { + "200": { + "description": "Instance connected successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/create": { + "post": { + "description": "Creates a new instance with the provided data", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Create a new instance", + "parameters": [ + { + "description": "Instance data", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct" + } + } + ], + "responses": { + "200": { + "description": "Instance created successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/delete/{instanceId}": { + "delete": { + "description": "Delete instance", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Delete instance", + "parameters": [ + { + "type": "string", + "description": "Instance Id", + "name": "instanceId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Instance deleted successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/disconnect": { + "post": { + "description": "Disconnect from instance", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Disconnect from instance", + "responses": { + "200": { + "description": "Instance disconnected successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/logout": { + "delete": { + "description": "Logout from instance", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Logout from instance", + "responses": { + "200": { + "description": "Instance logged out successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/pair": { + "post": { + "description": "Request pairing code", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Request pairing code", + "parameters": [ + { + "description": "Instance data", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct" + } + } + ], + "responses": { + "200": { + "description": "Pairing code", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/proxy/{instanceId}": { + "delete": { + "description": "Delete proxy", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Delete proxy", + "parameters": [ + { + "type": "string", + "description": "Instance id", + "name": "instanceId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Proxy deleted successfully", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/qr": { + "get": { + "description": "Get instance QR code", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Get instance QR code", + "responses": { + "200": { + "description": "Instance QR code", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/instance/status": { + "get": { + "description": "Get instance status", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Instance" + ], + "summary": "Get instance status", + "responses": { + "200": { + "description": "Instance status", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/label/chat": { + "post": { + "description": "Add label to chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Add label to chat", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/label/edit": { + "post": { + "description": "Edit label", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Edit label", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/label/message": { + "post": { + "description": "Add label to message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Add label to message", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/delete": { + "post": { + "description": "Delete a message for everyone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Delete a message for everyone", + "parameters": [ + { + "description": "Delete a message for everyone", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/downloadimage": { + "post": { + "description": "Download an image", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Download an image", + "parameters": [ + { + "description": "Download an image", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/edit": { + "post": { + "description": "Edit a message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Edit a message", + "parameters": [ + { + "description": "Edit a message", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/markread": { + "post": { + "description": "Mark a message as read", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Mark a message as read", + "parameters": [ + { + "description": "Mark a message as read", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/presence": { + "post": { + "description": "Set chat presence", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Set chat presence", + "parameters": [ + { + "description": "Set chat presence", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/react": { + "post": { + "description": "React a message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "React a message", + "parameters": [ + { + "description": "React a message", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/message/status": { + "post": { + "description": "Get message status", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Message" + ], + "summary": "Get message status", + "parameters": [ + { + "description": "Get message status", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/create": { + "post": { + "description": "Create newsletter", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Create newsletter", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/info": { + "post": { + "description": "Get newsletter", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Get newsletter", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/link": { + "post": { + "description": "Get newsletter invite", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Get newsletter invite", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/list": { + "get": { + "description": "List newsletters", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "List newsletters", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/messages": { + "post": { + "description": "Get newsletter messages", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Get newsletter messages", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/newsletter/subscribe": { + "post": { + "description": "Subscribe newsletter", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Newsletter" + ], + "summary": "Subscribe newsletter", + "parameters": [ + { + "description": "Newsletter data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/contact": { + "post": { + "description": "Send a contact message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a contact message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/link": { + "post": { + "description": "Send a link message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a link message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/location": { + "post": { + "description": "Send a location message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a location message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/media": { + "post": { + "description": "Send a media message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a media message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/poll": { + "post": { + "description": "Send a poll message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a poll message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/sticker": { + "post": { + "description": "Send a sticker message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a sticker message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/send/text": { + "post": { + "description": "Send a text message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Send Message" + ], + "summary": "Send a text message", + "parameters": [ + { + "description": "Message data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/unlabel/chat": { + "post": { + "description": "Remove label from chat", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Remove label from chat", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/unlabel/message": { + "post": { + "description": "Remove label from message", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Label" + ], + "summary": "Remove label from message", + "parameters": [ + { + "description": "Label data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/avatar": { + "post": { + "description": "Get a user's avatar", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user's avatar", + "parameters": [ + { + "description": "Avatar data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/block": { + "post": { + "description": "Block a contact", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Block a contact", + "parameters": [ + { + "description": "Block data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/blocklist": { + "get": { + "description": "Get a user's block list", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user's block list", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/check": { + "post": { + "description": "Check a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Check a user", + "parameters": [ + { + "description": "User data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/contacts": { + "get": { + "description": "Get a user's contacts", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user's contacts", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/info": { + "post": { + "description": "Get a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user", + "parameters": [ + { + "description": "User data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/privacy": { + "get": { + "description": "Get a user's privacy settings", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Get a user's privacy settings", + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/profile": { + "post": { + "description": "Set a user's profile picture", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Set a user's profile picture", + "parameters": [ + { + "description": "Profile picture data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + }, + "/user/unblock": { + "post": { + "description": "Unblock a contact", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "User" + ], + "summary": "Unblock a contact", + "parameters": [ + { + "description": "Block data", + "name": "message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct" + } + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "400": { + "description": "Error on validation", + "schema": { + "$ref": "#/definitions/gin.H" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/gin.H" + } + } + } + } + } + }, + "definitions": { + "gin.H": { + "type": "object", + "additionalProperties": {} + }, + "github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct": { + "type": "object", + "properties": { + "chat": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct": { + "type": "object", + "properties": { + "communityJid": { + "type": "string" + }, + "groupJid": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct": { + "type": "object", + "properties": { + "communityName": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct": { + "type": "object", + "properties": { + "action": { + "$ref": "#/definitions/whatsmeow.ParticipantChange" + }, + "groupJid": { + "$ref": "#/definitions/types.JID" + }, + "participants": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct": { + "type": "object", + "properties": { + "groupName": { + "type": "string" + }, + "participants": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct": { + "type": "object", + "properties": { + "groupJid": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct": { + "type": "object", + "properties": { + "groupJid": { + "type": "string" + }, + "reset": { + "type": "boolean" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct": { + "type": "object", + "properties": { + "code": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct": { + "type": "object", + "properties": { + "groupJid": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct": { + "type": "object", + "properties": { + "groupJid": { + "type": "string" + }, + "image": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct": { + "type": "object", + "properties": { + "immediate": { + "type": "boolean" + }, + "phone": { + "type": "string" + }, + "subscribe": { + "type": "array", + "items": { + "type": "string" + } + }, + "webhookUrl": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "proxy": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig" + }, + "token": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct": { + "type": "object", + "properties": { + "phone": { + "type": "string" + }, + "subscribe": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig": { + "type": "object", + "properties": { + "address": { + "type": "string" + }, + "password": { + "type": "string" + }, + "port": { + "type": "string" + }, + "username": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct": { + "type": "object", + "properties": { + "jid": { + "type": "string" + }, + "labelId": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct": { + "type": "object", + "properties": { + "color": { + "type": "integer" + }, + "deleted": { + "type": "boolean" + }, + "labelId": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct": { + "type": "object", + "properties": { + "jid": { + "type": "string" + }, + "labelId": { + "type": "string" + }, + "messageId": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct": { + "type": "object", + "properties": { + "isAudio": { + "type": "boolean" + }, + "number": { + "type": "string" + }, + "state": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct": { + "type": "object", + "properties": { + "directPath": { + "type": "string" + }, + "fileEncSHA256": { + "type": "array", + "items": { + "type": "integer" + } + }, + "fileLength": { + "type": "integer" + }, + "fileSHA256": { + "type": "array", + "items": { + "type": "integer" + } + }, + "mediaKey": { + "type": "array", + "items": { + "type": "integer" + } + }, + "mimetype": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct": { + "type": "object", + "properties": { + "chat": { + "type": "string" + }, + "message": { + "type": "string" + }, + "messageId": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct": { + "type": "object", + "properties": { + "id": { + "type": "array", + "items": { + "type": "string" + } + }, + "number": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct": { + "type": "object", + "properties": { + "chat": { + "type": "string" + }, + "messageId": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "number": { + "type": "string" + }, + "reaction": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct": { + "type": "object", + "properties": { + "key": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct": { + "type": "object", + "properties": { + "before_id": { + "type": "integer" + }, + "count": { + "type": "integer" + }, + "jid": { + "$ref": "#/definitions/types.JID" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct": { + "type": "object", + "properties": { + "jid": { + "$ref": "#/definitions/types.JID" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "vcard": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "imgUrl": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "text": { + "type": "string" + }, + "title": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct": { + "type": "object", + "properties": { + "address": { + "type": "string" + }, + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "latitude": { + "type": "number" + }, + "longitude": { + "type": "number" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct": { + "type": "object", + "properties": { + "caption": { + "type": "string" + }, + "delay": { + "type": "integer" + }, + "filename": { + "type": "string" + }, + "id": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "type": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "maxAnswer": { + "type": "integer" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "string" + } + }, + "question": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct": { + "type": "object", + "properties": { + "messageId": { + "type": "string" + }, + "participant": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "sticker": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "mentionAll": { + "type": "boolean" + }, + "mentionedJid": { + "type": "string" + }, + "number": { + "type": "string" + }, + "quoted": { + "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct" + }, + "text": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct": { + "type": "object", + "properties": { + "number": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct": { + "type": "object", + "properties": { + "number": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct": { + "type": "object", + "properties": { + "number": { + "type": "string" + }, + "preview": { + "type": "boolean" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct": { + "type": "object", + "properties": { + "image": { + "type": "string" + } + } + }, + "github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct": { + "type": "object", + "properties": { + "fullName": { + "type": "string" + }, + "organization": { + "type": "string" + }, + "phone": { + "type": "string" + } + } + }, + "types.JID": { + "type": "object", + "properties": { + "device": { + "type": "integer" + }, + "integrator": { + "type": "integer" + }, + "rawAgent": { + "type": "integer" + }, + "server": { + "type": "string" + }, + "user": { + "type": "string" + } + } + }, + "whatsmeow.ParticipantChange": { + "type": "string", + "enum": [ + "add", + "remove", + "promote", + "demote" + ], + "x-enum-varnames": [ + "ParticipantChangeAdd", + "ParticipantChangeRemove", + "ParticipantChangePromote", + "ParticipantChangeDemote" + ] + } + } +} \ No newline at end of file diff --git a/docs/swagger.yaml b/docs/swagger.yaml new file mode 100644 index 0000000..ed07f1f --- /dev/null +++ b/docs/swagger.yaml @@ -0,0 +1,2134 @@ +definitions: + gin.H: + additionalProperties: {} + type: object + github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct: + properties: + chat: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct: + properties: + communityJid: + type: string + groupJid: + items: + type: string + type: array + type: object + github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct: + properties: + communityName: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct: + properties: + action: + $ref: '#/definitions/whatsmeow.ParticipantChange' + groupJid: + $ref: '#/definitions/types.JID' + participants: + items: + type: string + type: array + type: object + github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct: + properties: + groupName: + type: string + participants: + items: + type: string + type: array + type: object + github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct: + properties: + groupJid: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct: + properties: + groupJid: + type: string + reset: + type: boolean + type: object + github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct: + properties: + code: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct: + properties: + groupJid: + type: string + name: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct: + properties: + groupJid: + type: string + image: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct: + properties: + immediate: + type: boolean + phone: + type: string + subscribe: + items: + type: string + type: array + webhookUrl: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct: + properties: + name: + type: string + proxy: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig' + token: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct: + properties: + phone: + type: string + subscribe: + items: + type: string + type: array + type: object + github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig: + properties: + address: + type: string + password: + type: string + port: + type: string + username: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct: + properties: + jid: + type: string + labelId: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct: + properties: + color: + type: integer + deleted: + type: boolean + labelId: + type: string + name: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct: + properties: + jid: + type: string + labelId: + type: string + messageId: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct: + properties: + isAudio: + type: boolean + number: + type: string + state: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct: + properties: + directPath: + type: string + fileEncSHA256: + items: + type: integer + type: array + fileLength: + type: integer + fileSHA256: + items: + type: integer + type: array + mediaKey: + items: + type: integer + type: array + mimetype: + type: string + url: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct: + properties: + chat: + type: string + message: + type: string + messageId: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct: + properties: + id: + items: + type: string + type: array + number: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct: + properties: + id: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct: + properties: + chat: + type: string + messageId: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct: + properties: + id: + type: string + number: + type: string + reaction: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct: + properties: + description: + type: string + name: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct: + properties: + key: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct: + properties: + before_id: + type: integer + count: + type: integer + jid: + $ref: '#/definitions/types.JID' + type: object + github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct: + properties: + jid: + $ref: '#/definitions/types.JID' + type: object + github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct: + properties: + delay: + type: integer + id: + type: string + mentionAll: + type: boolean + mentionedJid: + type: string + number: + type: string + quoted: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct' + vcard: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct' + type: object + github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct: + properties: + delay: + type: integer + description: + type: string + id: + type: string + imgUrl: + type: string + mentionAll: + type: boolean + mentionedJid: + type: string + number: + type: string + quoted: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct' + text: + type: string + title: + type: string + url: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct: + properties: + address: + type: string + delay: + type: integer + id: + type: string + latitude: + type: number + longitude: + type: number + mentionAll: + type: boolean + mentionedJid: + type: string + name: + type: string + number: + type: string + quoted: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct' + type: object + github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct: + properties: + caption: + type: string + delay: + type: integer + filename: + type: string + id: + type: string + mentionAll: + type: boolean + mentionedJid: + type: string + number: + type: string + quoted: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct' + type: + type: string + url: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct: + properties: + delay: + type: integer + id: + type: string + maxAnswer: + type: integer + mentionAll: + type: boolean + mentionedJid: + type: string + number: + type: string + options: + items: + type: string + type: array + question: + type: string + quoted: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct' + type: object + github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct: + properties: + messageId: + type: string + participant: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct: + properties: + delay: + type: integer + id: + type: string + mentionAll: + type: boolean + mentionedJid: + type: string + number: + type: string + quoted: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct' + sticker: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct: + properties: + delay: + type: integer + id: + type: string + mentionAll: + type: boolean + mentionedJid: + type: string + number: + type: string + quoted: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct' + text: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct: + properties: + number: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct: + properties: + number: + items: + type: string + type: array + type: object + github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct: + properties: + number: + type: string + preview: + type: boolean + type: object + github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct: + properties: + image: + type: string + type: object + github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct: + properties: + fullName: + type: string + organization: + type: string + phone: + type: string + type: object + types.JID: + properties: + device: + type: integer + integrator: + type: integer + rawAgent: + type: integer + server: + type: string + user: + type: string + type: object + whatsmeow.ParticipantChange: + enum: + - add + - remove + - promote + - demote + type: string + x-enum-varnames: + - ParticipantChangeAdd + - ParticipantChangeRemove + - ParticipantChangePromote + - ParticipantChangeDemote +info: + contact: {} + description: Evolution GO - whatsmeow + title: Evolution GO + version: "1.0" +paths: + /chat/archive: + post: + consumes: + - application/json + description: Archive a chat + parameters: + - description: Chat + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Archive a chat + tags: + - Chat + /chat/mute: + post: + consumes: + - application/json + description: Mute a chat + parameters: + - description: Chat + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Mute a chat + tags: + - Chat + /chat/pin: + post: + consumes: + - application/json + description: Pin a chat + parameters: + - description: Chat + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Pin a chat + tags: + - Chat + /chat/unpin: + post: + consumes: + - application/json + description: Unpin a chat + parameters: + - description: Chat + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Unpin a chat + tags: + - Chat + /community/add: + post: + consumes: + - application/json + description: Add participant to community + parameters: + - description: Participant data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Add participant to community + tags: + - Community + /community/create: + post: + consumes: + - application/json + description: Create community + parameters: + - description: Community data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Create community + tags: + - Community + /community/remove: + post: + consumes: + - application/json + description: Remove participant from community + parameters: + - description: Participant data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Remove participant from community + tags: + - Community + /group/create: + post: + consumes: + - application/json + description: Create group + parameters: + - description: Group data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Create group + tags: + - Group + /group/info: + post: + consumes: + - application/json + description: Get group info + parameters: + - description: Group data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get group info + tags: + - Group + /group/invitelink: + post: + consumes: + - application/json + description: Get group invite link + parameters: + - description: Group data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get group invite link + tags: + - Group + /group/join: + post: + consumes: + - application/json + description: Join group link + parameters: + - description: Group data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Join group link + tags: + - Group + /group/list: + get: + consumes: + - application/json + description: List groups + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: List groups + tags: + - Group + /group/myall: + get: + consumes: + - application/json + description: Get my groups + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get my groups + tags: + - Group + /group/name: + post: + consumes: + - application/json + description: Set group name + parameters: + - description: Group data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Set group name + tags: + - Group + /group/participant: + post: + consumes: + - application/json + description: Update participant + parameters: + - description: Group data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Update participant + tags: + - Group + /group/photo: + post: + consumes: + - application/json + description: Set group photo + parameters: + - description: Group data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Set group photo + tags: + - Group + /instance/all: + get: + consumes: + - application/json + description: Get all instances + produces: + - application/json + responses: + "200": + description: All instances + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get all instances + tags: + - Instance + /instance/connect: + post: + consumes: + - application/json + description: Connect to instance with the provided data + parameters: + - description: Instance data + in: body + name: instance + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct' + produces: + - application/json + responses: + "200": + description: Instance connected successfully + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Connect to instance + tags: + - Instance + /instance/create: + post: + consumes: + - application/json + description: Creates a new instance with the provided data + parameters: + - description: Instance data + in: body + name: instance + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct' + produces: + - application/json + responses: + "200": + description: Instance created successfully + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Create a new instance + tags: + - Instance + /instance/delete/{instanceId}: + delete: + consumes: + - application/json + description: Delete instance + parameters: + - description: Instance Id + in: path + name: instanceId + required: true + type: string + produces: + - application/json + responses: + "200": + description: Instance deleted successfully + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Delete instance + tags: + - Instance + /instance/disconnect: + post: + consumes: + - application/json + description: Disconnect from instance + produces: + - application/json + responses: + "200": + description: Instance disconnected successfully + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Disconnect from instance + tags: + - Instance + /instance/logout: + delete: + consumes: + - application/json + description: Logout from instance + produces: + - application/json + responses: + "200": + description: Instance logged out successfully + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Logout from instance + tags: + - Instance + /instance/pair: + post: + consumes: + - application/json + description: Request pairing code + parameters: + - description: Instance data + in: body + name: instance + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct' + produces: + - application/json + responses: + "200": + description: Pairing code + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Request pairing code + tags: + - Instance + /instance/proxy/{instanceId}: + delete: + consumes: + - application/json + description: Delete proxy + parameters: + - description: Instance id + in: path + name: instanceId + required: true + type: string + produces: + - application/json + responses: + "200": + description: Proxy deleted successfully + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Delete proxy + tags: + - Instance + /instance/qr: + get: + consumes: + - application/json + description: Get instance QR code + produces: + - application/json + responses: + "200": + description: Instance QR code + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get instance QR code + tags: + - Instance + /instance/status: + get: + consumes: + - application/json + description: Get instance status + produces: + - application/json + responses: + "200": + description: Instance status + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get instance status + tags: + - Instance + /label/chat: + post: + consumes: + - application/json + description: Add label to chat + parameters: + - description: Label data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Add label to chat + tags: + - Label + /label/edit: + post: + consumes: + - application/json + description: Edit label + parameters: + - description: Label data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Edit label + tags: + - Label + /label/message: + post: + consumes: + - application/json + description: Add label to message + parameters: + - description: Label data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Add label to message + tags: + - Label + /message/delete: + post: + consumes: + - application/json + description: Delete a message for everyone + parameters: + - description: Delete a message for everyone + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Delete a message for everyone + tags: + - Message + /message/downloadimage: + post: + consumes: + - application/json + description: Download an image + parameters: + - description: Download an image + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Download an image + tags: + - Message + /message/edit: + post: + consumes: + - application/json + description: Edit a message + parameters: + - description: Edit a message + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Edit a message + tags: + - Message + /message/markread: + post: + consumes: + - application/json + description: Mark a message as read + parameters: + - description: Mark a message as read + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Mark a message as read + tags: + - Message + /message/presence: + post: + consumes: + - application/json + description: Set chat presence + parameters: + - description: Set chat presence + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Set chat presence + tags: + - Message + /message/react: + post: + consumes: + - application/json + description: React a message + parameters: + - description: React a message + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: React a message + tags: + - Message + /message/status: + post: + consumes: + - application/json + description: Get message status + parameters: + - description: Get message status + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get message status + tags: + - Message + /newsletter/create: + post: + consumes: + - application/json + description: Create newsletter + parameters: + - description: Newsletter data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Create newsletter + tags: + - Newsletter + /newsletter/info: + post: + consumes: + - application/json + description: Get newsletter + parameters: + - description: Newsletter data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get newsletter + tags: + - Newsletter + /newsletter/link: + post: + consumes: + - application/json + description: Get newsletter invite + parameters: + - description: Newsletter data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get newsletter invite + tags: + - Newsletter + /newsletter/list: + get: + consumes: + - application/json + description: List newsletters + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: List newsletters + tags: + - Newsletter + /newsletter/messages: + post: + consumes: + - application/json + description: Get newsletter messages + parameters: + - description: Newsletter data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get newsletter messages + tags: + - Newsletter + /newsletter/subscribe: + post: + consumes: + - application/json + description: Subscribe newsletter + parameters: + - description: Newsletter data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Subscribe newsletter + tags: + - Newsletter + /send/contact: + post: + consumes: + - application/json + description: Send a contact message + parameters: + - description: Message data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Send a contact message + tags: + - Send Message + /send/link: + post: + consumes: + - application/json + description: Send a link message + parameters: + - description: Message data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Send a link message + tags: + - Send Message + /send/location: + post: + consumes: + - application/json + description: Send a location message + parameters: + - description: Message data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Send a location message + tags: + - Send Message + /send/media: + post: + consumes: + - application/json + description: Send a media message + parameters: + - description: Message data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Send a media message + tags: + - Send Message + /send/poll: + post: + consumes: + - application/json + description: Send a poll message + parameters: + - description: Message data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Send a poll message + tags: + - Send Message + /send/sticker: + post: + consumes: + - application/json + description: Send a sticker message + parameters: + - description: Message data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Send a sticker message + tags: + - Send Message + /send/text: + post: + consumes: + - application/json + description: Send a text message + parameters: + - description: Message data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Send a text message + tags: + - Send Message + /unlabel/chat: + post: + consumes: + - application/json + description: Remove label from chat + parameters: + - description: Label data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Remove label from chat + tags: + - Label + /unlabel/message: + post: + consumes: + - application/json + description: Remove label from message + parameters: + - description: Label data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Remove label from message + tags: + - Label + /user/avatar: + post: + consumes: + - application/json + description: Get a user's avatar + parameters: + - description: Avatar data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get a user's avatar + tags: + - User + /user/block: + post: + consumes: + - application/json + description: Block a contact + parameters: + - description: Block data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Block a contact + tags: + - User + /user/blocklist: + get: + consumes: + - application/json + description: Get a user's block list + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get a user's block list + tags: + - User + /user/check: + post: + consumes: + - application/json + description: Check a user + parameters: + - description: User data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Check a user + tags: + - User + /user/contacts: + get: + consumes: + - application/json + description: Get a user's contacts + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get a user's contacts + tags: + - User + /user/info: + post: + consumes: + - application/json + description: Get a user + parameters: + - description: User data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get a user + tags: + - User + /user/privacy: + get: + consumes: + - application/json + description: Get a user's privacy settings + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Get a user's privacy settings + tags: + - User + /user/profile: + post: + consumes: + - application/json + description: Set a user's profile picture + parameters: + - description: Profile picture data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Set a user's profile picture + tags: + - User + /user/unblock: + post: + consumes: + - application/json + description: Unblock a contact + parameters: + - description: Block data + in: body + name: message + required: true + schema: + $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct' + produces: + - application/json + responses: + "200": + description: success + schema: + $ref: '#/definitions/gin.H' + "400": + description: Error on validation + schema: + $ref: '#/definitions/gin.H' + "500": + description: Internal server error + schema: + $ref: '#/definitions/gin.H' + summary: Unblock a contact + tags: + - User +swagger: "2.0" diff --git a/docs/wiki/README.md b/docs/wiki/README.md new file mode 100644 index 0000000..6894dd4 --- /dev/null +++ b/docs/wiki/README.md @@ -0,0 +1,171 @@ +
+ +# 📚 Documentação Evolution GO + +**Gateway de API WhatsApp de alta performance desenvolvido em Go** + +[![Documentação: 100%](https://img.shields.io/badge/Documenta%C3%A7%C3%A3o-100%25-success?style=flat-square)]() +[![Endpoints: 79](https://img.shields.io/badge/Endpoints-79-blue?style=flat-square)]() +[![Guias: 30](https://img.shields.io/badge/Guias-30-informational?style=flat-square)]() + +
+ +--- + +Bem-vindo à documentação oficial do Evolution GO! Aqui você encontrará guias completos, referências de API e melhores práticas para integrar o WhatsApp às suas aplicações de forma profissional e escalável. + +## 🚀 Começo Rápido + +**Primeira vez aqui?** Siga este caminho: + +1. 📖 [**Introdução**](./fundamentos/introduction.md) - Entenda o que é o Evolution GO +2. 🔧 [**Instalação**](./fundamentos/installation.md) - Configure em 5 minutos +3. ⚡ [**Quickstart**](./fundamentos/quickstart.md) - Envie sua primeira mensagem +4. 📡 [**Visão Geral da API**](./guias-api/api-overview.md) - Conheça os endpoints disponíveis + +## 📖 O que você quer fazer? + +### Enviar Mensagens +- [Enviar texto, imagens e documentos](./guias-api/api-messages.md) +- [Criar enquetes interativas](./guias-api/api-messages.md#enviar-enquete) +- [Enviar localizações e contatos](./guias-api/api-messages.md#enviar-localização) + +### Gerenciar Instâncias +- [Criar e conectar instâncias](./guias-api/api-instances.md) +- [Autenticação via QR Code](./recursos-avancados/qrcode-connection.md) +- [Gerenciar múltiplas contas](./conceitos-core/instances.md) + +### Automatizar Workflows +- [Receber eventos via Webhook](./recursos-avancados/events-system.md) +- [Integrar com RabbitMQ/NATS](./recursos-avancados/events-system.md) +- [Armazenar mídias automaticamente](./recursos-avancados/media-storage.md) + +### Deploy em Produção +- [Deploy com Docker](./deploy-producao/docker-deployment.md) +- [Segurança e compliance](./deploy-producao/security.md) +- [Escalabilidade](./conceitos-core/architecture.md) + +--- + +## 📚 Documentação Completa + +### 🎯 Fundamentos + +Documentação essencial para começar a usar o Evolution GO. + +| Documento | Descrição | +|-----------|-----------| +| [**Introdução**](./fundamentos/introduction.md) | O que é o Evolution GO, recursos e casos de uso | +| [**Instalação**](./fundamentos/installation.md) | Guia completo de instalação (Docker, Local, Swarm) | +| [**Configuração**](./fundamentos/configuration.md) | Variáveis de ambiente e configurações | +| [**Quickstart**](./fundamentos/quickstart.md) | Tutorial prático: primeira instância em minutos | + +### 🏗️ Conceitos Core + +Entenda como o Evolution GO funciona por dentro. + +| Documento | Descrição | +|-----------|-----------| +| [**Arquitetura**](./conceitos-core/architecture.md) | Arquitetura em camadas, componentes e fluxos | +| [**Instâncias**](./conceitos-core/instances.md) | Como funcionam as instâncias WhatsApp | +| [**Autenticação**](./conceitos-core/authentication.md) | API Keys, tokens e segurança | +| [**Banco de Dados**](./conceitos-core/database.md) | Estrutura dual: evogo_auth + evogo_users | + +### 📡 API Reference + +Referência completa de todos os endpoints disponíveis. + +| API | Endpoints | Descrição | +|-----|-----------|-----------| +| [**Overview**](./guias-api/api-overview.md) | - | Visão geral da API REST | +| [**Instâncias**](./guias-api/api-instances.md) | 16 | Criar, conectar, gerenciar instâncias | +| [**Mensagens**](./guias-api/api-messages.md) | 16 | Enviar texto, mídia, enquetes, stickers | +| [**Usuários**](./guias-api/api-user.md) | 13 | Perfil, contatos, privacidade, bloqueio | +| [**Grupos**](./guias-api/api-groups.md) | 11 | Criar e administrar grupos | +| [**Chats**](./guias-api/api-chats.md) | 7 | Pin, archive, mute, histórico | +| [**Labels**](./guias-api/api-labels.md) | 6 | Etiquetar chats e mensagens | +| [**Chamadas**](./guias-api/api-call.md) | 1 | Rejeitar chamadas recebidas | +| [**Comunidades**](./guias-api/api-community.md) | 3 | Criar e gerenciar comunidades | +| [**Newsletters**](./guias-api/api-newsletter.md) | 6 | Canais do WhatsApp | +| [**Webhooks**](./guias-api/api-webhooks.md) | - | Configurar eventos em tempo real | + +### 🚀 Recursos Avançados + +Funcionalidades avançadas para casos de uso complexos. + +| Documento | Descrição | +|-----------|-----------| +| [**Sistema de Eventos**](./recursos-avancados/events-system.md) | Webhooks, RabbitMQ, NATS, WebSocket | +| [**Armazenamento de Mídia**](./recursos-avancados/media-storage.md) | MinIO/S3, presigned URLs | +| [**Conexão QR Code**](./recursos-avancados/qrcode-connection.md) | Fluxo de autenticação detalhado | +| [**Multi-Device**](./recursos-avancados/multi-device.md) | Protocolo Multi-Device do WhatsApp | + +### 🐳 Deploy e Produção + +Guias para colocar o Evolution GO em produção. + +| Documento | Descrição | +|-----------|-----------| +| [**Deploy com Docker**](./deploy-producao/docker-deployment.md) | Docker Compose, Swarm, Kubernetes | +| [**Segurança**](./deploy-producao/security.md) | SSL/TLS, API Keys, Firewall, Hardening | + +### 💻 Desenvolvimento + +Para desenvolvedores que querem contribuir ou personalizar. + +| Documento | Descrição | +|-----------|-----------| +| [**Guia de Desenvolvimento**](./desenvolvimento/development-guide.md) | Setup do ambiente de desenvolvimento | +| [**Como Contribuir**](./desenvolvimento/contributing.md) | Padrões de código e processo de PR | +| [**Debugging**](./desenvolvimento/debugging.md) | Troubleshooting e profiling | + +### 📖 Referência Técnica + +Consulta rápida para desenvolvedores. + +| Documento | Descrição | +|-----------|-----------| +| [**API Reference**](./referencia/api-reference.md) | Todos os 79 endpoints em uma página | +| [**Environment Variables**](./referencia/environment-variables.md) | Lista completa de variáveis de ambiente | +| [**Error Codes**](./referencia/error-codes.md) | Códigos HTTP e erros da aplicação | +| [**FAQ**](./referencia/faq.md) | Perguntas frequentes e soluções | + +--- + +## 💡 Precisa de Ajuda? + +### 📖 Recursos de Aprendizado +- **Novo no Evolution GO?** Comece pelo [Quickstart](./fundamentos/quickstart.md) +- **Dúvidas frequentes?** Confira o [FAQ](./referencia/faq.md) +- **Problemas técnicos?** Veja o guia de [Debugging](./desenvolvimento/debugging.md) + +### 🔗 Links Importantes +- 🌐 [Repositório Oficial](https://git.evoai.app/Evolution/evolution-go) +- 📚 [Biblioteca Whatsmeow](https://github.com/tulir/whatsmeow) +- 🔧 [API Swagger](http://localhost:4000/swagger/index.html) (quando servidor estiver rodando) +- 🐛 [Reportar Issues](https://git.evoai.app/Evolution/evolution-go/issues) + +### 💬 Suporte +- **Issues técnicos**: Abra uma issue no repositório +- **Dúvidas sobre API**: Consulte a [Referência da API](./referencia/api-reference.md) +- **Erros e códigos**: Veja [Códigos de Erro](./referencia/error-codes.md) + +## 🎯 Recursos Principais + +- ✅ **79 endpoints** REST documentados +- ✅ **Multi-instância** - Gerencie múltiplas contas WhatsApp +- ✅ **Multi-device** - Suporte WhatsApp Multi-Device nativo +- ✅ **Eventos em tempo real** - Webhooks, RabbitMQ, NATS, WebSocket +- ✅ **Armazenamento de mídia** - MinIO/S3 integrado +- ✅ **Alta performance** - Desenvolvido em Go +- ✅ **Docker ready** - Deploy fácil em produção + +--- + +
+ +**Mantido por EvoAI Services** • **Versão da Documentação: 1.0.0** + +[⬆️ Voltar ao topo](#-documentação-evolution-go) + +
diff --git a/docs/wiki/conceitos-core/architecture.md b/docs/wiki/conceitos-core/architecture.md new file mode 100644 index 0000000..bc9b765 --- /dev/null +++ b/docs/wiki/conceitos-core/architecture.md @@ -0,0 +1,540 @@ +# Arquitetura + +Como o Evolution GO está organizado por dentro - explicado de forma simples. + +## 📋 Índice + +- [Visão Geral](#visão-geral) +- [Arquitetura em 3 Camadas](#arquitetura-em-3-camadas) +- [Componentes Principais](#componentes-principais) +- [Como Funciona uma Requisição](#como-funciona-uma-requisição) +- [Organização de Pastas](#organização-de-pastas) +- [Tecnologias Usadas](#tecnologias-usadas) + +--- + +## Visão Geral + +O Evolution GO é organizado em **3 camadas** separadas. Pense nisso como uma lanchonete: + +1. **Atendente** (Handler) - Recebe seu pedido +2. **Cozinha** (Service) - Prepara o pedido +3. **Estoque** (Repository) - Busca os ingredientes + +Cada parte tem uma função específica e não faz o trabalho das outras. + +### Por que Separar? + +**Vantagens**: +- **Organização**: Cada coisa no seu lugar +- **Manutenção**: Fácil de encontrar e corrigir problemas +- **Testes**: Pode testar cada parte separadamente +- **Escalabilidade**: Fácil de crescer e adicionar funcionalidades + +--- + +## Arquitetura em 3 Camadas + +### Camada 1: Handler (Atendente) + +**O que faz**: Recebe requisições HTTP e responde ao cliente. + +**Responsabilidades**: +- Receber dados do cliente (JSON, formulários) +- Validar se os dados estão corretos +- Chamar o Service para fazer o trabalho +- Devolver a resposta (sucesso ou erro) + +**Analogia**: Como o atendente de um restaurante +- Recebe seu pedido +- Anota tudo certinho +- Passa para a cozinha +- Traz sua comida quando fica pronta + +**Exemplo do mundo real**: +``` +Cliente: "Quero enviar uma mensagem para o número 11999999999" +Handler: "Ok, deixa eu passar isso para o Service..." +Service: "Mensagem enviada!" +Handler: "Pronto, sua mensagem foi enviada!" +``` + +### Camada 2: Service (Cozinha) + +**O que faz**: Implementa a lógica de negócio - onde acontece a "mágica". + +**Responsabilidades**: +- Aplicar regras de negócio +- Coordenar entre diferentes partes do sistema +- Validar dados complexos +- Gerenciar transações +- Decidir o que fazer + +**Analogia**: Como a cozinha do restaurante +- Recebe o pedido do atendente +- Prepara a comida seguindo a receita +- Coordena entre fogão, forno, geladeira +- Entrega o prato pronto + +**Exemplo do mundo real**: +``` +Service recebe: "Enviar mensagem para 11999999999" + +Service faz: +1. Busca a instância do WhatsApp +2. Verifica se está conectada +3. Formata o número corretamente +4. Monta a mensagem +5. Envia via WhatsApp +6. Salva no banco de dados +7. Avisa o webhook (se tiver) +8. Retorna "Sucesso!" +``` + +### Camada 3: Repository (Estoque) + +**O que faz**: Gerencia os dados do banco de dados. + +**Responsabilidades**: +- Salvar dados no banco +- Buscar dados do banco +- Atualizar dados existentes +- Deletar dados + +**Analogia**: Como o estoque do restaurante +- Guarda os ingredientes +- Entrega quando a cozinha pede +- Recebe novos ingredientes +- Organiza tudo + +**Exemplo do mundo real**: +``` +Service: "Preciso das informações da instância 'vendas'" +Repository: "Deixa eu buscar no banco... Aqui está!" + +Service: "Salva essa mensagem no banco" +Repository: "Ok, salvei!" +``` + +--- + +## Componentes Principais + +### 1. Whatsmeow Service + +**O que é**: O componente que faz a conexão com o WhatsApp. + +**Analogia**: É o "telefone" do sistema. Cada instância tem seu próprio "telefone" para falar com o WhatsApp. + +**Funções**: +- Conectar ao WhatsApp +- Manter a conexão ativa +- Enviar mensagens +- Receber mensagens +- Gerenciar sessões + +### 2. Event Producer + +**O que é**: Componente que avisa outros sistemas quando algo acontece. + +**Analogia**: Como um carteiro que entrega notificações. + +**Tipos de notificação**: +- **Webhook**: Envia para uma URL sua +- **RabbitMQ**: Envia para fila de mensagens +- **WebSocket**: Envia em tempo real +- **NATS**: Envia para sistema de eventos + +**Exemplos de eventos**: +- "Nova mensagem recebida!" +- "QR Code gerado!" +- "Cliente desconectou!" + +### 3. Storage Service + +**O que é**: Componente que guarda arquivos (fotos, vídeos, áudios). + +**Opções**: +- **MinIO/S3**: Para produção (servidor na nuvem) +- **Local**: Para desenvolvimento (pasta no computador) + +**Analogia**: Como um HD externo onde ficam salvos os arquivos. + +### 4. Config Service + +**O que é**: Componente que carrega as configurações do sistema. + +**O que configura**: +- Porta do servidor +- Conexão com banco de dados +- API Keys +- URLs de webhooks +- Configurações do WhatsApp + +**Analogia**: Como as "regras da casa" - tudo que precisa ser configurado fica aqui. + +--- + +## Como Funciona uma Requisição + +### Exemplo: Enviar uma Mensagem de Texto + +``` +1. VOCÊ + │ + │ POST /send/text + │ {"number": "11999999999", "text": "Olá!"} + │ + ▼ +2. HANDLER (Atendente) + │ + │ "Recebeu um pedido, vou validar..." + │ ✓ JSON está correto + │ ✓ Campos obrigatórios presentes + │ + ▼ +3. SERVICE (Cozinha) + │ + │ "Vou preparar o envio da mensagem..." + │ 1. Buscar cliente WhatsApp + │ 2. Verificar se está conectado + │ 3. Formatar número (11999999999 → 5511999999999@s.whatsapp.net) + │ 4. Montar mensagem + │ + ▼ +4. WHATSAPP + │ + │ "Enviando mensagem..." + │ ✓ Mensagem enviada + │ Retorna ID: msg_123456 + │ + ▼ +5. SERVICE (continuação) + │ + │ "Mensagem enviada! Agora vou registrar..." + │ → Salvar no banco via REPOSITORY + │ → Avisar webhook via EVENT PRODUCER + │ + ▼ +6. HANDLER (continuação) + │ + │ "Tudo certo! Vou responder o cliente..." + │ + ▼ +7. VOCÊ + │ + │ Recebe resposta: + │ {"status": "success", "messageId": "msg_123456"} +``` + +### Tempo Total + +Tudo isso acontece em menos de 1 segundo! ⚡ + +--- + +## Organização de Pastas + +### Estrutura Simplificada + +``` +evolution-go/ +│ +├── cmd/ +│ └── evolution-go/ +│ └── main.go ← Arquivo principal (inicia tudo) +│ +├── pkg/ ← Código principal +│ │ +│ ├── instance/ ← Gerenciar instâncias +│ │ ├── handler/ ← Recebe requisições HTTP +│ │ ├── service/ ← Lógica de negócio +│ │ ├── repository/ ← Acesso ao banco +│ │ └── model/ ← Estrutura de dados +│ │ +│ ├── message/ ← Gerenciar mensagens +│ │ ├── handler/ +│ │ ├── service/ +│ │ ├── repository/ +│ │ └── model/ +│ │ +│ ├── group/ ← Gerenciar grupos +│ ├── user/ ← Gerenciar usuários +│ ├── chat/ ← Gerenciar chats +│ │ +│ ├── whatsmeow/ ← Conexão WhatsApp +│ ├── events/ ← Sistema de eventos +│ ├── storage/ ← Armazenar arquivos +│ └── config/ ← Configurações +│ +├── docs/ ← Documentação +├── logs/ ← Arquivos de log +└── .env ← Configurações (senhas, chaves) +``` + +### Padrão de Organização + +Cada funcionalidade tem a mesma estrutura: + +``` +funcionalidade/ +├── handler/ ← Recebe requisições +├── service/ ← Processa lógica +├── repository/ ← Acessa banco +└── model/ ← Define estruturas +``` + +**Exemplo**: Para enviar mensagens, você tem: +- `message/handler/` - Recebe a requisição +- `message/service/` - Prepara e envia +- `message/repository/` - Salva no banco +- `message/model/` - Define como é uma mensagem + +--- + +## Tecnologias Usadas + +### Framework Web + +**Gin** - Framework HTTP para Go +- Rápido e leve +- Fácil de usar +- Gerencia rotas e middlewares + +**O que faz**: Recebe requisições HTTP e encaminha para os handlers. + +### Cliente WhatsApp + +**Whatsmeow** - Biblioteca oficial +- Implementa protocolo do WhatsApp Web +- Multi-dispositivo +- Criptografia ponta-a-ponta + +**O que faz**: Conversa com os servidores do WhatsApp. + +### Banco de Dados + +**GORM** - ORM (Mapeador Objeto-Relacional) +- Facilita trabalhar com banco de dados +- Suporta PostgreSQL e SQLite +- Migrations automáticas + +**O que faz**: Converte dados entre o código e o banco de dados. + +### Filas de Mensagem + +**RabbitMQ** - Sistema de filas +**NATS** - Sistema de eventos +- Entregam notificações de forma confiável +- Processamento assíncrono + +**O que fazem**: Avisam outros sistemas quando algo acontece. + +### Armazenamento de Arquivos + +**MinIO** - Storage compatível com S3 +- Armazena fotos, vídeos, áudios +- Escalável + +**O que faz**: Guarda arquivos de mídia enviados/recebidos. + +### Utilitários + +**QRCode** - Gera QR Codes +**UUID** - Gera IDs únicos +**WebSocket** - Comunicação em tempo real +**Zap Logger** - Logs estruturados + +--- + +## Ciclo de Vida de uma Instância + +### Estados + +``` +1. CRIADA + ↓ + (usuário cria via API) + ↓ +2. DESCONECTADA + ↓ + (usuário conecta) + ↓ +3. CONECTANDO + ↓ + (gera QR Code) + ↓ +4. AGUARDANDO SCAN + ↓ + (usuário escaneia QR no celular) + ↓ +5. ABERTA/CONECTADA + ↓ + (pode enviar/receber mensagens) + ↓ + (se desconectar) + ↓ +6. DESCONECTADA + ↓ + (pode reconectar sem QR) + ↓ +5. ABERTA/CONECTADA +``` + +### Ações Possíveis + +| Estado | O que Pode Fazer | +|--------|------------------| +| **Criada** | Conectar, Deletar | +| **Desconectada** | Conectar, Reconectar, Deletar | +| **Conectando** | Aguardar, Cancelar | +| **Aguardando QR** | Escanear QR, Timeout | +| **Aberta** | Enviar mensagens, Desconectar, Logout | + +--- + +## Segurança + +### 1. Autenticação + +Todas as requisições precisam de API Key: +- Administrador: API Key Global +- Instância: Token específico + +### 2. Isolamento + +Cada instância é completamente isolada: +- Não pode acessar dados de outras instâncias +- Tem seu próprio cliente WhatsApp +- Sessão separada no banco + +### 3. Validação + +Todos os dados são validados antes de processar: +- Formato de número de telefone +- Tamanho de mensagens +- Tipos de arquivo permitidos + +### 4. Criptografia + +WhatsApp usa criptografia ponta-a-ponta: +- Mensagens criptografadas automaticamente +- Chaves guardadas de forma segura +- Ninguém pode interceptar + +--- + +## Escalabilidade + +### Horizontal (Mais Servidores) + +Pode ter múltiplas cópias do Evolution GO: + +``` + ┌─────────────────┐ + │ Load Balancer │ + └────────┬─────────┘ + │ + ┌───────────┼───────────┐ + │ │ │ + ┌────▼───┐ ┌───▼────┐ ┌───▼────┐ + │Server 1│ │Server 2│ │Server 3│ + └────┬───┘ └───┬────┘ └───┬────┘ + │ │ │ + └──────────┼───────────┘ + │ + ┌──────▼──────┐ + │ PostgreSQL │ + └─────────────┘ +``` + +**Vantagens**: +- Suporta mais usuários +- Se um servidor cair, outros continuam +- Distribuição de carga + +### Vertical (Servidor Mais Potente) + +Melhorar o servidor existente: +- Mais CPU +- Mais RAM +- Mais espaço em disco + +**Quando usar**: +- Até ~100 instâncias: Vertical +- Mais de 100: Horizontal + +--- + +## Resumo Visual + +### Fluxo Completo + +``` + REQUISIÇÃO + ↓ + ┌────────┐ + │Handler │ ← Valida dados + └───┬────┘ + ↓ + ┌────────┐ + │Service │ ← Aplica lógica + └───┬────┘ + ↓ + ┌────────────┐ + │Repository │ ← Salva/busca dados + └───┬────────┘ + ↓ + ┌────────┐ + │Database│ + └────────┘ +``` + +### Componentes Interconectados + +``` +┌──────────────────────────────────┐ +│ Evolution GO Server │ +├──────────────────────────────────┤ +│ │ +│ ┌────────┐ ┌───────────┐ │ +│ │Handler │─────>│ Service │ │ +│ └────────┘ └─────┬─────┘ │ +│ │ │ +│ ┌──────────────┼────────┐│ +│ │ │ ││ +│ ┌────▼───┐ ┌────▼────┐ ││ +│ │Whatsapp│ │Repository ││ +│ │Service │ └────┬────┘ ││ +│ └────┬───┘ │ ││ +└─────────┼─────────────┼────────┘│ + │ │ + ┌───▼────┐ ┌───▼───┐ + │WhatsApp│ │ DB │ + │Servers │ │ │ + └────────┘ └───────┘ +``` + +--- + +## Resumo Rápido + +| Conceito | Explicação Simples | +|----------|-------------------| +| **Handler** | Atendente - recebe pedidos | +| **Service** | Cozinha - prepara tudo | +| **Repository** | Estoque - guarda dados | +| **Whatsmeow** | Telefone - fala com WhatsApp | +| **Events** | Carteiro - avisa outros sistemas | +| **Storage** | HD - guarda arquivos | + +**Lembre-se**: +- 📱 Cada camada tem uma função específica +- 🔄 Requisição passa por todas as camadas +- 🏗️ Organização facilita manutenção +- 🚀 Pode escalar horizontal ou verticalmente +- 🔒 Segurança em todas as camadas + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/conceitos-core/authentication.md b/docs/wiki/conceitos-core/authentication.md new file mode 100644 index 0000000..86464c6 --- /dev/null +++ b/docs/wiki/conceitos-core/authentication.md @@ -0,0 +1,452 @@ +# Autenticação + +Sistema de autenticação do Evolution GO usando chaves de acesso (API Keys). + +## 📋 Índice + +- [Visão Geral](#visão-geral) +- [Dois Tipos de Chave](#dois-tipos-de-chave) +- [API Key Global](#api-key-global) +- [Token de Instância](#token-de-instância) +- [Como Usar](#como-usar) +- [Fluxos de Autenticação](#fluxos-de-autenticação) +- [Segurança](#segurança) + +--- + +## Visão Geral + +O Evolution GO usa **chaves de acesso** (API Keys) para proteger sua API. Pense nisso como senhas especiais que você precisa enviar em cada requisição. + +### Como Funciona + +Imagine um prédio com dois tipos de chave: +- **Chave Master (Admin)**: Abre todas as portas, permite criar/deletar salas +- **Chave Individual (Instância)**: Abre apenas uma sala específica + +É assim que funciona a autenticação no Evolution GO! + +**Importante**: Não usamos login/senha tradicional, JWT ou cookies. Apenas chaves simples! + +--- + +## Dois Tipos de Chave + +### 1. API Key Global (Admin) + +**O que é**: A chave mestre do sistema. Quem tem essa chave controla tudo. + +**Para que serve**: +- Criar novas instâncias do WhatsApp +- Deletar instâncias existentes +- Ver todas as instâncias do sistema +- Gerenciar configurações globais + +**Como usar**: +``` +Envie no header da requisição: +apikey: sua-chave-global-aqui +``` + +**Exemplo prático**: +```bash +# Criar uma instância nova +POST /instance/create +Header: apikey: minha-chave-master-123 +``` + +### 2. Token de Instância + +**O que é**: A chave individual de cada WhatsApp conectado. + +**Para que serve**: +- Enviar mensagens +- Criar grupos +- Gerenciar contatos +- Todas as operações do WhatsApp dessa instância + +**Como usar**: +``` +Envie no header da requisição: +apikey: token-da-sua-instancia +``` + +**Exemplo prático**: +```bash +# Enviar uma mensagem +POST /send/text +Header: apikey: token-vendas-123 +``` + +--- + +## API Key Global + +### Configurando + +A API Key Global é definida como uma variável de ambiente: + +```env +GLOBAL_API_KEY=minha-chave-super-secreta +``` + +### Gerando uma Chave Segura + +**Recomendado** (Linux/Mac): +```bash +# Gera uma chave aleatória forte +openssl rand -base64 32 +``` + +Resultado exemplo: +``` +dGhpc2lzYXNlY3VyZWtleXRoYXRpc3Zlcnlsb25nYW5kc2VjdXJl +``` + +**Não use chaves óbvias**: +- ❌ `123456` +- ❌ `admin` +- ❌ `minha-senha` + +### Onde é Usado + +**Endpoints que precisam da API Key Global**: +- Criar instância: `POST /instance/create` +- Deletar instância: `DELETE /instance/delete/:id` +- Listar todas: `GET /instance/all` +- Ver informações: `GET /instance/info/:id` +- Configurar proxy: `POST /instance/proxy/:id` +- Ver logs: `GET /instance/logs/:id` + +--- + +## Token de Instância + +### O que é + +Cada instância do WhatsApp tem seu próprio token único. É como o CPF da instância - identifica ela no sistema. + +### Como Obter + +**Opção 1: Sistema gera automaticamente** +```json +POST /instance/create +{ + "name": "vendas" +} + +Resposta: +{ + "id": "abc-123", + "name": "vendas", + "token": "token-gerado-automaticamente-xyz789" +} +``` + +**Opção 2: Você define o token** +```json +POST /instance/create +{ + "name": "vendas", + "token": "meu-token-customizado-vendas" +} +``` + +⚠️ **Atenção**: O token deve ser único no sistema! + +### Onde é Usado + +**Endpoints que precisam do Token de Instância**: + +**Mensagens**: +- Enviar texto: `POST /send/text` +- Enviar mídia: `POST /send/media` +- Enviar áudio: `POST /send/audio` +- Reagir: `POST /message/react` +- Marcar como lida: `POST /message/markread` + +**Grupos**: +- Listar grupos: `GET /group/list` +- Criar grupo: `POST /group/create` +- Adicionar participante: `POST /group/participant` +- Sair do grupo: `POST /group/leave` + +**Usuários**: +- Ver informações: `POST /user/info` +- Bloquear: `POST /user/block` +- Desbloquear: `POST /user/unblock` +- Ver contatos: `GET /user/contacts` + +--- + +## Como Usar + +### Formato do Header HTTP + +Todas as requisições devem incluir o header `apikey`: + +``` +apikey: sua-chave-aqui +``` + +**NÃO use**: +``` +❌ Authorization: Bearer sua-chave +❌ apikey: Bearer sua-chave +``` + +### Exemplos Práticos + +**1. Criando uma instância (usa API Key Global)**: +```bash +curl -X POST http://localhost:4000/instance/create \ + -H "Content-Type: application/json" \ + -H "apikey: minha-chave-global" \ + -d '{"name": "vendas", "token": "token-vendas"}' +``` + +**2. Enviando mensagem (usa Token da Instância)**: +```bash +curl -X POST http://localhost:4000/send/text \ + -H "Content-Type: application/json" \ + -H "apikey: token-vendas" \ + -d '{ + "number": "5511999999999", + "text": "Olá!" + }' +``` + +**3. Com JavaScript**: +```javascript +fetch('http://localhost:4000/send/text', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'apikey': 'token-vendas' + }, + body: JSON.stringify({ + number: '5511999999999', + text: 'Olá!' + }) +}); +``` + +--- + +## Fluxos de Autenticação + +### Fluxo 1: Criar Instância + +``` +1. Você ─────> API + POST /instance/create + apikey: CHAVE-GLOBAL + +2. API verifica ─────> ✓ Chave Global OK + +3. API cria instância ─────> Banco de Dados + +4. API retorna ─────> Você + { + "name": "vendas", + "token": "token-vendas-123" + } +``` + +### Fluxo 2: Enviar Mensagem + +``` +1. Você ─────> API + POST /send/text + apikey: token-vendas-123 + +2. API busca ─────> Banco de Dados + "Qual instância tem esse token?" + +3. Banco responde ─────> API + "É a instância 'vendas'" + +4. API envia mensagem ─────> WhatsApp + +5. API retorna ─────> Você + {"status": "success"} +``` + +### Fluxo 3: Chave Inválida + +``` +1. Você ─────> API + POST /send/text + apikey: token-errado + +2. API busca ─────> Banco de Dados + "Qual instância tem esse token?" + +3. Banco responde ─────> API + "Token não encontrado!" + +4. API retorna ERRO ─────> Você + 401 Unauthorized + {"error": "not authorized"} +``` + +--- + +## Segurança + +### 1. Protegendo a API Key Global + +**❌ NUNCA faça isso**: +- Compartilhar no Slack, email ou WhatsApp +- Salvar em arquivos públicos no GitHub +- Usar valores óbvios como "admin" ou "123456" +- Colocar no código-fonte + +**✅ SEMPRE faça isso**: +- Salvar em arquivo `.env` (e adicionar ao `.gitignore`) +- Usar gerenciadores de secrets (Vault, AWS Secrets) +- Gerar chaves fortes (32+ caracteres aleatórios) +- Rotacionar periodicamente (trocar a chave) + +### 2. Protegendo Tokens de Instância + +**❌ NUNCA faça isso**: +- Colocar tokens na URL (`?token=...`) +- Salvar tokens em logs +- Expor tokens em páginas públicas + +**✅ SEMPRE faça isso**: +- Enviar apenas via header HTTP +- Usar HTTPS em produção +- Guardar em local seguro (variáveis de ambiente) + +### 3. Use HTTPS em Produção + +⚠️ **CRÍTICO**: Em produção, sempre use HTTPS! + +``` +✅ https://api.suaempresa.com/send/text +❌ http://api.suaempresa.com/send/text +``` + +Sem HTTPS, suas chaves trafegam em **texto puro** pela internet e podem ser interceptadas. + +### 4. Rotação de Chaves + +Se uma chave foi comprometida: + +**Para API Key Global**: +1. Gere uma nova chave forte +2. Atualize a variável `GLOBAL_API_KEY` no servidor +3. Reinicie a aplicação +4. Atualize todos os clientes que usam a API + +**Para Token de Instância**: +1. Crie uma nova instância com novo token +2. Migre seus dados +3. Delete a instância antiga + +💡 Não há como "trocar" um token existente - você precisa criar uma nova instância. + +### 5. Monitorando Acessos + +**Sinais de problema**: +- Muitas tentativas com chaves inválidas +- Acessos de IPs desconhecidos +- Horários estranhos de acesso + +**Recomendação**: Configure logs e alertas para tentativas de acesso não autorizado. + +--- + +## Exemplos do Dia a Dia + +### Cenário 1: Primeiro Uso + +```bash +# 1. Configure a chave global no servidor +echo "GLOBAL_API_KEY=$(openssl rand -base64 32)" >> .env + +# 2. Inicie o servidor +docker-compose up -d + +# 3. Crie sua primeira instância +curl -X POST http://localhost:4000/instance/create \ + -H "apikey: $(grep GLOBAL_API_KEY .env | cut -d '=' -f2)" \ + -H "Content-Type: application/json" \ + -d '{"name": "vendas"}' + +# Guarde o token que foi retornado! +``` + +### Cenário 2: Múltiplas Instâncias + +```bash +# Vendas +curl -X POST http://localhost:4000/send/text \ + -H "apikey: token-vendas" \ + -d '{"number": "5511111111", "text": "Equipe vendas"}' + +# Suporte +curl -X POST http://localhost:4000/send/text \ + -H "apikey: token-suporte" \ + -d '{"number": "5522222222", "text": "Equipe suporte"}' +``` + +Cada instância é independente e usa seu próprio token! + +--- + +## Troubleshooting + +### Erro: "not authorized" + +**Possíveis causas**: +1. Header `apikey` está faltando +2. Valor da chave está errado +3. Usando chave global onde precisa token de instância (ou vice-versa) + +**Como resolver**: +```bash +# Verifique se o header está sendo enviado +curl -v http://localhost:4000/send/text + +# Confirme o valor no .env +cat .env | grep GLOBAL_API_KEY + +# Liste suas instâncias para ver os tokens +curl -H "apikey: sua-chave-global" http://localhost:4000/instance/all +``` + +### Token não funciona após reiniciar + +**Causa**: Tokens ficam salvos no banco e não mudam. + +**Solução**: Use o mesmo token que foi fornecido na criação da instância. + +### Esqueci minha API Key Global + +**Solução**: +1. Acesse o servidor +2. Veja o arquivo `.env` +3. Procure por `GLOBAL_API_KEY` + +--- + +## Resumo Rápido + +| Tipo | Quando Usar | Exemplo | +|------|-------------|---------| +| **API Key Global** | Criar/deletar instâncias | `apikey: minha-chave-master` | +| **Token Instância** | Enviar mensagens, criar grupos | `apikey: token-vendas-123` | + +**Lembre-se**: +- 🔑 API Key Global = Chave mestre (admin) +- 🎫 Token Instância = Chave de uma sala específica +- 🔒 Sempre use HTTPS em produção +- 📝 Guarde suas chaves em local seguro +- 🚫 Nunca compartilhe chaves publicamente + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/conceitos-core/database.md b/docs/wiki/conceitos-core/database.md new file mode 100644 index 0000000..ae55aab --- /dev/null +++ b/docs/wiki/conceitos-core/database.md @@ -0,0 +1,425 @@ +# Banco de Dados + +Sistema de armazenamento de dados do Evolution GO usando bancos separados para diferentes finalidades. + +## 📋 Índice + +- [Visão Geral](#visão-geral) +- [Por que Dois Bancos](#por-que-dois-bancos) +- [Banco Auth](#banco-auth) +- [Banco Users](#banco-users) +- [Tabelas Principais](#tabelas-principais) +- [Como os Dados se Relacionam](#como-os-dados-se-relacionam) +- [Boas Práticas](#boas-práticas) + +--- + +## Visão Geral + +O Evolution GO usa **dois bancos de dados separados**. Pense nisso como ter dois armários diferentes: + +1. **Banco Auth** (`evogo_auth`): Guarda os dados técnicos do WhatsApp +2. **Banco Users** (`evogo_users`): Guarda os dados da sua aplicação + +### Tipos de Banco Suportados + +- **PostgreSQL**: Recomendado para produção (servidores reais) +- **SQLite**: Usado para desenvolvimento e testes (arquivo local) + +--- + +## Por que Dois Bancos + +### Analogia do Armário + +Imagine que você tem uma loja: +- **Armário 1** (Auth): Guarda as chaves, segredos e equipamentos técnicos +- **Armário 2** (Users): Guarda produtos, clientes e vendas + +É mais organizado e seguro manter separado! + +### Vantagens + +1. **Organização**: Dados do WhatsApp separados dos dados da sua API +2. **Segurança**: Backup independente para cada tipo de dado +3. **Performance**: Cada banco pode ser otimizado para seu uso +4. **Escalabilidade**: Pode colocar cada banco em um servidor diferente + +--- + +## Banco Auth + +### O que Guarda + +Todos os dados técnicos do WhatsApp (biblioteca whatsmeow): + +- **Chaves de criptografia** - Para proteger suas mensagens +- **Informações do dispositivo** - Identificação do seu WhatsApp +- **Sessões ativas** - Conexões abertas +- **Contatos sincronizados** - Lista de contatos + +### Tabelas Importantes + +O WhatsApp cria automaticamente várias tabelas: + +1. **whatsmeow_device** - Seu "telefone virtual" +2. **whatsmeow_identity_keys** - Chaves de segurança +3. **whatsmeow_sessions** - Sessões de conversa +4. **whatsmeow_contacts** - Lista de contatos +5. ... e outras 6-7 tabelas técnicas + +⚠️ **IMPORTANTE**: Não mexa nessas tabelas manualmente! O WhatsApp gerencia tudo automaticamente. + +### Por que é Crítico + +Este banco contém as **chaves de criptografia**. Sem backup dele: +- ✅ Com backup: Reconecta automaticamente após reiniciar +- ❌ Sem backup: Precisa escanear QR Code novamente + +--- + +## Banco Users + +### O que Guarda + +Todos os dados da **sua aplicação**: + +- **Instâncias** - Cada WhatsApp conectado +- **Mensagens** - Histórico de mensagens enviadas +- **Labels** - Etiquetas/marcações +- **Configurações** - Webhooks, eventos, etc. + +### Tabelas Principais + +#### 1. Tabela `instances` + +**O que é**: A tabela mais importante! Cada linha é um WhatsApp conectado. + +**Informações guardadas**: +- **id**: Identificador único (tipo CPF) +- **name**: Nome amigável (ex: "vendas", "suporte") +- **token**: Chave de acesso da instância +- **webhook**: URL para receber eventos +- **jid**: Número do WhatsApp (ex: 5511999999999@s.whatsapp.net) +- **connected**: Está conectado? (true/false) +- **qrcode**: QR Code para conectar +- **events**: Quais eventos quer receber + +**Configurações Avançadas**: +- **always_online**: Aparecer sempre online +- **reject_call**: Rejeitar chamadas automaticamente +- **read_messages**: Marcar mensagens como lidas +- **ignore_groups**: Ignorar mensagens de grupo +- **ignore_status**: Ignorar status/stories + +#### 2. Tabela `messages` + +**O que é**: Histórico de mensagens (opcional, pode ser desabilitado). + +**Informações guardadas**: +- **id**: Identificador único +- **message_id**: ID da mensagem no WhatsApp +- **timestamp**: Quando foi enviada +- **status**: Status (enviada, entregue, lida) +- **source**: De qual instância veio + +💡 **Dica**: Por padrão, não salvamos o conteúdo completo das mensagens por questão de espaço. + +#### 3. Tabela `labels` + +**O que é**: Etiquetas/marcações do WhatsApp. + +**Informações guardadas**: +- **id**: Identificador único +- **instance_id**: De qual instância +- **label_name**: Nome da etiqueta (ex: "Cliente VIP") +- **label_color**: Cor da etiqueta (0-19) + +--- + +## Tabelas Principais + +### Estrutura Visual + +``` +┌──────────────┐ +│ instances │ (Tabela Principal) +│ │ +│ - id │◄─────────┐ +│ - name │ │ +│ - token │ │ Relacionamento +│ - connected │ │ +└──────────────┘ │ + │ + ┌──────────────┴──────────────┐ + │ │ + ┌──────▼──────┐ ┌───────▼──────┐ + │ messages │ │ labels │ + │ │ │ │ + │ - id │ │ - id │ + │ - source ───┼─────┐ │ - instance_id│───┐ + │ (FK) │ │ │ (FK) │ │ + └─────────────┘ │ └──────────────┘ │ + │ │ + └────── Aponta para ────────┘ + instances.id +``` + +**FK = Foreign Key (Chave Estrangeira)** +- Significa que aponta para outra tabela +- Como um "link" entre tabelas + +### Quando Deleta uma Instância + +Se você deletar uma instância, automaticamente deleta: +- ✅ Todas as mensagens dessa instância +- ✅ Todas as labels dessa instância + +Isso se chama **deleção em cascata** - como um efeito dominó! + +--- + +## Como os Dados se Relacionam + +### Exemplo Prático + +Imagine que você tem: + +**1 Instância**: +``` +ID: abc-123 +Nome: vendas +Token: token-vendas-123 +``` + +**3 Mensagens desta instância**: +``` +Mensagem 1: source = abc-123 +Mensagem 2: source = abc-123 +Mensagem 3: source = abc-123 +``` + +**2 Labels desta instância**: +``` +Label 1: instance_id = abc-123 +Label 2: instance_id = abc-123 +``` + +Se você deletar a instância `abc-123`: +- ❌ Instância deletada +- ❌ 3 mensagens deletadas automaticamente +- ❌ 2 labels deletadas automaticamente + +--- + +## Configuração + +### Variáveis de Ambiente + +```env +# Banco Auth (Dados do WhatsApp) +POSTGRES_AUTH_DB=postgresql://user:pass@localhost:5432/evogo_auth + +# Banco Users (Dados da API) +POSTGRES_USERS_DB=postgresql://user:pass@localhost:5432/evogo_users +``` + +### Criação Automática de Tabelas + +Quando você inicia o Evolution GO pela primeira vez: + +1. Sistema verifica se as tabelas existem +2. Se não existir, cria automaticamente +3. Se existir, apenas conecta +4. **Nunca remove ou altera tabelas existentes** (seguro!) + +Isso se chama **Auto-Migration** (migração automática). + +--- + +## Boas Práticas + +### 1. Faça Backup Regular + +**Recomendado**: Backup diário automático + +```bash +# Backup do banco Auth (CRÍTICO!) +pg_dump -U postgres evogo_auth > backup_auth_$(date +%Y%m%d).sql + +# Backup do banco Users +pg_dump -U postgres evogo_users > backup_users_$(date +%Y%m%d).sql +``` + +💡 O backup do **Auth** é mais crítico pois contém as chaves de criptografia! + +### 2. Monitorar Espaço + +Tabelas crescem com o tempo: + +| Tabela | Crescimento | +|--------|-------------| +| **messages** | Rápido (se salvar mensagens) | +| **instances** | Lento | +| **labels** | Lento | +| **whatsmeow_***| Médio | + +**Recomendação**: Limpar mensagens antigas regularmente. + +### 3. Connection Pooling + +**O que é**: Reutilizar conexões ao banco ao invés de abrir/fechar toda hora. + +**Configurações recomendadas**: + +**Desenvolvimento** (computador local): +- Máximo 20 conexões simultâneas +- 5 conexões em stand-by + +**Produção** (servidor): +- Máximo 100 conexões simultâneas +- 25 conexões em stand-by + +### 4. Índices para Performance + +**O que são índices**: Como um índice de livro - ajuda a encontrar coisas mais rápido! + +**Índices importantes já criados**: +- `instances.name` - Buscar por nome +- `instances.token` - Buscar por token +- `messages.source` - Buscar mensagens de uma instância +- `labels.instance_id` - Buscar labels de uma instância + +### 5. Limpeza de Dados + +**Recomendações**: + +```bash +# Deletar mensagens com mais de 90 dias +DELETE FROM messages WHERE timestamp < NOW() - INTERVAL '90 days'; + +# Deletar instâncias desconectadas há mais de 30 dias +DELETE FROM instances +WHERE connected = false +AND updated_at < NOW() - INTERVAL '30 days'; +``` + +--- + +## Troubleshooting + +### Erro: "too many connections" + +**Problema**: Muitas conexões abertas ao banco. + +**Soluções**: +1. Verifique quantas conexões o PostgreSQL permite +2. Reduza o número de conexões máximas no Evolution GO +3. Aumente o limite no PostgreSQL + +```bash +# Ver limite atual +psql -c "SHOW max_connections;" + +# Aumentar para 200 (editar postgresql.conf) +max_connections = 200 +``` + +### Erro: "table does not exist" + +**Problema**: Tabela não foi criada. + +**Solução**: Reinicie a aplicação. Ela cria as tabelas automaticamente. + +### Banco crescendo muito + +**Problema**: Banco de dados está ocupando muito espaço. + +**Diagnóstico**: +```sql +-- Ver tamanho de cada tabela +SELECT + tablename, + pg_size_pretty(pg_total_relation_size(tablename::text)) as size +FROM pg_tables +WHERE schemaname = 'public' +ORDER BY pg_total_relation_size(tablename::text) DESC; +``` + +**Solução**: Limpe mensagens antigas ou desabilite o salvamento de mensagens. + +### Queries lentas + +**Problema**: Operações demorando muito. + +**Solução**: Provavelmente falta um índice. Consulte um DBA (administrador de banco de dados). + +--- + +## Resumo Visual + +### Separação de Responsabilidades + +``` +┌────────────────────────┐ ┌────────────────────────┐ +│ Banco Auth │ │ Banco Users │ +│ (evogo_auth) │ │ (evogo_users) │ +├────────────────────────┤ ├────────────────────────┤ +│ │ │ │ +│ WhatsApp │ │ Sua Aplicação │ +│ Dados Técnicos │ │ Dados de Negócio │ +│ │ │ │ +│ • Chaves cripto │ │ • Instâncias │ +│ • Sessões │ │ • Mensagens │ +│ • Device info │ │ • Labels │ +│ • Contatos │ │ • Webhooks │ +│ │ │ • Configurações │ +└────────────────────────┘ └────────────────────────┘ + ▲ ▲ + │ │ + └───────── Gerenciado por ──────────┘ + Evolution GO +``` + +### Fluxo de Dados + +``` +1. Usuário cria instância + ↓ +2. Salvo em: users → instances + +3. Usuário conecta WhatsApp + ↓ +4. WhatsApp salva sessão em: auth → whatsmeow_device + +5. Mensagem enviada + ↓ +6. Salvo em: users → messages + +7. Label criada + ↓ +8. Salvo em: users → labels +``` + +--- + +## Resumo Rápido + +| Conceito | Explicação | +|----------|------------| +| **2 Bancos** | Auth (WhatsApp) + Users (API) | +| **Auto-Migration** | Cria tabelas automaticamente | +| **Cascata** | Deletar instância → deleta tudo relacionado | +| **Backup** | Crítico para Auth (chaves cripto) | +| **Índices** | Fazem buscas ficarem rápidas | + +**Lembre-se**: +- 🔐 Banco Auth = Dados do WhatsApp (crítico!) +- 📊 Banco Users = Dados da sua aplicação +- 💾 Faça backup regular +- 🧹 Limpe dados antigos +- 📈 Monitore crescimento + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/conceitos-core/instances.md b/docs/wiki/conceitos-core/instances.md new file mode 100644 index 0000000..3951f2c --- /dev/null +++ b/docs/wiki/conceitos-core/instances.md @@ -0,0 +1,790 @@ +# Instâncias WhatsApp + +Como funcionam as conexões do WhatsApp no Evolution GO - explicado de forma simples. + +## 📋 Índice + +- [O que é uma Instância](#o-que-é-uma-instância) +- [Informações de uma Instância](#informações-de-uma-instância) +- [Estados da Instância](#estados-da-instância) +- [Ciclo de Vida](#ciclo-de-vida) +- [Configurações Avançadas](#configurações-avançadas) +- [Sistema de Eventos](#sistema-de-eventos) +- [Proxy](#proxy) +- [Boas Práticas](#boas-práticas) + +--- + +## O que é uma Instância + +Uma **instância** é uma conexão independente com o WhatsApp. Pense assim: + +### Analogia do Celular + +Imagine que cada instância é como um celular separado: +- 📱 Celular 1 = Instância "vendas" +- 📱 Celular 2 = Instância "suporte" +- 📱 Celular 3 = Instância "marketing" + +Cada um: +- Tem seu próprio número do WhatsApp +- Envia e recebe mensagens independentemente +- Não interfere nos outros +- Tem suas próprias configurações + +### Características + +**Isolamento**: Cada instância é completamente separada +- Não compartilham mensagens +- Não compartilham contatos +- Não compartilham configurações + +**Persistência**: A conexão fica salva +- Se o servidor reiniciar, reconecta automaticamente +- Não precisa escanear QR Code novamente +- Sessão guardada com segurança + +**Multi-Device**: Usa o protocolo do WhatsApp Web +- Funciona como WhatsApp no computador +- Não desconecta o celular +- Até 4 dispositivos por número + +--- + +## Informações de uma Instância + +### Dados Básicos + +Toda instância tem essas informações: + +**id** - Identificador único (como um CPF) +``` +Exemplo: abc-123-def-456 +``` + +**name** - Nome amigável +``` +Exemplo: "vendas", "suporte", "atendimento-24h" +Deve ser único no sistema +``` + +**token** - Chave de acesso +``` +Exemplo: "token-vendas-secreto-123" +Usado para autenticar requisições +Deve ser único no sistema +``` + +**jid** - ID do WhatsApp (seu número) +``` +Formato: 5511999999999@s.whatsapp.net +Só aparece depois de conectar +``` + +**connected** - Está conectado? +``` +true = Conectado e funcionando +false = Desconectado +``` + +**qrcode** - QR Code para conectar +``` +Formato: imagem_base64|codigo_texto +Expira em ~40 segundos +``` + +### Dados de Integração + +**webhook** - URL para receber notificações +``` +Exemplo: https://meusite.com/webhook +Recebe eventos em tempo real +``` + +**events** - Quais eventos quer receber +``` +Exemplo: "MESSAGE,GROUP_UPDATE,CALL" +Pode ser "ALL" para receber tudo +``` + +**rabbitmqEnable** - Usar RabbitMQ? +``` +"true" = Sim, enviar eventos +"false" = Não usar +``` + +**websocketEnable** - Usar WebSocket? +``` +"true" = Sim, eventos em tempo real +"false" = Não usar +``` + +--- + +## Estados da Instância + +### Diagrama de Estados + +``` +┌──────────────┐ +│ CRIADA │ ← Acabou de criar +└──────┬───────┘ + │ (aguardando conexão) + ▼ +┌──────────────┐ +│ DESCONECTADA │ ← Sem conexão WhatsApp +└──────┬───────┘ + │ (conectar) + ▼ +┌──────────────┐ +│ CONECTANDO │ ← Iniciando conexão +└──────┬───────┘ + │ (gera QR Code) + ▼ +┌──────────────┐ +│AGUARDANDO QR │ ← Esperando escanear +└──────┬───────┘ + │ (escaneia no celular) + ▼ +┌──────────────┐ +│ ABERTA │ ← Conectado! ✓ +└──────┬───────┘ + │ (pode enviar/receber) + │ + │ (se desconectar) + ▼ +┌──────────────┐ +│ DESCONECTADA │ +└──────────────┘ +``` + +### Verificando o Estado + +**Via API**: +```bash +GET /instance/status?instanceName=vendas + +Resposta: +{ + "connected": true, + "loggedIn": true, + "jid": "5511999999999@s.whatsapp.net", + "name": "João Silva" +} +``` + +--- + +## Ciclo de Vida + +### 1. Criar Instância + +**Endpoint**: `POST /instance/create` + +**O que acontece**: +1. Sistema verifica se o nome já existe +2. Gera um ID único automaticamente +3. Salva no banco de dados +4. Retorna informações da instância +5. **Não conecta ainda** - apenas cria o registro + +**Exemplo**: +```json +POST /instance/create +{ + "name": "vendas", + "token": "meu-token-vendas" +} + +Resposta: +{ + "id": "abc-123", + "name": "vendas", + "token": "meu-token-vendas", + "connected": false +} +``` + +### 2. Conectar Instância + +**Endpoint**: `POST /instance/connect` + +**O que acontece**: +1. Sistema inicia cliente WhatsApp +2. Gera QR Code +3. Salva QR Code no banco +4. Aguarda você escanear + +**Exemplo**: +```json +POST /instance/connect +{ + "instanceName": "vendas", + "webhookUrl": "https://meusite.com/webhook", + "subscribe": ["MESSAGE", "GROUP_UPDATE"] +} +``` + +**Importante**: A conexão é assíncrona! O QR Code aparece depois de alguns segundos. + +### 3. Obter QR Code + +**Endpoint**: `GET /instance/qr?instanceName=vendas` + +**O que acontece**: +1. Sistema verifica se já está conectado +2. Se não estiver, retorna o QR Code +3. QR Code tem duas partes separadas por `|` + +**Formato do QR Code**: +``` +parte1|parte2 + +parte1 = imagem PNG em base64 +parte2 = código texto do QR +``` + +**Uso prático**: +```html + + + + + +``` + +### 4. Parear com Código + +**Endpoint**: `POST /instance/pair` + +**Alternativa ao QR Code**: Você recebe um código de 8 dígitos para digitar no celular. + +**Exemplo**: +```json +POST /instance/pair +{ + "instanceName": "vendas", + "phone": "5511999999999" +} + +Resposta: +{ + "pairingCode": "1234-5678" +} +``` + +**Como usar**: +1. Abra WhatsApp no celular +2. Vá em Dispositivos Conectados +3. Conectar Dispositivo +4. Digite o código: 1234-5678 + +### 5. Reconectar + +**Endpoint**: `POST /instance/reconnect` + +**Diferença importante**: +- **Connect**: Primeira vez, precisa de QR Code +- **Reconnect**: Já conectou antes, reutiliza sessão + +**Quando usar**: +- Após reiniciar o servidor +- Quando perder conexão temporária +- Para forçar reconexão + +**Não precisa de QR Code!** A sessão já está salva. + +### 6. Desconectar + +**Endpoint**: `POST /instance/disconnect` + +**O que acontece**: +1. Fecha a conexão com WhatsApp +2. Para de receber mensagens +3. **Mantém a sessão salva** +4. Pode reconectar depois sem QR Code + +**Quando usar**: +- Manutenção temporária +- Pausar operação +- Trocar configurações + +### 7. Logout + +**Endpoint**: `POST /instance/logout` + +**Diferença de Disconnect**: +- **Disconnect**: Desliga mas mantém sessão +- **Logout**: Remove a sessão completamente + +**O que acontece**: +1. Remove sessão do WhatsApp +2. Desconecta completamente +3. **Precisa de novo QR Code** para conectar de novo +4. Como se nunca tivesse conectado + +**Quando usar**: +- Trocar de número +- Limpar conexão completamente +- Resetar instância + +### 8. Deletar + +**Endpoint**: `DELETE /instance/delete/:id` + +**O que acontece**: +1. Faz logout se estiver conectado +2. Remove todas as mensagens dessa instância +3. Remove todas as labels dessa instância +4. **Deleta tudo do banco de dados** +5. Operação irreversível! + +**⚠️ ATENÇÃO**: Não tem como desfazer! + +--- + +## Configurações Avançadas + +### O que São + +Configurações extras para mudar o comportamento da instância. + +### Opções Disponíveis + +**alwaysOnline** - Aparecer sempre online +``` +true = Sempre mostra como "online" +false = Normal (online quando está usando) +``` + +**rejectCall** - Rejeitar chamadas automaticamente +``` +true = Rejeita chamadas de voz/vídeo +false = Aceita normalmente +``` + +**msgRejectCall** - Mensagem ao rejeitar +``` +Exemplo: "Desculpe, não atendo chamadas. Envie mensagem de texto." +Enviada automaticamente quando rejeitar +``` + +**readMessages** - Marcar como lidas automaticamente +``` +true = Marca todas as mensagens recebidas como lidas +false = Normal (você marca manualmente) +``` + +**ignoreGroups** - Ignorar mensagens de grupo +``` +true = Não processa eventos de grupos +false = Normal (recebe tudo) +``` + +**ignoreStatus** - Ignorar status/stories +``` +true = Não processa atualizações de status +false = Normal (recebe tudo) +``` + +### Como Configurar + +**Endpoint**: `POST /instance/:id/advanced-settings` + +**Exemplo**: +```json +{ + "alwaysOnline": true, + "rejectCall": true, + "msgRejectCall": "Não atendo chamadas, envie mensagem!", + "readMessages": false, + "ignoreGroups": false, + "ignoreStatus": true +} +``` + +**Efeito**: Aplica instantaneamente sem precisar reconectar! + +--- + +## Sistema de Eventos + +### O que São Eventos + +Notificações que o Evolution GO envia quando algo acontece. + +**Analogia**: Como notificações do celular +- "Nova mensagem recebida!" +- "Fulano entrou no grupo!" +- "Chamada recebida!" + +### Tipos de Eventos + +**Mensagens**: +- `MESSAGE` - Mensagem recebida +- `MESSAGE_SENT` - Mensagem enviada +- `MESSAGE_UPDATE` - Mensagem editada/deletada +- `MESSAGE_REACTION` - Reação em mensagem + +**Grupos**: +- `GROUP_UPDATE` - Grupo atualizado +- `GROUP_PARTICIPANT_UPDATE` - Alguém entrou/saiu + +**Conexão**: +- `CONNECTION_UPDATE` - Mudou status de conexão +- `QR_CODE` - QR Code gerado +- `QRCODE_UPDATED` - QR Code atualizado + +**Outros**: +- `PRESENCE_UPDATE` - Alguém ficou online/offline +- `CALL` - Chamada recebida +- `CONTACT_UPDATE` - Contato atualizado +- `LABEL` - Label criada/atualizada + +### Como Subscrever + +**Ao conectar, escolha quais eventos quer**: + +```json +POST /instance/connect +{ + "instanceName": "vendas", + "subscribe": ["MESSAGE", "GROUP_UPDATE", "CALL"] +} +``` + +**Opções**: +- Lista específica: `["MESSAGE", "CALL"]` +- Todos os eventos: `["ALL"]` +- Apenas mensagens (padrão): `["MESSAGE"]` + +### Destinos dos Eventos + +Pode enviar para vários lugares ao mesmo tempo: + +**Webhook** (HTTP POST): +```json +{ + "webhookUrl": "https://meusite.com/webhook" +} +``` + +**RabbitMQ** (Fila de mensagens): +```json +{ + "rabbitmqEnable": "true" +} +``` + +**WebSocket** (Tempo real): +```json +{ + "websocketEnable": "true" +} +``` + +**NATS** (Sistema de eventos): +```json +{ + "natsEnable": "true" +} +``` + +**Pode ativar todos juntos!** Cada evento será enviado para todos os destinos configurados. + +--- + +## Proxy + +### O que é Proxy + +Um servidor intermediário entre você e o WhatsApp. + +**Analogia**: Como usar uma empresa de correio +- Você → Correio → Destinatário +- Seu IP fica escondido +- WhatsApp vê o IP do proxy + +### Quando Usar + +**Recomendado se**: +- Tem muitas instâncias (>10) +- Quer esconder seu IP real +- Precisa de múltiplos IPs +- WhatsApp bloqueou seu IP + +### Como Configurar + +**Endpoint**: `POST /instance/proxy/:id` + +**Exemplo**: +```json + { + "host": "proxy.exemplo.com", + "port": "8080", + "username": "usuario", // Opcional + "password": "senha" // Opcional +} +``` + +**Importante**: Precisa reconectar para aplicar! + +### Como Remover + +**Endpoint**: `DELETE /instance/proxy/:id` + +Remove o proxy e volta a conexão direta. + +--- + +## Boas Práticas + +### 1. Nomeação + +Use nomes descritivos: + +**✅ Bom**: +- `vendas-regiao-sul` +- `suporte-nivel-1` +- `marketing-campanhas` +- `atendimento-24h` + +**❌ Ruim**: +- `teste` +- `instance1` +- `minha-instancia` +- `zap` + +### 2. Gerenciar Eventos + +**Subscreva apenas o necessário**: + +```json +// ✅ Bom - Apenas o que precisa +{"subscribe": ["MESSAGE", "GROUP_UPDATE"]} + +// ❌ Ruim - Muito tráfego desnecessário +{"subscribe": ["ALL"]} +``` + +Menos eventos = menos processamento = mais rápido + +### 3. Configurações Avançadas + +**Otimize para seu caso**: + +```json +// Bot de atendimento +{ + "ignoreGroups": true, // Não precisa de grupos + "ignoreStatus": true, // Não precisa de status + "readMessages": true // Marca como lido automaticamente +} + +// Monitoramento de grupos +{ + "ignoreGroups": false, // Precisa de grupos + "ignoreStatus": true, // Não precisa de status + "readMessages": false // Não marca como lido +} +``` + +### 4. Use Proxy + +**Se tiver muitas instâncias** (>10): + +- Evita bloqueio de IP +- Distribui a carga +- Mais estável + +### 5. Monitore Logs + +**Acompanhe sua instância**: + +```bash +GET /instance/logs/vendas?level=ERROR&limit=50 +``` + +Veja erros antes que causem problemas! + +### 6. Limpeza Regular + +**Delete instâncias não usadas**: + +```bash +DELETE /instance/delete/teste-antigo +``` + +Libera recursos e organiza o sistema. + +### 7. Reconexão vs Logout + +**Entenda a diferença**: + +| Situação | Use | +|----------|-----| +| Reiniciou servidor | Reconnect | +| Perdeu conexão | Reconnect | +| Trocar de número | Logout | +| Limpar tudo | Logout + Delete | + +--- + +## Limitações + +### Limites do WhatsApp + +**Dispositivos**: +- Máximo 4 dispositivos por número +- Evolution GO conta como 1 dispositivo + +**QR Code**: +- Expira em ~40 segundos +- Máximo de tentativas por hora + +**Reconexão**: +- Não reconecte mais de 1x por minuto +- Pode ser bloqueado temporariamente + +### Limites do Evolution GO + +**Por Servidor**: +- Depende da RAM disponível +- Cada instância usa ~50-100MB +- Exemplo: 16GB RAM = ~100 instâncias + +**Banco de Dados**: +- PostgreSQL: 100 conexões simultâneas (padrão) +- Pode configurar mais se necessário + +--- + +## Troubleshooting + +### "no active session found" + +**Problema**: Cliente não existe. + +**Causa**: Não conectou ainda ou sessão expirou. + +**Solução**: +1. Conecte via `POST /instance/connect` +2. Escaneie QR Code +3. Aguarde conectar + +### "client disconnected" + +**Problema**: Perdeu conexão com WhatsApp. + +**Causa**: Internet caiu ou WhatsApp instável. + +**Solução**: +```bash +POST /instance/reconnect +``` + +### QR Code não aparece + +**Problema**: QR Code vazio ou nulo. + +**Causa**: Cliente ainda inicializando. + +**Solução**: +1. Aguarde 2-3 segundos após `/connect` +2. Tente `/instance/qr` novamente +3. Se persistir, tente reconectar + +### Não reconecta após reiniciar + +**Problema**: Precisa escanear QR Code de novo. + +**Causa**: Sessão corrompida ou expirada. + +**Solução**: +```bash +# 1. Logout completo +POST /instance/logout + +# 2. Conectar de novo +POST /instance/connect + +# 3. Escanear novo QR Code +``` + +### Mensagens não chegam + +**Problema**: Eventos não são recebidos. + +**Causa**: Configuração de eventos errada. + +**Solução**: +1. Verifique se inscreveu no evento `MESSAGE` +2. Teste o webhook/RabbitMQ +3. Veja os logs da instância + +--- + +## Exemplo Completo + +### Do Zero até Enviar Mensagem + +```bash +# 1. Criar instância +POST /instance/create +{ + "name": "vendas", + "token": "token-vendas-123" +} + +# 2. Conectar +POST /instance/connect +{ + "instanceName": "vendas", + "webhookUrl": "https://meusite.com/webhook", + "subscribe": ["MESSAGE"] +} + +# 3. Aguardar 2 segundos... + +# 4. Pegar QR Code +GET /instance/qr?instanceName=vendas + +# 5. Escanear QR Code no celular + +# 6. Aguardar conectar (~5 segundos) + +# 7. Enviar mensagem! 🎉 +POST /send/text +Headers: apikey: token-vendas-123 +{ + "number": "5511999999999", + "text": "Olá! Primeira mensagem!" +} +``` + +--- + +## Resumo Rápido + +| Conceito | Explicação | +|----------|------------| +| **Instância** | Uma conexão WhatsApp independente | +| **QR Code** | Código para parear com celular | +| **Connect** | Primeira conexão (precisa QR) | +| **Reconnect** | Reconexão (não precisa QR) | +| **Logout** | Remove sessão completamente | +| **Delete** | Apaga tudo (irreversível) | +| **Eventos** | Notificações quando algo acontece | +| **Proxy** | Servidor intermediário | + +**Lembre-se**: +- 📱 Cada instância = 1 WhatsApp +- 🔄 Reconnect não precisa de QR Code +- 🚪 Logout remove tudo +- 📊 Configure apenas eventos necessários +- 🔒 Use proxy para muitas instâncias +- 🗑️ Delete instâncias não usadas + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/deploy-producao/docker-deployment.md b/docs/wiki/deploy-producao/docker-deployment.md new file mode 100644 index 0000000..70d1d8c --- /dev/null +++ b/docs/wiki/deploy-producao/docker-deployment.md @@ -0,0 +1,814 @@ +# Deploy com Docker + +Guia de deploy do Evolution GO usando Docker, Docker Compose, Swarm e Kubernetes. + +## Índice + +- [Visão Geral](#visão-geral) +- [Deploy com Docker Compose](#deploy-com-docker-compose) +- [Deploy com Docker Swarm](#deploy-com-docker-swarm) +- [Deploy com Kubernetes](#deploy-com-kubernetes) +- [Otimização e Gestão](#otimização-e-gestão) +- [Troubleshooting](#troubleshooting) + +--- + +## Visão Geral + +### Estratégias de Deploy + +| Estratégia | Uso Recomendado | Complexidade | Escalabilidade | +|------------|-----------------|--------------|----------------| +| **Docker Compose** | Desenvolvimento, testes, deploys pequenos | Baixa | Limitada (single-host) | +| **Docker Swarm** | Produção pequena/média, HA | Média | Boa (multi-host) | +| **Kubernetes** | Produção enterprise, orquestração avançada | Alta | Excelente | + +### Arquitetura de Componentes + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ EVOLUTION GO STACK │ +├─────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Evolution GO │◄────►│ PostgreSQL │ │ RabbitMQ │ │ +│ │ (API) │ │ (Auth DB) │ │ (Events) │ │ +│ │ Port: 4000 │ │ (Users DB) │ │ Port: 5672 │ │ +│ └──────┬───────┘ └──────────────┘ └──────────────┘ │ +│ │ │ +│ │ ┌──────────────┐ ┌──────────────┐ │ +│ └─────────────►│ MinIO │ │ NATS │ │ +│ │ (Media) │ │ (Optional) │ │ +│ │ Port: 9000 │ │ Port: 4222 │ │ +│ └──────────────┘ └──────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +### Imagem Docker + +- **Registry**: `evoapicloud/evolution-go` +- **Tags**: `latest`, `v1.x.x` +- **Base**: Alpine Linux 3.19.1 +- **Tamanho**: ~50MB (compactada) +- **Arquiteturas**: amd64, arm64 + +--- + +## Deploy com Docker Compose + +### Setup Básico + +Configuração mínima com Evolution GO + PostgreSQL. + +#### docker-compose.yml + +```yaml +version: '3.8' + +services: + evolution-go: + image: evoapicloud/evolution-go:latest + container_name: evolution-go + restart: unless-stopped + ports: + - "4000:4000" + environment: + SERVER_PORT: 4000 + CLIENT_NAME: "evolution" + GLOBAL_API_KEY: "SUBSTITUA-POR-UUID-FORTE" + + POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable" + POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable" + DATABASE_SAVE_MESSAGES: "false" + + WADEBUG: "INFO" + LOGTYPE: "console" + CONNECT_ON_STARTUP: "false" + WEBHOOKFILES: "true" + + volumes: + - evolution_data:/app/dbdata + - evolution_logs:/app/logs + networks: + - evolution_network + depends_on: + - postgres + + postgres: + image: postgres:15-alpine + container_name: postgres + restart: unless-stopped + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: postgres + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + - ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql + networks: + - evolution_network + +volumes: + evolution_data: + evolution_logs: + postgres_data: + +networks: + evolution_network: + driver: bridge +``` + +#### init-db.sql + +```sql +CREATE DATABASE evogo_auth; +CREATE DATABASE evogo_users; +SELECT 'Databases criados com sucesso!' as message; +``` + +#### Deploy + +```bash +# Gerar API Key +uuidgen + +# Editar docker-compose.yml e inserir API Key + +# Iniciar +docker-compose up -d + +# Verificar +docker-compose logs -f evolution-go +curl http://localhost:4000/server/ok +``` + +### Setup Completo + +Incluindo RabbitMQ, MinIO e NATS. + +```yaml +version: '3.8' + +services: + evolution-go: + image: evoapicloud/evolution-go:latest + restart: unless-stopped + ports: + - "4000:4000" + environment: + SERVER_PORT: 4000 + GLOBAL_API_KEY: "SUA-CHAVE-AQUI" + + POSTGRES_AUTH_DB: "postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable" + POSTGRES_USERS_DB: "postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable" + DATABASE_SAVE_MESSAGES: "true" + + AMQP_URL: "amqp://admin:admin@rabbitmq:5672/default" + AMQP_GLOBAL_ENABLED: "true" + AMQP_GLOBAL_EVENTS: "messages.upsert,messages.update,connection.update" + + MINIO_ENABLED: "true" + MINIO_ENDPOINT: "minio:9000" + MINIO_ACCESS_KEY: "minioadmin" + MINIO_SECRET_KEY: "minioadmin" + MINIO_BUCKET: "evolution-media" + MINIO_USE_SSL: "false" + + volumes: + - evolution_data:/app/dbdata + - evolution_logs:/app/logs + depends_on: + - postgres + - rabbitmq + - minio + + postgres: + image: postgres:15-alpine + restart: unless-stopped + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: senha + POSTGRES_DB: postgres + volumes: + - postgres_data:/var/lib/postgresql/data + - ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql + + rabbitmq: + image: rabbitmq:3-management-alpine + restart: unless-stopped + environment: + RABBITMQ_DEFAULT_USER: admin + RABBITMQ_DEFAULT_PASS: admin + RABBITMQ_DEFAULT_VHOST: default + ports: + - "5672:5672" + - "15672:15672" + volumes: + - rabbitmq_data:/var/lib/rabbitmq + + minio: + image: minio/minio:latest + restart: unless-stopped + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER: minioadmin + MINIO_ROOT_PASSWORD: minioadmin + ports: + - "9000:9000" + - "9001:9001" + volumes: + - minio_data:/data + + nats: + image: nats:2-alpine + restart: unless-stopped + ports: + - "4222:4222" + - "8222:8222" + +volumes: + evolution_data: + evolution_logs: + postgres_data: + rabbitmq_data: + minio_data: +``` + +**Acessos:** +- Evolution GO: http://localhost:4000 +- Swagger: http://localhost:4000/swagger/index.html +- RabbitMQ: http://localhost:15672 (admin/admin) +- MinIO: http://localhost:9001 (minioadmin/minioadmin) + +### Configurações Avançadas + +#### Arquivo .env + +```bash +# .env +EVOLUTION_VERSION=latest +POSTGRES_VERSION=15-alpine + +# Portas +EVOLUTION_PORT=4000 +POSTGRES_PORT=5432 + +# Credenciais +POSTGRES_USER=postgres +POSTGRES_PASSWORD=senha_forte +RABBITMQ_USER=admin +RABBITMQ_PASS=senha_forte + +# Evolution GO +GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db +CLIENT_NAME=evolution-prod +``` + +Referência no compose: +```yaml +services: + evolution-go: + image: evoapicloud/evolution-go:${EVOLUTION_VERSION:-latest} + ports: + - "${EVOLUTION_PORT:-4000}:4000" + environment: + GLOBAL_API_KEY: "${GLOBAL_API_KEY}" +``` + +#### Health Checks + +```yaml +services: + evolution-go: + healthcheck: + test: ["CMD", "wget", "-q", "--spider", "http://localhost:4000/server/ok"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 40s + + postgres: + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres"] + interval: 10s + timeout: 5s + retries: 5 + + rabbitmq: + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "ping"] + interval: 30s + timeout: 10s + retries: 3 +``` + +#### Resource Limits + +```yaml +services: + evolution-go: + deploy: + resources: + limits: + cpus: '2.0' + memory: 2G + reservations: + cpus: '0.5' + memory: 512M + + postgres: + deploy: + resources: + limits: + cpus: '1.0' + memory: 1G + reservations: + cpus: '0.25' + memory: 256M +``` + +--- + +## Deploy com Docker Swarm + +### Inicialização + +```bash +# Manager node +docker swarm init --advertise-addr 192.168.1.10 + +# Worker nodes +docker swarm join --token SWMTKN-1-xxxxx 192.168.1.10:2377 + +# Verificar cluster +docker node ls +``` + +### Preparação + +```bash +# Volumes +docker volume create evolution_go_data +docker volume create evolution_go_logs + +# Rede +docker network create --driver overlay network_public +``` + +### docker-compose.swarm.yml + +```yaml +version: '3.8' + +services: + evolution_go: + image: evoapicloud/evolution-go:latest + networks: + - network_public + environment: + SERVER_PORT: 4000 + GLOBAL_API_KEY: "sua-chave-api" + POSTGRES_AUTH_DB: "postgresql://user:pass@postgres:5432/evogo_auth" + POSTGRES_USERS_DB: "postgresql://user:pass@postgres:5432/evogo_users" + + volumes: + - evolution_go_data:/app/dbdata + - evolution_go_logs:/app/logs + + deploy: + replicas: 3 + placement: + constraints: + - node.role == worker + restart_policy: + condition: on-failure + delay: 5s + max_attempts: 3 + window: 120s + update_config: + parallelism: 1 + delay: 10s + failure_action: rollback + order: start-first + rollback_config: + parallelism: 1 + delay: 5s + labels: + - traefik.enable=true + - traefik.http.routers.evolution.rule=Host(`evolution.domain.com`) + - traefik.http.routers.evolution.entrypoints=websecure + - traefik.http.routers.evolution.tls.certresolver=letsencrypt + - traefik.http.services.evolution.loadbalancer.server.port=4000 + +volumes: + evolution_go_data: + external: true + evolution_go_logs: + external: true + +networks: + network_public: + external: true +``` + +### Deploy e Gerenciamento + +```bash +# Deploy +docker stack deploy -c docker-compose.swarm.yml evolution + +# Status +docker stack ls +docker service ls +docker service ps evolution_evolution_go + +# Logs +docker service logs evolution_evolution_go -f + +# Escalar +docker service scale evolution_evolution_go=5 + +# Atualizar (rolling update) +docker service update --image evoapicloud/evolution-go:v1.2.0 evolution_evolution_go + +# Remover +docker stack rm evolution +``` + +--- + +## Deploy com Kubernetes + +### Manifests Básicos + +#### Namespace + +```yaml +# namespace.yaml +apiVersion: v1 +kind: Namespace +metadata: + name: evolution-go +``` + +#### ConfigMap + +```yaml +# configmap.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: evolution-config + namespace: evolution-go +data: + SERVER_PORT: "4000" + CLIENT_NAME: "evolution" + WADEBUG: "INFO" + LOGTYPE: "console" + CONNECT_ON_STARTUP: "false" + WEBHOOKFILES: "true" + DATABASE_SAVE_MESSAGES: "false" +``` + +#### Secrets + +```bash +kubectl create secret generic evolution-secrets \ + --from-literal=GLOBAL_API_KEY=$(uuidgen) \ + --from-literal=POSTGRES_PASSWORD=$(openssl rand -base64 32) \ + --namespace=evolution-go +``` + +#### Deployment + +```yaml +# deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: evolution-go + namespace: evolution-go +spec: + replicas: 3 + selector: + matchLabels: + app: evolution-go + template: + metadata: + labels: + app: evolution-go + spec: + containers: + - name: evolution-go + image: evoapicloud/evolution-go:latest + ports: + - containerPort: 4000 + env: + - name: SERVER_PORT + valueFrom: + configMapKeyRef: + name: evolution-config + key: SERVER_PORT + - name: GLOBAL_API_KEY + valueFrom: + secretKeyRef: + name: evolution-secrets + key: GLOBAL_API_KEY + resources: + requests: + memory: "512Mi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "2000m" + livenessProbe: + httpGet: + path: /server/ok + port: 4000 + initialDelaySeconds: 30 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /server/ok + port: 4000 + initialDelaySeconds: 10 + periodSeconds: 5 + volumeMounts: + - name: evolution-data + mountPath: /app/dbdata + - name: evolution-logs + mountPath: /app/logs + volumes: + - name: evolution-data + persistentVolumeClaim: + claimName: evolution-data-pvc + - name: evolution-logs + persistentVolumeClaim: + claimName: evolution-logs-pvc +``` + +#### Service + +```yaml +# service.yaml +apiVersion: v1 +kind: Service +metadata: + name: evolution-go-service + namespace: evolution-go +spec: + type: LoadBalancer + selector: + app: evolution-go + ports: + - port: 4000 + targetPort: 4000 +``` + +#### Ingress + +```yaml +# ingress.yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: evolution-ingress + namespace: evolution-go + annotations: + kubernetes.io/ingress.class: "nginx" + cert-manager.io/cluster-issuer: "letsencrypt-prod" +spec: + tls: + - hosts: + - evolution.domain.com + secretName: evolution-tls + rules: + - host: evolution.domain.com + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: evolution-go-service + port: + number: 4000 +``` + +#### HorizontalPodAutoscaler + +```yaml +# hpa.yaml +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: evolution-hpa + namespace: evolution-go +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: evolution-go + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 70 + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 +``` + +### Deploy Kubernetes + +```bash +# Aplicar manifests +kubectl apply -f namespace.yaml +kubectl apply -f configmap.yaml +kubectl apply -f secrets.yaml +kubectl apply -f deployment.yaml +kubectl apply -f service.yaml +kubectl apply -f ingress.yaml +kubectl apply -f hpa.yaml + +# Verificar +kubectl get all -n evolution-go +kubectl get pods -n evolution-go + +# Logs +kubectl logs -f deployment/evolution-go -n evolution-go + +# Escalar +kubectl scale deployment evolution-go --replicas=5 -n evolution-go + +# Atualizar +kubectl set image deployment/evolution-go \ + evolution-go=evoapicloud/evolution-go:v1.2.0 \ + -n evolution-go + +# Rollback +kubectl rollout undo deployment/evolution-go -n evolution-go +``` + +--- + +## Otimização e Gestão + +### Gestão de Volumes + +#### Backup + +```bash +# Backup volume +docker run --rm \ + -v evolution_data:/data \ + -v $(pwd):/backup \ + alpine tar czf /backup/backup-$(date +%Y%m%d).tar.gz -C /data . + +# Restaurar +docker run --rm \ + -v evolution_data:/data \ + -v $(pwd):/backup \ + alpine tar xzf /backup/backup-20250111.tar.gz -C /data +``` + +### Logging + +```yaml +services: + evolution-go: +logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" +``` + +### Boas Práticas + +**Segurança:** +- Não executar containers como root +- Usar secrets para credenciais +- Habilitar HTTPS em produção +- Configurar resource limits +- Implementar health checks + +**Performance:** +- Definir resource requests/limits +- Usar health checks +- Implementar HPA (Kubernetes) +- Configurar connection pooling + +**Monitoramento:** +- Coletar logs centralizados +- Implementar métricas (Prometheus) +- Configurar alertas +- Dashboard de visualização (Grafana) + +--- + +## Troubleshooting + +### Container Reiniciando + +```bash +# Ver logs +docker-compose logs evolution-go + +# Verificar variáveis obrigatórias +# - GLOBAL_API_KEY +# - POSTGRES_*_DB +``` + +### Conectividade PostgreSQL + +```bash +# Testar conexão +docker-compose exec evolution-go ping postgres + +# Verificar porta +docker-compose exec evolution-go nc -zv postgres 5432 + +# Inspecionar rede +docker network inspect evolution_network +``` + +### Sem Espaço em Disco + +```bash +# Ver uso +docker system df + +# Limpar +docker container prune +docker image prune +docker volume prune # CUIDADO: apaga volumes não utilizados +docker system prune -a +``` + +### OOM (Out of Memory) + +```bash +# Ver eventos OOM +docker events --filter 'event=oom' + +# Ver uso de memória +docker stats evolution-go + +# Aumentar limite +deploy: + resources: + limits: + memory: 4G +``` + +--- + +## Comandos Úteis + +### Docker Compose + +```bash +docker-compose up -d # Iniciar +docker-compose ps # Status +docker-compose logs -f # Logs +docker-compose stop # Parar +docker-compose restart # Reiniciar +docker-compose down # Remover +docker-compose pull # Atualizar imagens +``` + +### Docker Swarm + +```bash +docker stack deploy -c file.yml name # Deploy +docker stack ls # Listar stacks +docker service ls # Listar serviços +docker service logs name -f # Logs +docker service scale name=N # Escalar +docker stack rm name # Remover +``` + +### Kubernetes + +```bash +kubectl apply -f file.yaml # Aplicar +kubectl get all -n namespace # Listar recursos +kubectl logs -f deployment/name # Logs +kubectl scale deployment name --replicas=N # Escalar +kubectl delete -f file.yaml # Deletar +``` + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/deploy-producao/security.md b/docs/wiki/deploy-producao/security.md new file mode 100644 index 0000000..fc2a6a2 --- /dev/null +++ b/docs/wiki/deploy-producao/security.md @@ -0,0 +1,732 @@ +# Segurança e Hardening + +Guia de práticas de segurança para ambientes de produção do Evolution GO. + +## Índice + +- [Princípios de Segurança](#princípios-de-segurança) +- [Autenticação e API Keys](#autenticação-e-api-keys) +- [Gestão de Secrets](#gestão-de-secrets) +- [Segurança de Rede](#segurança-de-rede) +- [Hardening de Containers](#hardening-de-containers) +- [SSL/TLS](#ssltls) +- [Segurança do Banco de Dados](#segurança-do-banco-de-dados) +- [Backup Seguro](#backup-seguro) +- [Proteção contra Ataques](#proteção-contra-ataques) +- [Auditoria e Compliance](#auditoria-e-compliance) +- [Resposta a Incidentes](#resposta-a-incidentes) + +--- + +## Princípios de Segurança + +### Defense in Depth + +Implementar múltiplas camadas de proteção: +- Autenticação forte +- Firewall e isolamento de rede +- Criptografia em trânsito e repouso +- Monitoramento e auditoria +- Backup e disaster recovery + +### Least Privilege + +Conceder apenas permissões mínimas necessárias: +- Containers não executam como root +- Credenciais com escopo limitado +- Acesso à rede restrito +- Segregação de ambientes + +### Security by Default + +- Configurações seguras desde a instalação +- HTTPS obrigatório em produção +- Logs de auditoria habilitados +- Credenciais fortes exigidas + +### Requisitos por Ambiente + +| Ambiente | Segurança Mínima | +|----------|------------------| +| **Desenvolvimento** | API Key forte, senhas não-padrão | +| **Staging** | + Firewall, backup, logs | +| **Produção** | + HTTPS, monitoramento, auditoria, secrets management | + +--- + +## Autenticação e API Keys + +### Geração de API Keys + +Utilize chaves criptograficamente seguras: + +```bash +# UUID v4 (recomendado) +uuidgen + +# 64 caracteres hexadecimais +openssl rand -hex 32 + +# URL-safe base64 +python3 -c "import secrets; print(secrets.token_urlsafe(32))" +``` + +**Exemplo de chave forte:** +``` +df16caad-d0d2-41b2-bec5-75b90048a0db +``` + +**Evitar:** +- Valores padrão ou previsíveis +- Senhas comuns ou sequências +- Reutilização de chaves entre ambientes + +### Rotação de Chaves + +**Política recomendada:** +- Rotação periódica (90 dias) +- Rotação imediata em caso de comprometimento +- Manter período de transição para atualização de clientes + +**Processo de rotação:** + +1. Gerar nova chave +2. Atualizar configuração do servidor +3. Notificar clientes integradores +4. Estabelecer deadline para migração +5. Desabilitar chave antiga + +### Rate Limiting + +Implementar limitação de requisições por API Key via NGINX: + +```nginx +http { + map $http_apikey $limit_key { + default $http_apikey; + "" $binary_remote_addr; + } + + limit_req_zone $limit_key zone=api_limit:10m rate=100r/s; + + server { + location / { + limit_req zone=api_limit burst=200 nodelay; + limit_req_status 429; + proxy_pass http://evolution-go:4000; + } + } +} +``` + +--- + +## Gestão de Secrets + +### Docker Secrets (Swarm) + +```bash +# Criar secrets +echo "senha_postgres" | docker secret create postgres_password - +echo "$(uuidgen)" | docker secret create evolution_api_key - + +# docker-compose.swarm.yml +services: + evolution-go: + secrets: + - evolution_api_key + - postgres_password + environment: + GLOBAL_API_KEY_FILE: /run/secrets/evolution_api_key + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + +secrets: + evolution_api_key: + external: true + postgres_password: + external: true +``` + +### Kubernetes Secrets + +```bash +# Criar secrets +kubectl create secret generic evolution-secrets \ + --from-literal=GLOBAL_API_KEY=$(uuidgen) \ + --from-literal=POSTGRES_PASSWORD=$(openssl rand -base64 32) \ + --namespace=evolution-go + +# Habilitar encryption at rest +# https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/ +``` + +```yaml +# deployment.yaml + env: + - name: GLOBAL_API_KEY + valueFrom: + secretKeyRef: + name: evolution-secrets + key: GLOBAL_API_KEY + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: evolution-secrets + key: POSTGRES_PASSWORD +``` + +### HashiCorp Vault + +```yaml +# vault-agent-config.hcl +vault { + address = "https://vault.seudominio.com:8200" +} + +auto_auth { + method { + type = "kubernetes" + config = { + role = "evolution-go" + } + } +} + +template { + source = "/vault/configs/.env.tpl" + destination = "/app/.env" +} +``` + +--- + +## Segurança de Rede + +### Firewall (iptables) + +```bash +#!/bin/bash +# firewall-setup.sh + +# Políticas padrão +iptables -P INPUT DROP +iptables -P FORWARD DROP +iptables -P OUTPUT ACCEPT + +# Loopback +iptables -A INPUT -i lo -j ACCEPT + +# Conexões estabelecidas +iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT + +# SSH com rate limiting +iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set +iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP +iptables -A INPUT -p tcp --dport 22 -j ACCEPT + +# HTTP/HTTPS restrito à rede interna +iptables -A INPUT -p tcp --dport 80 -s 10.0.1.0/24 -j ACCEPT +iptables -A INPUT -p tcp --dport 443 -s 10.0.1.0/24 -j ACCEPT + +# Docker network +iptables -A INPUT -s 172.16.0.0/12 -j ACCEPT + +# Drop inválidos +iptables -A INPUT -m conntrack --ctstate INVALID -j DROP + +# Salvar regras +iptables-save > /etc/iptables/rules.v4 +``` + +### UFW (Alternativa Simplificada) + +```bash +sudo apt-get install ufw + +# Configurar padrões +sudo ufw default deny incoming +sudo ufw default allow outgoing + +# Permitir serviços +sudo ufw allow 22/tcp # SSH +sudo ufw allow 80/tcp # HTTP +sudo ufw allow 443/tcp # HTTPS + +# Ativar +sudo ufw enable + +# Status +sudo ufw status +``` + +### Isolamento de Redes Docker + +```yaml +networks: + frontend: + driver: overlay + driver_opts: + encrypted: "true" + + backend: + driver: overlay + driver_opts: + encrypted: "true" + internal: true # Sem acesso externo + +services: + evolution-go: + networks: + - frontend + - backend + + postgres: + networks: + - backend # Apenas rede interna +``` + +--- + +## Hardening de Containers + +### Não Executar como Root + +```dockerfile +FROM alpine:3.19.1 + +RUN addgroup -g 1000 evolution && \ + adduser -D -u 1000 -G evolution evolution + +WORKDIR /app +COPY --chown=evolution:evolution server . + +USER evolution + +ENTRYPOINT ["/app/server"] +``` + +### Filesystem Read-Only + +```yaml +services: + evolution-go: + read_only: true + tmpfs: + - /tmp + volumes: + - evolution_data:/app/dbdata + - evolution_logs:/app/logs +``` + +### Security Options + +```yaml +services: + evolution-go: + security_opt: + - no-new-privileges:true + - apparmor:docker-default + - seccomp:default.json + cap_drop: + - ALL + cap_add: + - NET_BIND_SERVICE # Apenas se necessário +``` + +### Limites de Recursos + +```yaml +services: + evolution-go: + deploy: + resources: + limits: + cpus: '2.0' + memory: 2G + pids: 100 + reservations: + cpus: '1.0' + memory: 1G + ulimits: + nofile: + soft: 1024 + hard: 2048 + nproc: 64 +``` + +### Scan de Vulnerabilidades + +```bash +# Trivy +trivy image evoapicloud/evolution-go:latest + +# Apenas críticas +trivy image --severity CRITICAL evoapicloud/evolution-go:latest + +# Docker Scout +docker scout cves evoapicloud/evolution-go:latest +``` + +--- + +## SSL/TLS + +### Obtenção de Certificados (Let's Encrypt) + +```bash +# Instalar Certbot +sudo apt-get install certbot + +# Gerar certificado +sudo certbot certonly --standalone -d evolution.seudominio.com + +# Certificados em: +# /etc/letsencrypt/live/evolution.seudominio.com/ +``` + +### Configuração NGINX + +```nginx +# Redirecionar HTTP → HTTPS +server { + listen 80; + server_name evolution.seudominio.com; + return 301 https://$server_name$request_uri; +} + +# HTTPS +server { + listen 443 ssl http2; + server_name evolution.seudominio.com; + + # Certificados + ssl_certificate /etc/letsencrypt/live/evolution.seudominio.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/evolution.seudominio.com/privkey.pem; + + # Protocolos e ciphers + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'; + ssl_prefer_server_ciphers off; + + # HSTS + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; + + # OCSP Stapling + ssl_stapling on; + ssl_stapling_verify on; + ssl_trusted_certificate /etc/letsencrypt/live/evolution.seudominio.com/chain.pem; + + # Security Headers + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "no-referrer-when-downgrade" always; + + # Ocultar server tokens + server_tokens off; + + location / { + proxy_pass http://evolution-go:4000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_hide_header X-Powered-By; + } +} +``` + +### Renovação Automática + +```bash +# Testar renovação +sudo certbot renew --dry-run + +# Agendar via cron +sudo crontab -e + +# Adicionar (renovação diária às 3h) +0 3 * * * certbot renew --quiet && systemctl reload nginx +``` + +--- + +## Segurança do Banco de Dados + +### PostgreSQL Hardening + +```ini +# postgresql.conf + +# SSL obrigatório +ssl = on +ssl_cert_file = '/etc/ssl/certs/server.crt' +ssl_key_file = '/etc/ssl/private/server.key' + +# Auditoria +log_connections = on +log_disconnections = on +log_duration = on +log_statement = 'mod' # INSERT, UPDATE, DELETE + +# Senha forte obrigatória +password_encryption = scram-sha-256 +``` + +```ini +# pg_hba.conf + +# Apenas SSL +hostssl evogo_auth evolution 10.0.0.0/8 scram-sha-256 +hostssl evogo_users evolution 10.0.0.0/8 scram-sha-256 + +# Rejeitar sem SSL +hostnossl all all 0.0.0.0/0 reject +``` + +### Backup Criptografado + +```bash +#!/bin/bash +# backup-encrypted.sh + +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +BACKUP_FILE="postgres_${TIMESTAMP}.sql.gz.gpg" + +# Dump e criptografar +docker exec postgres pg_dumpall -U postgres | \ + gzip | \ + gpg --symmetric --cipher-algo AES256 --output "/backups/${BACKUP_FILE}" + +# Upload S3 com SSE +aws s3 cp "/backups/${BACKUP_FILE}" \ + "s3://bucket-backup/postgres/${BACKUP_FILE}" \ + --server-side-encryption AES256 +``` + +--- + +## Backup Seguro + +### Estratégia 3-2-1 + +- 3 cópias dos dados +- 2 mídias diferentes +- 1 cópia offsite + +```bash +#!/bin/bash +# backup-secure.sh + +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +BACKUP_DIR="/backups" +S3_BUCKET="s3://backup-bucket" +GPG_KEY="backup@seudominio.com" + +# PostgreSQL +docker exec postgres pg_dumpall -U postgres | \ + gzip | \ + gpg --encrypt --recipient $GPG_KEY --output "${BACKUP_DIR}/postgres_${TIMESTAMP}.sql.gz.gpg" + +# Volumes +docker run --rm \ + -v evolution_data:/data \ + -v ${BACKUP_DIR}:/backup \ + alpine tar czf - -C /data . | \ + gpg --encrypt --recipient $GPG_KEY --output "${BACKUP_DIR}/evolution_data_${TIMESTAMP}.tar.gz.gpg" + +# Upload S3 com KMS +aws s3 cp "${BACKUP_DIR}/postgres_${TIMESTAMP}.sql.gz.gpg" \ + "${S3_BUCKET}/postgres/" \ + --server-side-encryption aws:kms \ + --ssekms-key-id alias/backup-key + +# Limpeza (30 dias) +find ${BACKUP_DIR} -name "*.gpg" -mtime +30 -delete +``` + +--- + +## Proteção contra Ataques + +### DDoS Protection + +**NGINX Rate Limiting:** + +```nginx +http { + limit_conn_zone $binary_remote_addr zone=conn_limit:10m; + limit_conn conn_limit 10; + + limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; + + server { + location / { + limit_req zone=req_limit burst=20 nodelay; + proxy_pass http://evolution-go:4000; + } + } +} +``` + +**Cloudflare:** Habilitar proteção DDoS no painel. + +### SQL Injection + +Evolution GO usa GORM (ORM) que previne SQL injection por padrão através de prepared statements. + +### Brute-Force Protection (Fail2ban) + +```bash +sudo apt-get install fail2ban +``` + +```ini +# /etc/fail2ban/jail.local +[nginx-req-limit] +enabled = true +filter = nginx-req-limit +logpath = /var/log/nginx/error.log +maxretry = 5 +findtime = 600 +bantime = 3600 +``` + +```ini +# /etc/fail2ban/filter.d/nginx-req-limit.conf +[Definition] +failregex = limiting requests, excess:.* by zone.*client: +``` + +--- + +## Auditoria e Compliance + +### LGPD/GDPR + +**Direito ao esquecimento:** + +```sql +CREATE PROCEDURE delete_user_data(user_phone VARCHAR) +LANGUAGE plpgsql +AS $$ +BEGIN + DELETE FROM messages WHERE phone = user_phone; + DELETE FROM contacts WHERE phone = user_phone; + DELETE FROM instances WHERE owner_phone = user_phone; + + INSERT INTO audit_log (action, details, timestamp) + VALUES ('user_data_deleted', user_phone, NOW()); + + COMMIT; +END; +$$; +``` + +**Retenção de dados:** + +```sql +-- Deletar mensagens antigas (30 dias) +DELETE FROM messages WHERE timestamp < NOW() - INTERVAL '30 days'; +``` + +### Logging de Auditoria + +```yaml +services: + evolution-go: + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "5" + labels: "service,environment" +``` + +--- + +## Resposta a Incidentes + +### Plano de Resposta + +**1. Detecção** +- Alertas automatizados +- Monitoramento de logs +- Relatórios de usuários + +**2. Contenção** +- Isolar sistemas afetados +- Revogar credenciais comprometidas +- Bloquear IPs maliciosos +- Capturar evidências + +**3. Erradicação** +- Aplicar patches +- Atualizar imagens +- Revisar logs de auditoria +- Remover backdoors + +**4. Recuperação** +- Restaurar de backup +- Validar integridade +- Monitorar por 48h + +**5. Pós-Incidente** +- Documentar lições aprendidas +- Atualizar runbooks +- Treinar equipe + +### Forensics + +```bash +# Capturar estado do container +docker commit container_suspeito forensics-image +docker save forensics-image > forensics-image.tar + +# Coletar logs +docker logs container_suspeito > logs_suspeito.txt + +# Inspecionar +docker inspect container_suspeito > inspect_suspeito.json + +# Exportar filesystem +docker export container_suspeito > filesystem_suspeito.tar +``` + +--- + +## Checklist de Segurança + +### Crítico +- [ ] API Keys fortes (UUID) +- [ ] HTTPS habilitado +- [ ] Secrets em vault/secrets manager +- [ ] Firewall configurado +- [ ] Backups automáticos funcionando + +### Importante +- [ ] Containers não executam como root +- [ ] Isolamento de redes Docker +- [ ] Limites de recursos definidos +- [ ] Logs de auditoria ativos +- [ ] Monitoramento configurado + +### Recomendado +- [ ] Scan de vulnerabilidades regular +- [ ] Plano de resposta a incidentes +- [ ] Testes de restauração de backup +- [ ] Documentação de segurança +- [ ] Treinamento da equipe + +--- + +## Recursos Adicionais + +- [OWASP Top 10](https://owasp.org/www-project-top-ten/) +- [CIS Docker Benchmark](https://www.cisecurity.org/benchmark/docker) +- [Kubernetes Security Best Practices](https://kubernetes.io/docs/concepts/security/) +- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework) + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/desenvolvimento/contributing.md b/docs/wiki/desenvolvimento/contributing.md new file mode 100644 index 0000000..f9dea82 --- /dev/null +++ b/docs/wiki/desenvolvimento/contributing.md @@ -0,0 +1,297 @@ +# Como Contribuir + +Guia para contribuir com o Evolution GO. + +## Índice + +- [Como Contribuir](#como-contribuir) +- [Código de Conduta](#código-de-conduta) +- [Reportando Bugs](#reportando-bugs) +- [Sugerindo Features](#sugerindo-features) +- [Pull Requests](#pull-requests) +- [Padrões de Código](#padrões-de-código) +- [Processo de Review](#processo-de-review) + +--- + +## Como Contribuir + +Contribuições são bem-vindas! Você pode contribuir: + +- 🐛 Reportando bugs +- 💡 Sugerindo novas features +- 📝 Melhorando documentação +- 🔧 Corrigindo bugs +- ✨ Implementando features + +--- + +## Código de Conduta + +- Seja respeitoso e profissional +- Aceite feedback construtivo +- Foque no que é melhor para a comunidade +- Mostre empatia com outros membros + +--- + +## Reportando Bugs + +### Antes de Reportar + +1. Verifique se o bug já foi reportado nas [Issues](https://git.evoai.app/Evolution/evolution-go/issues) +2. Teste na versão mais recente +3. Colete informações: logs, versão do Go, sistema operacional + +### Template de Bug Report + +```markdown +**Descrição do Bug** +Descrição clara e concisa do bug. + +**Como Reproduzir** +1. Faça X +2. Execute Y +3. Veja erro Z + +**Comportamento Esperado** +O que deveria acontecer. + +**Comportamento Atual** +O que está acontecendo. + +**Screenshots/Logs** +Se aplicável, adicione screenshots ou logs. + +**Ambiente** +- OS: [ex: Ubuntu 22.04] +- Go Version: [ex: 1.24.0] +- Evolution GO Version: [ex: v1.0.0] +- PostgreSQL Version: [ex: 15.2] + +**Informações Adicionais** +Qualquer outro contexto sobre o problema. +``` + +--- + +## Sugerindo Features + +### Template de Feature Request + +```markdown +**Descrição da Feature** +Descrição clara da feature proposta. + +**Problema que Resolve** +Qual problema esta feature resolve? + +**Solução Proposta** +Como você imagina que esta feature funcionaria? + +**Alternativas Consideradas** +Outras abordagens que você considerou? + +**Informações Adicionais** +Mockups, exemplos, referências, etc. +``` + +--- + +## Pull Requests + +### Processo + +1. **Fork** o repositório +2. **Clone** seu fork: `git clone https://git.evochat.com/SEU-USUARIO/evolution-go.git` +3. **Crie branch**: `git checkout -b feature/minha-feature` +4. **Desenvolva** e **commit** suas mudanças +5. **Push**: `git push origin feature/minha-feature` +6. **Abra PR** no repositório original + +### Checklist do PR + +- [ ] Código segue os padrões do projeto +- [ ] Código foi formatado (`make fmt`) +- [ ] Lint passou sem erros (`make lint`) +- [ ] Documentação foi atualizada (se necessário) +- [ ] Swagger foi atualizado (`make swagger`) se alterou endpoints +- [ ] Commit messages são descritivas + +### Padrão de Commit + +Use [Conventional Commits](https://www.conventionalcommits.org/): + +```bash +# Feature +git commit -m "feat: adiciona suporte para envio de áudio" + +# Bug fix +git commit -m "fix: corrige erro ao deletar instância" + +# Documentação +git commit -m "docs: atualiza guia de instalação" + +# Refatoração +git commit -m "refactor: simplifica lógica de conexão" + +# Chore (manutenção) +git commit -m "chore: atualiza dependências" + +# Performance +git commit -m "perf: otimiza query de listagem de mensagens" +``` + +### Mensagens de Commit Detalhadas + +```bash +git commit -m "feat: adiciona endpoint de busca de mensagens + +- Implementa GET /message/search +- Adiciona filtros por data, remetente e texto +- Inclui paginação (limit/offset) +- Atualiza documentação Swagger + +Closes #42" +``` + +--- + +## Padrões de Código + +### Go Formatting + +```bash +# Sempre formate antes de commit +make fmt + +# Ou manualmente +go fmt ./... +goimports -w . +``` + +### Linting + +```bash +# Execute lint +make lint + +# Corrige automaticamente quando possível +golangci-lint run --fix +``` + +### Estrutura de Código + +Siga o padrão **Handler → Service → Repository**: + +```go +// pkg/mymodule/handler.go +package mymodule + +type MyHandler struct { + service MyService +} + +func (h *MyHandler) Create(c *gin.Context) { + // Valida input + // Chama service + // Retorna response +} + +// pkg/mymodule/service.go +type MyService interface { + Create(dto CreateDTO) (*Model, error) +} + +type myService struct { + repo MyRepository +} + +func (s *myService) Create(dto CreateDTO) (*Model, error) { + // Lógica de negócio + // Chama repository + return model, nil +} + +// pkg/mymodule/repository.go +type MyRepository interface { + Save(model *Model) error +} + +type myRepository struct { + db *gorm.DB +} + +func (r *myRepository) Save(model *Model) error { + return r.db.Create(model).Error +} +``` + +### Documentação Swagger + +Sempre documente endpoints públicos: + +```go +// GetInstance retorna uma instância por ID. +// +// @Summary Buscar instância +// @Description Retorna detalhes de uma instância WhatsApp +// @Tags instance +// @Accept json +// @Produce json +// @Param instanceName path string true "Nome da instância" +// @Success 200 {object} Instance +// @Failure 404 {object} ErrorResponse +// @Security ApiKeyAuth +// @Router /instance/{instanceName} [get] +func (h *InstanceHandler) GetInstance(c *gin.Context) { + // ... +} +``` + +--- + +## Processo de Review + +### O que os Reviewers Avaliam + +- ✅ **Funcionalidade**: O código faz o que deveria? +- ✅ **Qualidade**: Código limpo, legível e manutenível? +- ✅ **Performance**: Há problemas de performance? +- ✅ **Segurança**: Há vulnerabilidades? +- ✅ **Testes**: Há cobertura adequada? (quando testes existirem) +- ✅ **Documentação**: Está atualizada? + +### Timeline Esperado + +- **Primeira revisão**: 1-3 dias úteis +- **Revisões subsequentes**: 1-2 dias úteis +- **Merge**: Após aprovação de 1+ mantainer + +### Respondendo a Feedbacks + +- Seja receptivo a sugestões +- Faça perguntas se não entender +- Atualize o código conforme feedback +- Force push (`git push -f`) é OK durante review + +### Após o Merge + +- Delete sua branch: `git branch -d feature/minha-feature` +- Atualize seu fork: `git pull upstream main` + +--- + +## Recursos Úteis + +- **Issues**: https://git.evoai.app/Evolution/evolution-go/issues +- **Pull Requests**: https://git.evoai.app/Evolution/evolution-go/merge_requests +- **Documentação**: https://git.evoai.app/Evolution/evolution-go/-/wikis +- **Go Style Guide**: https://google.github.io/styleguide/go/ +- **Effective Go**: https://go.dev/doc/effective_go + +--- + +**Obrigado por contribuir!** 🎉 + +**Mantido por**: Equipe EvoAI Services diff --git a/docs/wiki/desenvolvimento/debugging.md b/docs/wiki/desenvolvimento/debugging.md new file mode 100644 index 0000000..80b637d --- /dev/null +++ b/docs/wiki/desenvolvimento/debugging.md @@ -0,0 +1,407 @@ +# Debugging e Troubleshooting + +Guia para resolver problemas comuns no Evolution GO. + +## Índice + +- [Logs e Debug Mode](#logs-e-debug-mode) +- [Problemas Comuns](#problemas-comuns) +- [Debugging com IDE](#debugging-com-ide) +- [Profiling de Performance](#profiling-de-performance) +- [Análise de Banco de Dados](#análise-de-banco-de-dados) +- [Network Debugging](#network-debugging) +- [Ferramentas Úteis](#ferramentas-úteis) + +--- + +## Logs e Debug Mode + +### Habilitar Debug Mode + +```env +# .env +WADEBUG=DEBUG +LOGTYPE=console # ou 'file' +``` + +### Visualizar Logs + +```bash +# Logs em console +make dev + +# Logs em arquivo +tail -f logs/evolution-go.log + +# Docker +docker-compose logs -f evolution-go + +# Filtrar logs de erro +docker-compose logs evolution-go | grep ERROR +``` + +### Níveis de Log + +- **DEBUG**: Detalhes de execução (desenvolvimento) +- **INFO**: Informações gerais (produção) +- **WARN**: Avisos (produção) +- **ERROR**: Erros (sempre) + +--- + +## Problemas Comuns + +### 1. Erro: "port 4000 already in use" + +**Causa**: Outra aplicação usando a porta 4000. + +**Solução**: + +```bash +# Verificar processo usando a porta +lsof -i :4000 + +# Ou +netstat -tuln | grep 4000 + +# Matar processo +kill -9 + +# Ou alterar porta no .env +SERVER_PORT=4001 +``` + +### 2. Erro: "connection refused" (PostgreSQL) + +**Causa**: PostgreSQL não está rodando ou inacessível. + +**Solução**: + +```bash +# Verificar se PostgreSQL está rodando +sudo systemctl status postgresql + +# Ou via Docker +docker ps | grep postgres + +# Iniciar PostgreSQL +sudo systemctl start postgresql + +# Ou via Docker +docker start postgres + +# Testar conexão +psql -h localhost -U postgres -d evogo_auth +``` + +### 3. Erro: "database does not exist" + +**Causa**: Databases `evogo_auth` ou `evogo_users` não criados. + +**Solução**: + +```bash +# Criar databases +sudo -u postgres psql << EOF +CREATE DATABASE evogo_auth; +CREATE DATABASE evogo_users; +EOF + +# Ou via Docker +docker exec -i postgres psql -U postgres << EOF +CREATE DATABASE evogo_auth; +CREATE DATABASE evogo_users; +EOF +``` + +### 4. Erro: "invalid API key" + +**Causa**: API key incorreta ou não configurada. + +**Solução**: + +```bash +# Verificar .env +cat .env | grep GLOBAL_API_KEY + +# Testar com API key correta +curl -H "apikey: SUA-CHAVE" http://localhost:4000/server/ok +``` + +### 5. QR Code não Aparece + +**Causa**: Instância já conectada ou erro de criação. + +**Solução**: + +```bash +# Verificar logs +docker-compose logs -f evolution-go | grep QR + +# Deletar e recriar instância +curl -X DELETE http://localhost:4000/instance/delete/NOME \ + -H "apikey: SUA-CHAVE" + +curl -X POST http://localhost:4000/instance/create \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE" \ + -d '{"instanceName": "NOME"}' +``` + +### 6. Webhook não Funciona + +**Causa**: URL inválida ou endpoint indisponível. + +**Solução**: + +```bash +# Testar webhook manualmente +curl -X POST https://seu-webhook.com/endpoint \ + -H "Content-Type: application/json" \ + -d '{"test": true}' + +# Verificar logs +docker-compose logs evolution-go | grep webhook + +# Verificar configuração +curl http://localhost:4000/instance/connectionState/NOME \ + -H "apikey: SUA-CHAVE" +``` + +### 7. Mensagem não Envia + +**Causa**: Instância desconectada, número inválido, ou erro de rede. + +**Solução**: + +```bash +# Verificar conexão +curl http://localhost:4000/instance/connectionState/NOME \ + -H "apikey: SUA-CHAVE" + +# Verificar logs +docker-compose logs -f evolution-go + +# Verificar formato do número +# Correto: 5511999999999 (DDI + DDD + número) +# Errado: 11999999999, +55 11 99999-9999 +``` + +--- + +## Debugging com IDE + +### VSCode + +1. Abrir `Run and Debug` (Ctrl+Shift+D) +2. Selecionar "Launch Evolution GO" +3. Adicionar breakpoints (F9) +4. Iniciar debug (F5) + +**launch.json**: + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Debug Evolution GO", + "type": "go", + "request": "launch", + "mode": "debug", + "program": "${workspaceFolder}/cmd/evolution-go", + "args": ["-dev"], + "showLog": true + } + ] +} +``` + +### GoLand + +1. **Run → Debug 'Evolution GO'** +2. Adicionar breakpoints (Ctrl+F8) +3. Debug com F5 + +--- + +## Profiling de Performance + +### CPU Profiling + +```bash +# Executar com pprof +go run cmd/evolution-go/main.go -dev & +PID=$! + +# Gerar CPU profile (30 segundos) +curl http://localhost:4000/debug/pprof/profile?seconds=30 > cpu.prof + +# Analisar +go tool pprof cpu.prof + +# Comandos no pprof: +# top10 - Top 10 funções +# list - Código da função +# web - Visualização gráfica (requer graphviz) +``` + +### Memory Profiling + +```bash +# Heap snapshot +curl http://localhost:4000/debug/pprof/heap > heap.prof + +# Analisar +go tool pprof heap.prof + +# Visualizar em browser +go tool pprof -http=:8081 heap.prof +``` + +### Goroutine Leaks + +```bash +# Ver goroutines ativas +curl http://localhost:4000/debug/pprof/goroutine?debug=1 + +# Profile de goroutines +curl http://localhost:4000/debug/pprof/goroutine > goroutine.prof +go tool pprof goroutine.prof +``` + +--- + +## Análise de Banco de Dados + +### Queries Lentas + +```sql +-- Habilitar log de queries lentas (PostgreSQL) +ALTER DATABASE evogo_users SET log_min_duration_statement = 1000; + +-- Ver queries lentas +SELECT query, calls, total_time, mean_time +FROM pg_stat_statements +ORDER BY mean_time DESC +LIMIT 10; +``` + +### Ver Conexões Ativas + +```sql +-- PostgreSQL +SELECT count(*) FROM pg_stat_activity; + +SELECT datname, usename, state, query +FROM pg_stat_activity +WHERE datname IN ('evogo_auth', 'evogo_users'); +``` + +### Índices Faltantes + +```sql +-- Verificar scans sequenciais (ruim) +SELECT schemaname, tablename, seq_scan, seq_tup_read +FROM pg_stat_user_tables +WHERE seq_scan > 0 +ORDER BY seq_tup_read DESC +LIMIT 10; +``` + +--- + +## Network Debugging + +### Testar Conectividade + +```bash +# Testar se porta está aberta +nc -zv localhost 4000 + +# Testar endpoint +curl -v http://localhost:4000/server/ok + +# Com proxy +curl -x http://proxy:8080 http://localhost:4000/server/ok +``` + +### Capturar Tráfego HTTP + +```bash +# tcpdump +sudo tcpdump -i any -A 'port 4000' + +# Wireshark +# Filtro: tcp.port == 4000 +``` + +--- + +## Ferramentas Úteis + +### 1. delve (Go Debugger) + +```bash +# Instalar +go install github.com/go-delve/delve/cmd/dlv@latest + +# Debug +dlv debug cmd/evolution-go/main.go -- -dev + +# Comandos: +# break main.main - Breakpoint +# continue - Continuar +# next - Próxima linha +# print var - Imprimir variável +``` + +### 2. Postman/Insomnia + +Importar collection Swagger: +- URL: http://localhost:4000/swagger/doc.json + +### 3. pgAdmin / DBeaver + +Conectar ao PostgreSQL: +- Host: localhost +- Port: 5432 +- Database: evogo_users +- Username: postgres + +### 4. Docker Stats + +```bash +# Ver uso de recursos +docker stats evolution-go + +# Inspecionar container +docker inspect evolution-go +``` + +--- + +## Checklist de Troubleshooting + +Quando algo não funciona: + +1. ✅ Verificar logs: `docker-compose logs -f` +2. ✅ Verificar .env: variáveis corretas? +3. ✅ Verificar PostgreSQL: está rodando? +4. ✅ Verificar porta: 4000 livre? +5. ✅ Verificar API key: está correta? +6. ✅ Testar health check: `/server/ok` +7. ✅ Verificar Swagger: documentação atualizada? +8. ✅ Verificar versão Go: 1.24+? + +--- + +## Recursos Adicionais + +- **Go Debugging**: https://go.dev/doc/gdb +- **GORM Debugging**: https://gorm.io/docs/logger.html +- **Gin Debugging**: https://gin-gonic.com/docs/examples/ + +--- + +**Mantido por**: Equipe EvoAI Services diff --git a/docs/wiki/desenvolvimento/development-guide.md b/docs/wiki/desenvolvimento/development-guide.md new file mode 100644 index 0000000..a471264 --- /dev/null +++ b/docs/wiki/desenvolvimento/development-guide.md @@ -0,0 +1,773 @@ +# Guia de Desenvolvimento + +Guia completo para desenvolver e contribuir com o Evolution GO. + +## Índice + +- [Visão Geral](#visão-geral) +- [Requisitos](#requisitos) +- [Setup Inicial](#setup-inicial) +- [Estrutura do Projeto](#estrutura-do-projeto) +- [Executando Localmente](#executando-localmente) +- [Makefile e Comandos](#makefile-e-comandos) +- [Configuração de IDE](#configuração-de-ide) +- [Convenções de Código](#convenções-de-código) +- [Workflow de Desenvolvimento](#workflow-de-desenvolvimento) +- [Próximos Passos](#próximos-passos) + +--- + +## Visão Geral + +O Evolution GO é um **gateway de API WhatsApp** escrito em Go, utilizando: + +- **Linguagem**: Go 1.24+ +- **Framework Web**: Gin +- **ORM**: GORM +- **Banco de Dados**: PostgreSQL / SQLite +- **WhatsApp Library**: whatsmeow +- **Documentação API**: Swagger + +--- + +## Requisitos + +### Obrigatórios + +- **Go 1.24+** ([Download](https://go.dev/dl/)) +- **Git** ([Download](https://git-scm.com/downloads)) +- **PostgreSQL 12+** ([Download](https://www.postgresql.org/download/)) + - Ou usar Docker: `docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:15-alpine` + +### Opcionais + +- **Make** (incluído no Linux/Mac, Windows: `choco install make`) +- **Docker** e **Docker Compose** (para desenvolvimento com containers) +- **RabbitMQ** (para testar sistema de eventos) +- **MinIO** (para testar armazenamento de mídia) + +### Ferramentas Recomendadas + +- **IDE**: VSCode, GoLand, ou Vim/Neovim +- **Postman** ou **Insomnia** (para testar API) +- **PostgreSQL Client**: pgAdmin, DBeaver, ou psql +- **Git GUI**: GitKraken, Sourcetree (opcional) + +--- + +## Setup Inicial + +### 1. Clonar o Repositório + +```bash +# Via HTTPS +git clone https://git.evoai.app/Evolution/evolution-go.git +cd evolution-go + +# Ou via SSH (se configurado) +git clone git@git.evochat.com:Evolution/evolution-go.git +cd evolution-go +``` + +### 2. Instalar Dependências Go + +```bash +# Baixar dependências +go mod download + +# Ou usando Make +make deps +``` + +### 3. Configurar PostgreSQL + +**Opção A: PostgreSQL Local** + +```bash +# Ubuntu/Debian +sudo apt-get install postgresql postgresql-contrib +sudo systemctl start postgresql + +# macOS +brew install postgresql@15 +brew services start postgresql@15 + +# Criar databases +sudo -u postgres psql << EOF +CREATE DATABASE evogo_auth; +CREATE DATABASE evogo_users; +EOF +``` + +**Opção B: PostgreSQL via Docker** + +```bash +docker run -d \ + --name postgres \ + -p 5432:5432 \ + -e POSTGRES_PASSWORD=postgres \ + -v postgres_data:/var/lib/postgresql/data \ + postgres:15-alpine + +# Criar databases +docker exec -i postgres psql -U postgres << EOF +CREATE DATABASE evogo_auth; +CREATE DATABASE evogo_users; +EOF +``` + +### 4. Configurar Variáveis de Ambiente + +```bash +# Copiar arquivo de exemplo +cp .env.example .env + +# Editar configurações +nano .env +``` + +**Configuração mínima (.env)**: + +```env +# Servidor +SERVER_PORT=4000 +CLIENT_NAME=evolution-dev + +# API Key (gere uma segura) +GLOBAL_API_KEY=dev-key-12345 + +# PostgreSQL +POSTGRES_AUTH_DB=postgresql://postgres:postgres@localhost:5432/evogo_auth?sslmode=disable +POSTGRES_USERS_DB=postgresql://postgres:postgres@localhost:5432/evogo_users?sslmode=disable +DATABASE_SAVE_MESSAGES=false + +# Logs +WADEBUG=DEBUG +LOGTYPE=console + +# Configurações de desenvolvimento +CONNECT_ON_STARTUP=false +WEBHOOKFILES=true +OS_NAME=Linux +``` + +### 5. Verificar Instalação + +```bash +# Verificar versão do Go +go version +# Deve mostrar: go version go1.24.x ... + +# Verificar dependências +go mod verify + +# Compilar (teste) +go build ./cmd/evolution-go +``` + +--- + +## Estrutura do Projeto + +``` +evolution-go/ +├── cmd/ +│ └── evolution-go/ +│ └── main.go # Entry point da aplicação +│ +├── pkg/ # Pacotes principais +│ ├── config/ # Configuração e env vars +│ │ ├── config.go +│ │ └── env.go +│ │ +│ ├── instance/ # Gerenciamento de instâncias +│ │ ├── handler.go # HTTP handlers +│ │ ├── service.go # Lógica de negócio +│ │ ├── repository.go # Acesso ao banco +│ │ └── model/ +│ │ └── instance_model.go +│ │ +│ ├── whatsmeow/ # Cliente WhatsApp +│ │ ├── whatsmeow.go +│ │ └── events.go +│ │ +│ ├── message/ # Mensagens +│ │ ├── handler.go +│ │ ├── service.go +│ │ ├── repository.go +│ │ └── model/ +│ │ +│ ├── sendMessage/ # Envio de mensagens +│ │ ├── handler.go +│ │ └── service.go +│ │ +│ ├── events/ # Produtores de eventos +│ │ ├── webhook/ +│ │ ├── rabbitmq/ +│ │ ├── nats/ +│ │ └── websocket/ +│ │ +│ ├── storage/ # Armazenamento de mídia +│ │ ├── media_storage.go +│ │ └── minio/ +│ │ +│ └── utils/ # Utilitários +│ ├── logger/ +│ └── validator/ +│ +├── docs/ # Documentação Swagger +│ ├── docs.go +│ ├── swagger.json +│ └── swagger.yaml +│ +├── docker/ # Configurações Docker +│ └── examples/ +│ ├── docker-compose.yml +│ ├── docker-compose.swarm.yml +│ └── .env.example +│ +├── Dockerfile # Imagem Docker +├── Makefile # Comandos de automação +├── go.mod # Dependências Go +├── go.sum # Checksums de dependências +├── .env.example # Exemplo de variáveis de ambiente +└── README.md # Documentação principal +``` + +### Arquitetura em Camadas + +Cada módulo segue o padrão **Handler → Service → Repository**: + +``` +┌─────────────┐ +│ Handler │ ← Recebe requests HTTP (Gin) +└──────┬──────┘ + │ + ▼ +┌─────────────┐ +│ Service │ ← Lógica de negócio +└──────┬──────┘ + │ + ▼ +┌─────────────┐ +│ Repository │ ← Acesso ao banco (GORM) +└─────────────┘ +``` + +--- + +## Executando Localmente + +### Modo Desenvolvimento (Hot Reload) + +```bash +# Executar em modo dev +make dev + +# Ou diretamente +go run cmd/evolution-go/main.go -dev +``` + +**Saída esperada**: + +``` +[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. +[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. +[GIN-debug] GET /swagger/*any --> github.com/swaggo/gin-swagger.CustomWrapHandler.func1 (3 handlers) +[GIN-debug] GET /server/ok --> main.main.func1 (3 handlers) +[GIN-debug] POST /instance/create --> evolution-go/pkg/instance.(*InstanceHandler).Create-fm (4 handlers) +... +[GIN-debug] Listening and serving HTTP on :4000 +``` + +### Build e Executar + +```bash +# Build local +make build-local + +# Executar binário +./build/evolution-go +``` + +### Com Docker Compose + +```bash +# Copiar exemplo +cp docker/examples/docker-compose.yml ./ + +# Editar GLOBAL_API_KEY +nano docker-compose.yml + +# Iniciar +docker-compose up -d + +# Ver logs +docker-compose logs -f evolution-go +``` + +### Acessar a Aplicação + +- **API Base**: http://localhost:4000 +- **Health Check**: http://localhost:4000/server/ok +- **Swagger UI**: http://localhost:4000/swagger/index.html + +--- + +## Makefile e Comandos + +### Comandos de Desenvolvimento + +```bash +# Executar em modo dev (hot reload) +make dev + +# Build para produção (Linux) +make build + +# Build local (seu SO) +make build-local + +# Build e executar +make run +``` + +### Comandos de Qualidade + +```bash +# Instalar dependências +make deps + +# Atualizar dependências +make deps-update + +# Formatar código +make fmt + +# Lint (fmt + vet) +make lint + +# Verificar tudo (deps + lint) +make check +``` + +### Comandos de Documentação + +```bash +# Gerar documentação Swagger +make swagger + +# Requer: go install github.com/swaggo/swag/cmd/swag@latest +``` + +### Comandos Docker + +```bash +# Build imagem Docker +make docker-build + +# Executar container +make docker-run + +# Executar em modo dev +make docker-run-dev + +# Limpar imagens +make docker-clean +``` + +### Comandos Auxiliares + +```bash +# Ver logs +make logs + +# Limpar builds +make clean + +# Setup completo (deps + tools) +make setup + +# Quick start +make quick-start +``` + +--- + +## Configuração de IDE + +### Visual Studio Code + +#### Extensões Recomendadas + +```json +{ + "recommendations": [ + "golang.go", // Go support + "ms-vscode.makefile-tools", // Makefile support + "humao.rest-client", // REST client + "42crunch.vscode-openapi", // Swagger/OpenAPI + "streetsidesoftware.code-spell-checker" + ] +} +``` + +Salvar em `.vscode/extensions.json`. + +#### Settings + +```json +{ + "go.useLanguageServer": true, + "go.lintTool": "golangci-lint", + "go.lintOnSave": "package", + "go.formatTool": "goimports", + "editor.formatOnSave": true, + "go.testFlags": ["-v"], + "go.coverOnSave": false, + "[go]": { + "editor.codeActionsOnSave": { + "source.organizeImports": true + } + } +} +``` + +Salvar em `.vscode/settings.json`. + +#### Tasks + +```json +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Run Dev", + "type": "shell", + "command": "make dev", + "group": { + "kind": "build", + "isDefault": true + } + }, + { + "label": "Build", + "type": "shell", + "command": "make build-local" + }, + { + "label": "Lint", + "type": "shell", + "command": "make lint" + } + ] +} +``` + +Salvar em `.vscode/tasks.json`. + +#### Launch (Debug) + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Evolution GO", + "type": "go", + "request": "launch", + "mode": "debug", + "program": "${workspaceFolder}/cmd/evolution-go", + "args": ["-dev"], + "env": { + "WADEBUG": "DEBUG" + }, + "showLog": true + } + ] +} +``` + +Salvar em `.vscode/launch.json`. + +### GoLand / IntelliJ IDEA + +#### Run Configuration + +1. **Run → Edit Configurations** +2. **Add New Configuration → Go Build** +3. Configurar: + - **Name**: Evolution GO Dev + - **Run kind**: Directory + - **Directory**: `cmd/evolution-go` + - **Program arguments**: `-dev` + - **Environment**: `WADEBUG=DEBUG` + - **Working directory**: Raiz do projeto + +#### File Watchers (opcional) + +1. **Settings → Tools → File Watchers** +2. **Add → go fmt** +3. **Add → goimports** + +--- + +## Convenções de Código + +### Estrutura de Pacotes + +```go +// Cada módulo deve ter: +package instance + +// handler.go - HTTP handlers +type InstanceHandler struct { + service InstanceService +} + +func (h *InstanceHandler) Create(c *gin.Context) { } + +// service.go - Lógica de negócio +type InstanceService interface { + Create(data CreateInstanceDTO) (*Instance, error) +} + +// repository.go - Banco de dados +type InstanceRepository interface { + Save(instance *Instance) error + FindByID(id string) (*Instance, error) +} + +// model/instance_model.go - Structs +type Instance struct { + Id string + Name string +} +``` + +### Nomenclatura + +```go +// Variáveis: camelCase +var instanceName string + +// Constantes: PascalCase ou UPPER_CASE +const MaxRetries = 5 +const DEFAULT_TIMEOUT = 30 + +// Structs: PascalCase +type InstanceConfig struct { } + +// Interfaces: PascalCase + sufixo "er" ou nome descritivo +type InstanceRepository interface { } +type MessageSender interface { } + +// Métodos: PascalCase +func (h *Handler) CreateInstance() { } + +// Funções privadas: camelCase +func parseConfig() { } + +// Funções públicas: PascalCase +func NewInstanceHandler() { } +``` + +### Comentários + +```go +// Comentários de package (em _doc.go ou no arquivo principal) +// Package instance fornece gerenciamento de instâncias WhatsApp. +package instance + +// Comentários de funções exportadas (obrigatório para Swagger) +// CreateInstance cria uma nova instância WhatsApp. +// +// @Summary Criar instância +// @Description Cria uma nova instância WhatsApp +// @Tags instance +// @Accept json +// @Produce json +// @Param data body CreateInstanceDTO true "Dados da instância" +// @Success 201 {object} Instance +// @Failure 400 {object} ErrorResponse +// @Router /instance/create [post] +func (h *InstanceHandler) CreateInstance(c *gin.Context) { + // Implementação... +} + +// Comentários inline para lógica complexa +// Gera UUID v4 para identificação única +instanceID := uuid.New().String() +``` + +### Tratamento de Erros + +```go +// Sempre retornar erros, não panic +func CreateInstance(name string) (*Instance, error) { + if name == "" { + return nil, fmt.Errorf("name cannot be empty") + } + + instance := &Instance{Name: name} + if err := repository.Save(instance); err != nil { + return nil, fmt.Errorf("failed to save instance: %w", err) + } + + return instance, nil +} + +// Em handlers HTTP +func (h *Handler) Create(c *gin.Context) { + var dto CreateDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return + } + + instance, err := h.service.Create(dto) + if err != nil { + logger.LogError("Failed to create instance: %v", err) + c.JSON(500, gin.H{"error": "Internal server error"}) + return + } + + c.JSON(201, instance) +} +``` + +### Logging + +```go +import "evolution-go/pkg/utils/logger" + +// Níveis de log +logger.LogInfo("Instance %s created successfully", instanceName) +logger.LogWarn("Webhook URL not configured for instance %s", instanceName) +logger.LogError("Failed to connect to database: %v", err) +logger.LogDebug("Processing message: %+v", message) +``` + +--- + +## Workflow de Desenvolvimento + +### 1. Criar Branch + +```bash +# Atualizar main +git checkout main +git pull origin main + +# Criar feature branch +git checkout -b feature/nome-da-feature + +# Ou bugfix +git checkout -b fix/nome-do-bug +``` + +### 2. Desenvolver + +```bash +# Executar em modo dev +make dev + +# Em outro terminal, fazer mudanças no código +# O servidor reinicia automaticamente com hot-reload +``` + +### 3. Testar Manualmente + +```bash +# Testar health check +curl http://localhost:4000/server/ok + +# Criar instância +curl -X POST http://localhost:4000/instance/create \ + -H "Content-Type: application/json" \ + -H "apikey: dev-key-12345" \ + -d '{"instanceName": "teste"}' + +# Verificar Swagger +open http://localhost:4000/swagger/index.html +``` + +### 4. Formatar e Lint + +```bash +# Formatar código +make fmt + +# Lint +make lint +``` + +### 5. Atualizar Swagger (se alterou endpoints) + +```bash +# Gerar documentação +make swagger + +# Verificar se docs/ foi atualizado +git status +``` + +### 6. Commit + +```bash +# Add mudanças +git add . + +# Commit com mensagem descritiva +git commit -m "feat: adiciona endpoint de listagem de instâncias + +- Implementa GET /instance/list +- Adiciona paginação +- Atualiza documentação Swagger" + +# Padrões de commit: +# feat: nova feature +# fix: correção de bug +# docs: documentação +# refactor: refatoração +# chore: tarefas de manutenção +``` + +### 7. Push e Pull Request + +```bash +# Push para origin +git push origin feature/nome-da-feature + +# Criar PR no GitLab/GitHub +# Preencher descrição detalhada +# Aguardar code review +``` + +--- + +## Próximos Passos + +Após setup completo: + +1. **[Como Contribuir](./contributing.md)** - Processo de contribuição e PR +2. **[Debugging](./debugging.md)** - Troubleshooting e resolução de problemas +3. **[Arquitetura](../conceitos-core/architecture.md)** - Entenda a arquitetura +4. **[API Overview](../guias-api/api-overview.md)** - Comece a desenvolver na API + +--- + +## Recursos Adicionais + +- **Documentação Go**: https://go.dev/doc/ +- **GORM**: https://gorm.io/docs/ +- **Gin Framework**: https://gin-gonic.com/docs/ +- **Whatsmeow**: https://github.com/tulir/whatsmeow +- **Swagger**: https://swagger.io/docs/ + +--- + +**Dica**: Use `make help` para ver todos os comandos disponíveis! + +**Mantido por**: Equipe EvoAI Services +**Versão**: 1.0.0 diff --git a/docs/wiki/fundamentos/configuration.md b/docs/wiki/fundamentos/configuration.md new file mode 100644 index 0000000..35460c0 --- /dev/null +++ b/docs/wiki/fundamentos/configuration.md @@ -0,0 +1,558 @@ +# Configuração + +Referência completa de variáveis de ambiente do Evolution GO. + +Para exemplos práticos, consulte: `docker/examples/.env.example` + +## Configuração via Ambiente + +As configurações podem ser definidas através de: +- **Variáveis de ambiente** (Docker, Kubernetes) +- **Arquivo `.env`** (instalação local) + +--- + +## Variáveis Obrigatórias + +### GLOBAL_API_KEY + +Chave de autenticação para acesso à API. + +- **Tipo**: String (UUID recomendado) +- **Obrigatório**: Sim + +```env +GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db +``` + +**Geração:** +```bash +# UUID v4 +uuidgen + +# Ou via Python +python3 -c "import uuid; print(uuid.uuid4())" +``` + +### DATABASE_SAVE_MESSAGES + +Habilita persistência de mensagens no banco de dados. + +- **Tipo**: Boolean +- **Obrigatório**: Sim +- **Padrão**: `false` + +```env +DATABASE_SAVE_MESSAGES=false +``` + +**Nota**: `true` aumenta significativamente o uso de storage. Recomendado apenas quando necessário manter histórico completo. + +--- + +## Servidor + +### SERVER_PORT + +Porta HTTP do servidor API. + +- **Tipo**: Integer +- **Padrão**: `4000` + +```env +SERVER_PORT=4000 +``` + +### CLIENT_NAME + +Identificador do cliente/instalação. + +- **Tipo**: String + +```env +CLIENT_NAME=evolution-production +``` + +### OS_NAME + +Sistema operacional do ambiente. + +- **Tipo**: String +- **Valores**: `Linux`, `Windows`, `macOS` + +```env +OS_NAME=Linux +``` + +--- + +## Banco de Dados PostgreSQL + +### POSTGRES_AUTH_DB + +String de conexão para banco de autenticação. + +- **Formato**: `postgresql://user:pass@host:port/database?sslmode=disable` + +```env +POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable +``` + +### POSTGRES_USERS_DB + +String de conexão para banco de dados de usuários. + +```env +POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable +``` + +**Componentes da URL:** +- `postgres` - usuário +- `senha` - password (substituir) +- `postgres` - hostname (ou `localhost`) +- `5432` - porta +- `evogo_auth` / `evogo_users` - database name + +--- + +## Logs e Debug + +### WADEBUG + +Nível de logging do WhatsApp. + +- **Valores**: `ERROR`, `INFO`, `DEBUG` +- **Padrão**: `INFO` + +```env +WADEBUG=INFO +``` + +- `ERROR` - Apenas erros críticos +- `INFO` - Informações importantes +- `DEBUG` - Detalhamento completo (uso em desenvolvimento) + +### LOGTYPE + +Destino de saída dos logs. + +- **Valores**: `console`, `file` +- **Padrão**: `console` + +```env +LOGTYPE=console +``` + +### LOG_DIRECTORY + +Diretório para arquivos de log (quando `LOGTYPE=file`). + +- **Padrão**: `./logs` + +```env +LOG_DIRECTORY=/app/logs +``` + +### LOG_MAX_SIZE + +Tamanho máximo de cada arquivo de log em MB. + +- **Padrão**: `100` + +```env +LOG_MAX_SIZE=100 +``` + +### LOG_MAX_BACKUPS + +Número de arquivos de log rotacionados a manter. + +- **Padrão**: `5` + +```env +LOG_MAX_BACKUPS=5 +``` + +### LOG_MAX_AGE + +Dias de retenção de arquivos de log. + +- **Padrão**: `30` + +```env +LOG_MAX_AGE=30 +``` + +### LOG_COMPRESS + +Compressão de logs rotacionados. + +- **Tipo**: Boolean +- **Padrão**: `true` + +```env +LOG_COMPRESS=true +``` + +--- + +## Conexão e Comportamento + +### CONNECT_ON_STARTUP + +Conecta automaticamente todas as instâncias ao iniciar o servidor. + +- **Tipo**: Boolean +- **Padrão**: `false` + +```env +CONNECT_ON_STARTUP=false +``` + +**Recomendação**: `false` para maior controle sobre o ciclo de vida das instâncias. + +### WEBHOOKFILES + +Envia URLs de mídia nos payloads de webhook. + +- **Tipo**: Boolean +- **Padrão**: `true` + +```env +WEBHOOKFILES=true +``` + +### QRCODE_MAX_COUNT + +Número máximo de tentativas de geração de QR Code antes de exigir reconexão manual. + +- **Tipo**: Integer +- **Padrão**: `5` + +```env +QRCODE_MAX_COUNT=5 +``` + +### CHECK_USER_EXISTS + +Valida existência do destinatário no WhatsApp antes de enviar mensagem. + +- **Tipo**: Boolean +- **Padrão**: `true` + +```env +CHECK_USER_EXISTS=true +``` + +**Nota**: `false` pode resultar em erros de envio para números inválidos. + +### EVENT_IGNORE_GROUP + +Ignora eventos originados de grupos. + +- **Tipo**: Boolean +- **Padrão**: `false` + +```env +EVENT_IGNORE_GROUP=false +``` + +### EVENT_IGNORE_STATUS + +Ignora eventos de status/stories. + +- **Tipo**: Boolean +- **Padrão**: `true` + +```env +EVENT_IGNORE_STATUS=true +``` + +--- + +## Webhooks + +### WEBHOOK_URL + +URL de destino para callbacks HTTP de eventos. + +```env +WEBHOOK_URL=https://api.seudominio.com/webhook +``` + +Eventos serão enviados via POST com payload JSON: + +```json +{ + "event": "messages.upsert", + "instanceName": "nome-instancia", + "data": { ... } +} +``` + +--- + +## RabbitMQ (AMQP) + +Sistema de filas para processamento assíncrono de eventos. + +### AMQP_URL + +URL de conexão RabbitMQ. + +- **Formato**: `amqp://user:pass@host:port/vhost` + +```env +AMQP_URL=amqp://admin:admin@rabbitmq:5672/default +``` + +### AMQP_GLOBAL_ENABLED + +Habilita publicação global de eventos via RabbitMQ. + +- **Tipo**: Boolean +- **Padrão**: `false` + +```env +AMQP_GLOBAL_ENABLED=true +``` + +### AMQP_GLOBAL_EVENTS + +Lista de eventos a serem publicados (separados por vírgula). + +```env +AMQP_GLOBAL_EVENTS=messages.upsert,messages.update,connection.update +``` + +**Eventos disponíveis:** +- `messages.upsert` - Nova mensagem recebida +- `messages.update` - Atualização de mensagem (leitura, entrega) +- `connection.update` - Mudança de status de conexão +- Entre outros + +--- + +## NATS + +Sistema de mensageria para eventos distribuídos. + +### NATS_URL + +URL do servidor NATS. + +```env +NATS_URL=nats://localhost:4222 +``` + +### NATS_GLOBAL_ENABLED + +Habilita publicação de eventos via NATS. + +- **Tipo**: Boolean +- **Padrão**: `false` + +```env +NATS_GLOBAL_ENABLED=true +``` + +--- + +## MinIO/S3 + +Armazenamento de objetos para mídia. + +### MINIO_ENABLED + +Habilita integração com MinIO/S3. + +- **Tipo**: Boolean +- **Padrão**: `false` + +```env +MINIO_ENABLED=true +``` + +### MINIO_ENDPOINT + +Endpoint do servidor de objetos. + +```env +# MinIO local +MINIO_ENDPOINT=localhost:9000 + +# AWS S3 +MINIO_ENDPOINT=s3.amazonaws.com +``` + +### MINIO_ACCESS_KEY + +Access Key para autenticação. + +```env +MINIO_ACCESS_KEY=minioadmin +``` + +### MINIO_SECRET_KEY + +Secret Key para autenticação. + +```env +MINIO_SECRET_KEY=minioadmin +``` + +### MINIO_BUCKET + +Nome do bucket para armazenamento de mídia. + +```env +MINIO_BUCKET=evolution-media +``` + +**Nota**: O bucket deve existir antes de habilitar a integração. + +### MINIO_USE_SSL + +Utiliza HTTPS para conexões ao S3/MinIO. + +- **Tipo**: Boolean +- **Padrão**: `false` + +```env +MINIO_USE_SSL=true +``` + +### MINIO_REGION + +Região do bucket S3 (AWS). + +- **Padrão**: `us-east-1` + +```env +MINIO_REGION=us-east-1 +``` + +--- + +## Proxy + +Configuração de proxy HTTP para instâncias WhatsApp. + +### PROXY_HOST + +Hostname do servidor proxy. + +```env +PROXY_HOST=proxy.empresa.com +``` + +### PROXY_PORT + +Porta do proxy. + +```env +PROXY_PORT=8080 +``` + +### PROXY_USERNAME + +Usuário para autenticação (se requerido). + +```env +PROXY_USERNAME=usuario +``` + +### PROXY_PASSWORD + +Senha para autenticação (se requerido). + +```env +PROXY_PASSWORD=senha +``` + +--- + +## Recursos Adicionais + +### API_AUDIO_CONVERTER + +URL de serviço externo para conversão de áudio. + +```env +API_AUDIO_CONVERTER=https://converter.seudominio.com +``` + +### API_AUDIO_CONVERTER_KEY + +Chave de autenticação do serviço de conversão. + +```env +API_AUDIO_CONVERTER_KEY=chave-do-servico +``` + +--- + +## Versão WhatsApp (Avançado) + +**⚠️ Atenção**: Modificar a versão do WhatsApp pode resultar em bloqueio de conta. Use apenas quando estritamente necessário. + +### WHATSAPP_VERSION_MAJOR + +```env +WHATSAPP_VERSION_MAJOR=2 +``` + +### WHATSAPP_VERSION_MINOR + +```env +WHATSAPP_VERSION_MINOR=2412 +``` + +### WHATSAPP_VERSION_PATCH + +```env +WHATSAPP_VERSION_PATCH=54 +``` + +**Recomendação**: Deixar não configurado para utilizar versão automática da biblioteca whatsmeow. + +--- + +## Exemplo de Configuração Mínima + +```env +# Obrigatórias +GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db +DATABASE_SAVE_MESSAGES=false + +# Servidor +SERVER_PORT=4000 +CLIENT_NAME=evolution +OS_NAME=Linux + +# Banco de Dados +POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable +POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable + +# Logs +WADEBUG=INFO +LOGTYPE=console + +# Comportamento +CONNECT_ON_STARTUP=false +WEBHOOKFILES=true +CHECK_USER_EXISTS=true +EVENT_IGNORE_STATUS=true +``` + +--- + +## Referências + +- **[Instalação](./installation.md)** - Guia de instalação +- **[Início Rápido](./quickstart.md)** - Primeiro uso +- **[.env.example](../../../docker/examples/.env.example)** - Exemplo completo com todas variáveis + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/fundamentos/installation.md b/docs/wiki/fundamentos/installation.md new file mode 100644 index 0000000..ec05c03 --- /dev/null +++ b/docs/wiki/fundamentos/installation.md @@ -0,0 +1,491 @@ +# Guia de Instalação + +Métodos de instalação do Evolution GO para diferentes ambientes. + +## Índice + +- [Requisitos](#requisitos) +- [Instalação com Docker (Recomendado)](#instalação-com-docker-recomendado) +- [Instalação Local](#instalação-local) +- [Instalação com Docker Swarm](#instalação-com-docker-swarm) +- [Stack Completa](#stack-completa) +- [Verificação](#verificação) +- [Solução de Problemas](#solução-de-problemas) + +--- + +## Requisitos + +### Docker (Recomendado) + +- Docker 20.10+ +- Docker Compose 2.0+ +- PostgreSQL 12+ (containerizado) +- Mínimo 1GB RAM +- Mínimo 2GB disco + +### Instalação Local + +- Go 1.24+ +- PostgreSQL 12+ +- Git +- Mínimo 1GB RAM +- Mínimo 2GB disco + +### Opcionais + +- RabbitMQ - Sistema de filas +- NATS - Mensageria distribuída +- MinIO - Storage S3-compatible + +--- + +## Instalação com Docker (Recomendado) + +Método mais simples e adequado para produção. + +### 1. Obter Arquivos + +**Opção A: Clonar repositório** + +```bash +git clone https://git.evoai.app/Evolution/evolution-go.git +cd evolution-go +``` + +**Opção B: Download direto** + +```bash +mkdir evolution-go-deploy && cd evolution-go-deploy + +curl -o docker-compose.yml https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/docker-compose.yml +curl -o init-db.sql https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/init-db.sql +``` + +### 2. Configurar API Key + +Gere uma chave segura: + +```bash +# Linux/Mac +uuidgen + +# Python +python3 -c "import uuid; print(uuid.uuid4())" + +# Resultado exemplo: df16caad-d0d2-41b2-bec5-75b90048a0db +``` + +Edite `docker-compose.yml`: + +```bash +nano docker-compose.yml +``` + +Localize e substitua: +```yaml +GLOBAL_API_KEY: "SUA-CHAVE-API-SEGURA-AQUI" +``` + +Por: +```yaml +GLOBAL_API_KEY: "df16caad-d0d2-41b2-bec5-75b90048a0db" +``` + +### 3. Iniciar Serviços + +```bash +docker-compose up -d +``` + +Aguarde ~30 segundos para inicialização completa. + +### 4. Verificar Logs + +```bash +# Evolution GO +docker-compose logs -f evolution-go + +# PostgreSQL +docker-compose logs -f postgres +``` + +### 5. Acessar Aplicação + +- **API**: http://localhost:4000 +- **Swagger**: http://localhost:4000/swagger/index.html +- **Health Check**: http://localhost:4000/server/ok + +--- + +## Instalação Local + +Para ambientes de desenvolvimento. + +### 1. Instalar PostgreSQL + +**Ubuntu/Debian:** +```bash +sudo apt-get update +sudo apt-get install postgresql postgresql-contrib +``` + +**macOS:** +```bash +brew install postgresql@15 +brew services start postgresql@15 +``` + +**Windows:** +Download: https://www.postgresql.org/download/windows/ + +### 2. Configurar Banco de Dados + +```bash +sudo -u postgres psql +``` + +```sql +CREATE DATABASE evogo_auth; +CREATE DATABASE evogo_users; +\q +``` + +### 3. Instalar Go + +Download: https://go.dev/dl/ + +Verificar: +```bash +go version +``` + +### 4. Clonar Repositório + +```bash +git clone https://git.evoai.app/Evolution/evolution-go.git +cd evolution-go +``` + +### 5. Instalar Dependências + +```bash +go mod download +``` + +Ou: +```bash +make deps +``` + +### 6. Configurar Ambiente + +```bash +cp .env.example .env +nano .env +``` + +Configuração mínima: + +```env +SERVER_PORT=4000 +GLOBAL_API_KEY=sua-chave-gerada + +POSTGRES_AUTH_DB=postgresql://postgres:postgres@localhost:5432/evogo_auth?sslmode=disable +POSTGRES_USERS_DB=postgresql://postgres:postgres@localhost:5432/evogo_users?sslmode=disable +DATABASE_SAVE_MESSAGES=false + +WADEBUG=DEBUG +LOGTYPE=console +CONNECT_ON_STARTUP=false +WEBHOOKFILES=true +OS_NAME=Linux +``` + +### 7. Executar + +**Modo desenvolvimento:** +```bash +make dev +``` + +Ou: +```bash +go run cmd/evolution-go/main.go -dev +``` + +**Build produção:** +```bash +make build-local +./build/evolution-go +``` + +--- + +## Instalação com Docker Swarm + +Para ambientes com alta disponibilidade. + +### 1. Inicializar Swarm + +```bash +docker swarm init +``` + +### 2. Criar Recursos + +```bash +docker volume create evolution_go_data +docker volume create evolution_go_logs +docker network create --driver overlay network_public +``` + +### 3. Configurar Stack + +```bash +cp docker/examples/docker-compose.swarm.yml ./docker-compose.swarm.yml +nano docker-compose.swarm.yml +``` + +Configure: +- `GLOBAL_API_KEY` +- `POSTGRES_AUTH_DB` +- `POSTGRES_USERS_DB` +- Labels Traefik (se aplicável) + +### 4. Deploy + +```bash +docker stack deploy -c docker-compose.swarm.yml evolution +``` + +### 5. Verificar + +```bash +docker service ls +docker service logs evolution_evolution_go -f +``` + +--- + +## Stack Completa + +Incluindo RabbitMQ, MinIO e NATS. + +```bash +curl -o docker-compose-full.yml https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/docker-compose.full.yml + +nano docker-compose-full.yml # Configurar API Key + +docker-compose -f docker-compose-full.yml up -d +``` + +**Serviços incluídos:** + +| Serviço | Porta | Função | +|---------|-------|--------| +| Evolution GO | 4000 | API principal | +| PostgreSQL | 5432 | Banco de dados | +| RabbitMQ | 5672, 15672 | Filas de mensagens | +| MinIO | 9000, 9001 | Storage de objetos | +| NATS | 4222 | Mensageria (opcional) | + +**Acessos:** + +- Evolution GO: http://localhost:4000 +- Swagger: http://localhost:4000/swagger/index.html +- RabbitMQ: http://localhost:15672 (admin/admin) +- MinIO: http://localhost:9001 (minioadmin/minioadmin) + +**Configuração MinIO (primeira vez):** + +1. Acesse http://localhost:9001 +2. Login: minioadmin / minioadmin +3. Create bucket: `evolution-media` +4. Configurar política de acesso + +--- + +## Verificação + +### Health Check + +```bash +curl http://localhost:4000/server/ok +``` + +Resposta esperada: +```json +{ + "status": "ok" +} +``` + +### Swagger UI + +Acesse: http://localhost:4000/swagger/index.html + +### Criar Instância de Teste + +```bash +curl -X POST http://localhost:4000/instance/create \ + -H "Content-Type: application/json" \ + -H "apikey: sua-chave-api-global" \ + -d '{ + "name": "teste", + "token": "token-unico-para-esta-instancia" + }' +``` + +> **Nota:** Use a `GLOBAL_API_KEY` no header e forneça `name` + `token` no body. + +### Verificar Logs + +**Docker:** +```bash +docker-compose logs -f evolution-go +``` + +**Local:** +```bash +tail -f logs/evolution-go.log +``` + +--- + +## Solução de Problemas + +### Connection Refused (PostgreSQL) + +**Diagnóstico:** +```bash +docker-compose ps postgres +# Ou local: +sudo systemctl status postgresql +``` + +**Verificar databases:** +```bash +docker-compose exec postgres psql -U postgres -c "\l" +``` + +### Porta em Uso + +Alterar porta no `docker-compose.yml`: +```yaml +ports: + - "4001:4000" +``` + +Acesso via: http://localhost:4001 + +### Container Reiniciando + +**Ver logs:** +```bash +docker-compose logs evolution-go +``` + +**Causas comuns:** +- `GLOBAL_API_KEY` não definida +- PostgreSQL não acessível +- Credenciais incorretas + +### Permissões de Volume + +```bash +mkdir -p logs dbdata +chmod 777 logs dbdata +``` + +Ou usar bind mounts: +```yaml +volumes: + - ./logs:/app/logs + - ./dbdata:/app/dbdata +``` + +### MinIO Bucket Não Existe + +1. Acessar console: http://localhost:9001 +2. Login: minioadmin / minioadmin +3. Criar bucket: `evolution-media` + +Ou via CLI: +```bash +docker-compose exec minio mc mb /data/evolution-media +``` + +--- + +## Comandos Úteis + +### Docker Compose + +```bash +# Iniciar +docker-compose up -d + +# Parar +docker-compose stop + +# Reiniciar +docker-compose restart + +# Status +docker-compose ps + +# Logs +docker-compose logs -f + +# Remover +docker-compose down + +# Atualizar +docker-compose pull +docker-compose up -d +``` + +### Docker Swarm + +```bash +# Listar serviços +docker service ls + +# Logs +docker service logs evolution_evolution_go -f + +# Escalar +docker service scale evolution_evolution_go=3 + +# Atualizar +docker service update --image evoapicloud/evolution-go:latest evolution_evolution_go + +# Remover +docker stack rm evolution +``` + +--- + +## Próximos Passos + +- **[Configuração](./configuration.md)** - Variáveis de ambiente +- **[Início Rápido](./quickstart.md)** - Primeira instância +- **[API Overview](../guias-api/api-overview.md)** - Estrutura da API +- **[Docker Deployment](../deploy-producao/docker-deployment.md)** - Deploy avançado + +--- + +## Arquivos de Exemplo + +Disponíveis em `docker/examples/`: + +- [docker-compose.yml](../../../docker/examples/docker-compose.yml) +- [docker-compose.swarm.yml](../../../docker/examples/docker-compose.swarm.yml) +- [docker-compose.full.yml](../../../docker/examples/docker-compose.full.yml) +- [init-db.sql](../../../docker/examples/init-db.sql) +- [.env.example](../../../docker/examples/.env.example) + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/fundamentos/introduction.md b/docs/wiki/fundamentos/introduction.md new file mode 100644 index 0000000..05138df --- /dev/null +++ b/docs/wiki/fundamentos/introduction.md @@ -0,0 +1,242 @@ +# Introdução ao Evolution GO + +## Visão Geral + +Evolution GO é um gateway de API WhatsApp construído em Go que fornece uma interface RESTful para integração com o protocolo WhatsApp Web. Funciona como camada de abstração entre aplicações e o WhatsApp, permitindo automação de mensagens, gerenciamento de múltiplas instâncias e integração através de APIs padronizadas. + +O projeto utiliza a biblioteca [whatsmeow](https://github.com/tulir/whatsmeow), uma implementação Go do protocolo WhatsApp Web Multi-Device, e adiciona sobre ela recursos empresariais como APIs REST, sistema de eventos, persistência de dados e gerenciamento multi-instância. + +## O que o Evolution GO oferece + +### Comunicação via API REST + +Envie e receba mensagens do WhatsApp através de requisições HTTP padrão: +- Mensagens de texto com formatação +- Mídia (imagens, vídeos, áudios, documentos) +- Localização, contatos e stickers +- Mensagens interativas (botões, listas, enquetes) +- Grupos e comunidades + +### Gerenciamento Multi-Instância + +- Conecte múltiplas contas WhatsApp simultaneamente +- Cada instância opera de forma independente +- Gerenciamento de ciclo de vida completo +- Configuração de proxy por instância +- Logs isolados por instância + +### Sistema de Eventos + +Receba notificações em tempo real através de: +- **Webhooks** - Callbacks HTTP para serviços externos +- **RabbitMQ** - Filas de mensagens para processamento assíncrono +- **NATS** - Mensageria leve para eventos distribuídos +- **WebSocket** - Conexões em tempo real + +### Armazenamento Empresarial + +- **Dual Database** - Separação entre dados de autenticação e usuários +- **PostgreSQL** - Banco principal para produção +- **SQLite** - Alternativa para desenvolvimento +- **MinIO/S3** - Armazenamento de mídia escalável +- Pool de conexões otimizado + +## Arquitetura + +O Evolution GO segue arquitetura em camadas: + +``` +┌─────────────────────────────────────────┐ +│ Camada Handler (HTTP) │ +│ Validação e Roteamento de Requests │ +├─────────────────────────────────────────┤ +│ Camada Service │ +│ Lógica de Negócio e Regras │ +├─────────────────────────────────────────┤ +│ Camada Repository │ +│ Persistência e Acesso a Dados │ +└─────────────────────────────────────────┘ +``` + +### Componentes Principais + +- **Instance Manager** - Gerencia ciclo de vida das sessões WhatsApp +- **Whatsmeow Service** - Wrapper sobre a biblioteca whatsmeow +- **Message Service** - Processamento e entrega de mensagens +- **Event System** - Propagação multi-canal de eventos +- **Storage Service** - Gerenciamento de mídia +- **User Service** - Perfis, contatos e configurações +- **Group Service** - Administração de grupos +- **Community Service** - Gerenciamento de comunidades + +### Biblioteca Whatsmeow + +A [whatsmeow](https://github.com/tulir/whatsmeow) implementa o protocolo WhatsApp Web Multi-Device: +- Comunicação direta com servidores WhatsApp +- Criptografia end-to-end +- Suporte a multi-dispositivos +- Sincronização de mensagens +- Gerenciamento de sessões + +O Evolution GO utiliza a whatsmeow como base e adiciona camada empresarial com APIs REST, gerenciamento de múltiplas instâncias, sistema de eventos e persistência. + +## Casos de Uso + +**Automação de Atendimento** +- Chatbots com respostas automáticas +- Integração com sistemas de tickets +- Roteamento inteligente de conversas + +**Notificações Transacionais** +- Confirmações de pedidos +- Alertas de pagamento +- Atualizações de status +- Lembretes automáticos + +**Marketing e Campanhas** +- Envio de mensagens em massa +- Segmentação de públicos +- Tracking de engajamento + +**Integração com CRM** +- Canal WhatsApp no CRM +- Histórico unificado +- Automação de fluxos + +**Comunicação Corporativa** +- Notificações internas +- Alertas de sistemas +- Integração com ERPs + +## Stack Tecnológico + +- **Linguagem**: Go 1.24+ +- **Framework Web**: Gin +- **Protocolo WhatsApp**: whatsmeow +- **ORM**: GORM +- **Banco de Dados**: PostgreSQL / SQLite +- **Filas**: RabbitMQ (AMQP), NATS +- **Storage**: MinIO (S3-compatible) +- **Documentação**: Swagger/OpenAPI +- **Containers**: Docker multi-stage builds + +## Endpoints Disponíveis + +### Instâncias +- Criar, conectar e gerenciar instâncias +- QR Code para autenticação +- Status e informações de conexão +- Configuração de proxy + +### Mensagens +- Envio de texto, mídia, localização +- Botões, listas e enquetes +- Reações e respostas +- Histórico de conversas + +### Usuários +- Gerenciamento de perfil +- Contatos e privacidade +- Bloqueios e configurações + +### Grupos +- Criação e administração +- Gerenciamento de participantes +- Configurações e permissões + +### Chats +- Pin, mute, archive +- Marcação de leitura +- Busca e filtros + +### Outros +- Labels (etiquetas) +- Chamadas +- Comunidades +- Newsletters/Canais + +## Segurança e Privacidade + +- Criptografia end-to-end mantida (protocolo WhatsApp) +- Autenticação via API Key +- Suporte a HTTPS +- Logs de auditoria +- Secrets management +- Isolamento de instâncias + +## Telemetria + +O sistema coleta métricas anônimas para melhorias: +- Rotas mais utilizadas +- Versão da API em uso +- Estatísticas de performance + +**Não são coletados**: mensagens, números de telefone, nomes ou dados pessoais. + +## Primeiros Passos + +### Requisitos + +- Go 1.24+ (instalação local) ou Docker 20.10+ +- PostgreSQL 12+ ou SQLite +- Chave de API para autenticação + +### Instalação Rápida + +```bash +# Clonar repositório +git clone https://git.evoai.app/Evolution/evolution-go.git +cd evolution-go + +# Configurar ambiente +cp .env.example .env + +# Executar com Docker +docker-compose up -d + +# Ou executar localmente +make dev +``` + +O servidor estará disponível em `http://localhost:4000` com documentação Swagger em `/swagger/index.html`. + +## Diferencial + +| Aspecto | Evolution GO | WhatsApp Business API | +|---------|--------------|----------------------| +| Licença | Apache 2.0 | Proprietária | +| Custo | Gratuito | Pago por mensagem | +| Aprovação | Não requer | Requer aprovação Meta | +| Setup | Minutos | Semanas/meses | +| Multi-instância | Ilimitado | Limitado por contrato | +| Flexibilidade | Total | Limitada por políticas | +| Recursos | Completo | Subconjunto aprovado | + +## Documentação + +- **[Instalação](./installation.md)** - Guia completo de instalação +- **[Configuração](./configuration.md)** - Variáveis de ambiente +- **[Início Rápido](./quickstart.md)** - Primeiro uso prático +- **[API Overview](../guias-api/api-overview.md)** - Estrutura da API +- **[Arquitetura](../conceitos-core/architecture.md)** - Design do sistema + +## Suporte + +- **Grupo WhatsApp**: [evolution-api.com/whatsapp](https://evolution-api.com/whatsapp) +- **Discord**: [evolution-api.com/discord](https://evolution-api.com/discord) +- **GitHub Issues**: [github.com/EvolutionAPI/evolution-go](https://github.com/EvolutionAPI/evolution-go/issues) +- **Documentação**: [doc.evolution-api.com](https://doc.evolution-api.com) + +## Licença + +Apache License 2.0 com condições adicionais: + +1. Logo e informações de copyright não podem ser removidas das interfaces +2. Uso do Evolution GO deve ser notificado/creditado no sistema que o utiliza + +Detalhes completos: [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) + +--- + +**Versão**: 1.0.0 +**Mantido por**: Equipe Evolution API diff --git a/docs/wiki/fundamentos/quickstart.md b/docs/wiki/fundamentos/quickstart.md new file mode 100644 index 0000000..1950ae3 --- /dev/null +++ b/docs/wiki/fundamentos/quickstart.md @@ -0,0 +1,336 @@ +# Início Rápido + +Tutorial prático para configurar sua primeira instância WhatsApp e enviar mensagens via Evolution GO. + +## Pré-requisitos + +- Evolution GO instalado e em execução +- Chave de API configurada (GLOBAL_API_KEY) +- Smartphone com WhatsApp ativo + +Se ainda não instalou, consulte o [Guia de Instalação](./installation.md). + +--- + +## 1. Verificar API + +Confirme que o servidor está respondendo: + +```bash +curl http://localhost:4000/server/ok +``` + +**Resposta esperada:** +```json +{ + "status": "ok" +} +``` + +--- + +## 2. Criar Instância + +Uma instância representa uma conexão única do WhatsApp. Crie sua primeira: + +```bash +curl -X POST http://localhost:4000/instance/create \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-GLOBAL-API-KEY" \ + -d '{ + "name": "minha-instancia", + "token": "token-secreto-da-instancia" + }' +``` + +> **Importante:** +> - `apikey` header: Use a `GLOBAL_API_KEY` configurada no servidor +> - `token`: Crie um token único para esta instância (será usado para autenticar requisições desta instância) +> - `name`: Nome identificador da instância + +**Resposta:** +```json +{ + "message": "success", + "data": { + "instanceId": "uuid-gerado", + "name": "minha-instancia", + "token": "token-secreto-da-instancia", + "status": "created" + } +} +``` + +A instância foi criada mas ainda não está autenticada no WhatsApp. + +--- + +## 3. Autenticar via QR Code + +### Iniciar Conexão + +```bash +curl -X POST http://localhost:4000/instance/connect \ + -H "Content-Type: application/json" \ + -H "apikey: token-secreto-da-instancia" +``` + +> **Nota:** Agora use o `token` da instância no header `apikey` (não mais a GLOBAL_API_KEY). + +### Obter QR Code + +**Via navegador:** +``` +http://localhost:4000/instance/qr +``` +(com o header `apikey: token-secreto-da-instancia`) + +**Via API:** +```bash +curl "http://localhost:4000/instance/qr" \ + -H "apikey: token-secreto-da-instancia" +``` + +### Escanear no WhatsApp + +1. Abra o WhatsApp no smartphone +2. Acesse **Mais opções (⋮)** → **Aparelhos conectados** +3. Toque em **Conectar um aparelho** +4. Escaneie o QR Code exibido + +A conexão deve ser estabelecida em aproximadamente 10 segundos. + +--- + +## 4. Verificar Status + +Confirme que a instância está conectada: + +```bash +curl "http://localhost:4000/instance/status" \ + -H "apikey: token-secreto-da-instancia" +``` + +**Resposta quando conectado:** +```json +{ + "message": "success", + "data": { + "instanceId": "uuid-da-instancia", + "name": "minha-instancia", + "status": "open", + "profilePictureUrl": "https://...", + "profileName": "Nome do Perfil" + } +} +``` + +**Status possíveis:** +- `created` - Instância criada, aguardando autenticação +- `connecting` - Processo de conexão em andamento +- `open` - Conectado e operacional +- `close` - Desconectado + +--- + +## 5. Enviar Mensagem + +### Mensagem de Texto + +```bash +curl -X POST http://localhost:4000/send/text \ + -H "Content-Type: application/json" \ + -H "apikey: token-secreto-da-instancia" \ + -d '{ + "number": "5511999999999", + "text": "Mensagem de teste via Evolution GO" + }' +``` + +> **Nota:** A instância é identificada pelo token no header `apikey`. Não é necessário enviar `instanceName` no body. + +**Formato do número:** +- DDI + DDD + Número (apenas dígitos) +- Exemplo Brasil: `5511999999999` (55=Brasil, 11=São Paulo) + +**Resposta:** +```json +{ + "message": "success", + "data": { + "messageId": "3EB0...", + "status": "sent" + } +} +``` + +### Mensagem com Mídia + +```bash +curl -X POST http://localhost:4000/send/media \ + -H "Content-Type: application/json" \ + -H "apikey: token-secreto-da-instancia" \ + -d '{ + "number": "5511999999999", + "mediaUrl": "https://exemplo.com/imagem.jpg", + "caption": "Legenda da imagem" + }' +``` + +### Mensagem com Documento + +```bash +curl -X POST http://localhost:4000/send/media \ + -H "Content-Type: application/json" \ + -H "apikey: token-secreto-da-instancia" \ + -d '{ + "number": "5511999999999", + "mediaUrl": "https://exemplo.com/documento.pdf", + "fileName": "relatorio.pdf" + }' +``` + +--- + +## Operações de Gerenciamento + +### Listar Instâncias + +```bash +curl "http://localhost:4000/instance/all" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +> **Nota:** Use a `GLOBAL_API_KEY` para listar todas as instâncias. + +### Detalhes da Instância + +```bash +curl "http://localhost:4000/instance/info/uuid-da-instancia" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +> **Nota:** Use o `instanceId` (UUID) da instância na URL. + +### Desconectar + +```bash +curl -X POST http://localhost:4000/instance/disconnect \ + -H "Content-Type: application/json" \ + -H "apikey: token-secreto-da-instancia" +``` + +### Reconectar (novo QR Code) + +```bash +curl -X POST http://localhost:4000/instance/reconnect \ + -H "Content-Type: application/json" \ + -H "apikey: token-secreto-da-instancia" +``` + +### Deletar + +```bash +curl -X DELETE "http://localhost:4000/instance/delete/uuid-da-instancia" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +> **Nota:** Use a `GLOBAL_API_KEY` e o `instanceId` (UUID) para deletar. + +--- + +## Documentação Interativa (Swagger) + +Acesse a interface Swagger para explorar e testar todos os endpoints: + +``` +http://localhost:4000/swagger/index.html +``` + +**Passos:** +1. Clique em **Authorize** no topo da página +2. Insira sua chave de API +3. Confirme a autenticação +4. Explore e teste os endpoints disponíveis + +--- + +## Resolução de Problemas + +### QR Code Expira + +QR Code possui validade limitada (~60 segundos). Se expirar: + +```bash +curl -X POST http://localhost:4000/instance/reconnect \ + -H "Content-Type: application/json" \ + -H "apikey: token-secreto-da-instancia" +``` + +### Instância Não Encontrada + +Verifique se está usando o token correto: + +```bash +# Listar todas as instâncias +curl "http://localhost:4000/instance/all" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +### Mensagem Não Entregue + +**Verificações:** + +1. **Status da conexão:** +```bash +curl "http://localhost:4000/instance/status" \ + -H "apikey: token-secreto-da-instancia" +``` +Status deve ser `open`. + +2. **Formato do número:** + - Apenas dígitos (sem espaços, hífens ou símbolos) + - Incluir DDI e DDD + - Validar se o número existe no WhatsApp + +3. **Logs do servidor:** +```bash +docker-compose logs -f evolution-go +``` + +### Erro de Autenticação + +Verifique se está enviando o header correto: +```bash +-H "apikey: sua-chave-aqui" +``` + +Confirme a chave configurada no `docker-compose.yml` ou `.env`. + +--- + +## Próximos Passos + +### Documentação da API + +- **[API de Mensagens](../guias-api/api-messages.md)** - Todos os tipos de mensagens +- **[API de Grupos](../guias-api/api-groups.md)** - Gerenciamento de grupos +- **[API de Usuários](../guias-api/api-users.md)** - Perfis e contatos +- **[Referência Completa](../guias-api/api-overview.md)** - Todos os endpoints + +### Recursos Avançados + +- **[Sistema de Eventos](../recursos-avancados/events-system.md)** - Webhooks e filas +- **[Webhooks](../recursos-avancados/webhooks.md)** - Receber notificações +- **[RabbitMQ](../recursos-avancados/rabbitmq.md)** - Processamento assíncrono +- **[MinIO/S3](../recursos-avancados/minio.md)** - Armazenamento de mídia + +### Deploy e Segurança + +- **[Configuração](./configuration.md)** - Variáveis de ambiente +- **[Docker Deployment](../deploy-producao/docker-deployment.md)** - Deploy em produção +- **[Segurança](../deploy-producao/security.md)** - Boas práticas de segurança + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/guias-api/api-call.md b/docs/wiki/guias-api/api-call.md new file mode 100644 index 0000000..cc4fd97 --- /dev/null +++ b/docs/wiki/guias-api/api-call.md @@ -0,0 +1,223 @@ +# API de Chamadas + +Documentação do endpoint para gerenciar chamadas WhatsApp. + +## 📋 Índice + +- [Rejeitar Chamada](#rejeitar-chamada) + +--- + +## Rejeitar Chamada + +Rejeita uma chamada recebida no WhatsApp. + +**Endpoint**: `POST /call/reject` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "callCreator": "5511999999999@s.whatsapp.net", + "callId": "ABC123XYZ" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `callCreator` | string (JID) | ✅ Sim | JID de quem está ligando | +| `callId` | string | ✅ Sim | ID da chamada | + +**Nota**: Os dados da chamada (`callCreator` e `callId`) são recebidos via webhook quando uma chamada chega. Você deve capturar esses dados do evento `call` para usar este endpoint. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Resposta de Erro (400)**: +```json +{ + "error": "invalid request body" +} +``` + +**Resposta de Erro (500)**: +```json +{ + "error": "instance not found" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/call/reject \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "callCreator": "5511999999999@s.whatsapp.net", + "callId": "ABC123XYZ" + }' +``` + +--- + +## Fluxo Completo de Rejeição Automática + +### 1. Receber Evento de Chamada via Webhook + +Quando alguém liga para sua instância, você recebe um webhook: + +```json +{ + "event": "call", + "instance": "minha-instancia", + "data": { + "id": "ABC123XYZ", + "from": "5511999999999@s.whatsapp.net", + "timestamp": "2025-11-11T10:30:00Z", + "isVideo": false, + "isGroup": false + } +} +``` + +### 2. Rejeitar Automaticamente + +No seu servidor que recebe webhooks, quando chegar um evento de chamada: +1. Capture o `id` e o `from` do evento +2. Faça uma requisição POST para `/call/reject` +3. Use os dados capturados como `callId` e `callCreator` + +Dessa forma, chamadas são rejeitadas automaticamente assim que chegam. + +### 3. Rejeição Seletiva + +Para rejeitar apenas chamadas de números não autorizados: +1. Mantenha uma lista de números permitidos +2. Ao receber evento de chamada, verifique se o número está na lista +3. Se não estiver, rejeite a chamada usando o endpoint `/call/reject` +4. Se estiver autorizado, não faça nada (deixe tocar) + +--- + +## Casos de Uso + +### 1. Rejeitar Todas as Chamadas + +Útil para contas de atendimento que só respondem via mensagens: +1. Configure seu webhook para receber eventos de chamada +2. Quando receber evento `call`, rejeite imediatamente +3. Envie uma mensagem de texto explicando que não atende chamadas + +### 2. Horário Comercial + +Rejeitar chamadas fora do horário de trabalho: +1. Ao receber evento de chamada, verifique o horário atual +2. Se estiver fora do horário comercial (ex: Segunda a Sexta, 9h-18h), rejeite +3. Envie mensagem informando o horário de atendimento + +### 3. Rejeitar Chamadas de Vídeo + +Aceitar apenas chamadas de áudio: +1. Verifique o campo `isVideo` no evento de chamada +2. Se for `true`, rejeite a chamada +3. Envie mensagem pedindo para ligar com chamada de voz + +--- + +## Limitações e Observações + +### Limitações do WhatsApp + +1. **Não é possível aceitar chamadas via API**: A API do WhatsApp Multi-Device não permite aceitar chamadas programaticamente. Você só pode rejeitá-las. + +2. **Chamadas em grupos**: Chamadas em grupos também disparam o evento, mas o campo `isGroup` será `true`. + +3. **Timing**: A rejeição deve ser feita rapidamente. Se demorar muito, a chamada pode cair antes da rejeição. + +### Boas Práticas + +1. **Sempre responda ao webhook rapidamente**: Rejeite a chamada em menos de 2 segundos para evitar timeout. + +2. **Envie mensagem explicativa**: Após rejeitar, informe o usuário o motivo via mensagem de texto. + +3. **Log de chamadas rejeitadas**: Mantenha registro para análise, salvando data/hora, número, ID da chamada e motivo da rejeição. + +4. **Tratamento de erros**: Sempre trate possíveis erros na rejeição para evitar que seu webhook trave ao falhar em rejeitar uma chamada. + +--- + +## Códigos de Erro Comuns + +| Código | Erro | Solução | +|--------|------|---------| +| 400 | `invalid request body` | Verifique formato do JSON | +| 500 | `instance not found` | Instância não conectada | +| 500 | `error reject call` | Chamada não existe ou já expirou | + +--- + +## Estrutura do Evento de Chamada + +Quando você recebe um webhook de chamada, a estrutura é: + +```json +{ + "event": "call", + "instance": "minha-instancia", + "data": { + "id": "ABC123XYZ", + "from": "5511999999999@s.whatsapp.net", + "timestamp": "2025-11-11T10:30:00Z", + "isVideo": false, + "isGroup": false, + "status": "ringing" + } +} +``` + +**Campos**: +- `id`: ID único da chamada (use como `callId`) +- `from`: JID de quem está ligando (use como `callCreator`) +- `timestamp`: Quando a chamada foi iniciada +- `isVideo`: Se é chamada de vídeo (true) ou áudio (false) +- `isGroup`: Se é chamada em grupo +- `status`: Status da chamada (ringing, timeout, reject) + +--- + +## Configuração de Webhooks + +Para receber eventos de chamada, configure o webhook: + +```env +WEBHOOK_URL=https://seu-servidor.com/webhook +``` + +Certifique-se de que seu servidor: +1. Aceita requisições POST +2. Responde rapidamente (< 5 segundos) +3. Retorna status 200 para confirmar recebimento + +--- + +## Próximos Passos + +- [Sistema de Eventos](../recursos-avancados/events-system.md) - Configurar webhooks +- [API de Mensagens](./api-messages.md) - Enviar mensagem após rejeitar +- [API de Usuários](./api-user.md) - Gerenciar contatos +- [Visão Geral da API](./api-overview.md) + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/guias-api/api-chats.md b/docs/wiki/guias-api/api-chats.md new file mode 100644 index 0000000..ec672fa --- /dev/null +++ b/docs/wiki/guias-api/api-chats.md @@ -0,0 +1,467 @@ +# API de Chats + +Documentação completa dos endpoints para gerenciar conversas (pin, arquivo, mute). + +## 📋 Índice + +- [Fixar Conversa](#fixar-conversa) +- [Desfixar Conversa](#desfixar-conversa) +- [Arquivar Conversa](#arquivar-conversa) +- [Desarquivar Conversa](#desarquivar-conversa) +- [Silenciar Conversa](#silenciar-conversa) +- [Dessilenciar Conversa](#dessilenciar-conversa) +- [Sincronizar Histórico](#sincronizar-histórico) + +--- + +## Fixar Conversa + +Fixa uma conversa no topo da lista de chats. + +**Endpoint**: `POST /chat/pin` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "chat": "5511999999999@s.whatsapp.net" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `chat` | string | ✅ Sim | JID do chat (individual ou grupo) | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +# Fixar chat individual +curl -X POST http://localhost:4000/chat/pin \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "5511999999999@s.whatsapp.net" + }' + +# Fixar grupo +curl -X POST http://localhost:4000/chat/pin \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "120363XXXXXXXXXX@g.us" + }' +``` + +--- + +## Desfixar Conversa + +Remove a fixação de uma conversa. + +**Endpoint**: `POST /chat/unpin` + +**Body**: +```json +{ + "chat": "5511999999999@s.whatsapp.net" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `chat` | string | ✅ Sim | JID do chat | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/chat/unpin \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "5511999999999@s.whatsapp.net" + }' +``` + +--- + +## Arquivar Conversa + +Move uma conversa para o arquivo. + +**Endpoint**: `POST /chat/archive` + +**Body**: +```json +{ + "chat": "5511999999999@s.whatsapp.net" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `chat` | string | ✅ Sim | JID do chat | + +**Nota**: Conversas arquivadas não aparecem na lista principal, mas ainda recebem mensagens. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/chat/archive \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "5511999999999@s.whatsapp.net" + }' +``` + +--- + +## Desarquivar Conversa + +Restaura uma conversa arquivada para a lista principal. + +**Endpoint**: `POST /chat/unarchive` + +**Body**: +```json +{ + "chat": "5511999999999@s.whatsapp.net" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `chat` | string | ✅ Sim | JID do chat | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/chat/unarchive \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "5511999999999@s.whatsapp.net" + }' +``` + +--- + +## Silenciar Conversa + +Silencia notificações de uma conversa por 1 hora. + +**Endpoint**: `POST /chat/mute` + +**Body**: +```json +{ + "chat": "5511999999999@s.whatsapp.net" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `chat` | string | ✅ Sim | JID do chat | + +**Nota**: O silenciamento é fixo por **1 hora** (hard-coded no código: `1*time.Hour`). Para silenciar permanentemente, use o aplicativo WhatsApp. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/chat/mute \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "5511999999999@s.whatsapp.net" + }' +``` + +--- + +## Dessilenciar Conversa + +Remove o silenciamento de uma conversa. + +**Endpoint**: `POST /chat/unmute` + +**Body**: +```json +{ + "chat": "5511999999999@s.whatsapp.net" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `chat` | string | ✅ Sim | JID do chat | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/chat/unmute \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "5511999999999@s.whatsapp.net" + }' +``` + +--- + +## Sincronizar Histórico + +Solicita sincronização de histórico de mensagens antigas (WhatsApp Multi-Device). + +**Endpoint**: `POST /chat/history-sync` + +**Body**: +```json +{ + "messageInfo": { + "Chat": "5511999999999@s.whatsapp.net", + "IsFromMe": false, + "IsGroup": false, + "ID": "3EB0C5A277F7F9B6C599", + "Timestamp": "2025-11-11T10:00:00Z" + }, + "count": 50 +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `messageInfo` | object | ✅ Sim | Informações da mensagem de referência | +| `messageInfo.Chat` | string | ✅ Sim | JID do chat | +| `messageInfo.IsFromMe` | bool | ✅ Sim | Se a mensagem foi enviada por você | +| `messageInfo.IsGroup` | bool | ✅ Sim | Se é um grupo | +| `messageInfo.ID` | string | ✅ Sim | ID da mensagem de referência | +| `messageInfo.Timestamp` | string | ✅ Sim | Timestamp da mensagem | +| `count` | int | ✅ Sim | Número de mensagens para sincronizar | + +**Nota**: Este endpoint é usado para sincronizar mensagens antigas do histórico do WhatsApp Multi-Device. Requer uma mensagem de referência válida. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Timestamp": "2025-11-11T10:30:00Z", + "ID": "abc123", + "ServerID": 12345 + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/chat/history-sync \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "messageInfo": { + "Chat": "5511999999999@s.whatsapp.net", + "IsFromMe": false, + "IsGroup": false, + "ID": "3EB0C5A277F7F9B6C599", + "Timestamp": "2025-11-11T10:00:00Z" + }, + "count": 50 + }' +``` + +--- + +## Fluxos de Uso Comuns + +### Organizar Conversas Prioritárias + +```bash +# 1. Fixar conversas importantes +curl -X POST http://localhost:4000/chat/pin \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"chat": "5511999999999@s.whatsapp.net"}' + +# 2. Arquivar conversas antigas +curl -X POST http://localhost:4000/chat/archive \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"chat": "5511888888888@s.whatsapp.net"}' +``` + +### Gerenciar Notificações + +```bash +# Silenciar grupo temporariamente (1 hora) +curl -X POST http://localhost:4000/chat/mute \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"chat": "120363XXXXXXXXXX@g.us"}' + +# Reativar notificações +curl -X POST http://localhost:4000/chat/unmute \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"chat": "120363XXXXXXXXXX@g.us"}' +``` + +### Limpar Lista de Chats + +```bash +# Arquivar múltiplas conversas +CHATS=("5511111111111@s.whatsapp.net" "5511222222222@s.whatsapp.net" "5511333333333@s.whatsapp.net") + +for chat in "\${CHATS[@]}"; do + curl -X POST http://localhost:4000/chat/archive \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d "{"chat": "$chat"}" +done +``` + +--- + +## Códigos de Erro Comuns + +| Código | Erro | Solução | +|--------|------|---------| +| 400 | `chat is required` | Forneça o campo `chat` | +| 500 | `instance not found` | Instância não conectada | +| 500 | `invalid phone number` | JID inválido (formato incorreto) | + +--- + +## Boas Práticas + +### 1. Validar JID +Sempre use JIDs no formato correto: +- Chat individual: `5511999999999@s.whatsapp.net` +- Grupo: `120363XXXXXXXXXX@g.us` + +### 2. Gerenciar Estado +Mantenha controle do estado dos chats na sua aplicação: +- Registre quais chats estão fixados, arquivados e silenciados +- Lembre-se: um chat não pode estar fixado e arquivado ao mesmo tempo +- Ao fixar um chat, ele é automaticamente desarquivado pelo WhatsApp + +### 3. Silenciamento Temporário +Lembre-se que o mute dura apenas 1 hora. Para silenciamento permanente: +- Use o aplicativo WhatsApp nativo +- Ou implemente lógica para re-silenciar periodicamente + +### 4. Limite de Chats Fixados +O WhatsApp permite fixar até **3 chats** no topo. Não há validação na API, mas isso é uma limitação do WhatsApp. + +### 5. Sincronização de Histórico +Use com cuidado - sincronizar histórico consome recursos. Recomendações: +- Sincronize no máximo **100 mensagens** por vez +- Aguarde resposta antes de nova sincronização +- Use apenas quando necessário (nova instalação, restauração) + +--- + +## Diferenças de Comportamento + +### Fixar vs Arquivar +- **Fixar**: Mantém conversa no topo (máx 3) +- **Arquivar**: Remove da lista principal, mas mantém notificações + +### Mute vs Archive +- **Mute**: Silencia notificações, mas chat permanece visível +- **Archive**: Oculta chat, mas notificações continuam (a menos que também esteja mutado) + +### Para Combinar +```bash +# Arquivar E silenciar (para "esconder" completamente) +curl -X POST http://localhost:4000/chat/archive ... +curl -X POST http://localhost:4000/chat/mute ... + +# Fixar (automaticamente desarquiva) +curl -X POST http://localhost:4000/chat/pin ... +``` + +--- + +## Próximos Passos + +- [API de Labels](./api-labels.md) - Organizar chats com etiquetas +- [API de Mensagens](./api-messages.md) - Gerenciar mensagens +- [API de Grupos](./api-groups.md) - Gerenciar grupos +- [Visão Geral da API](./api-overview.md) + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/guias-api/api-community.md b/docs/wiki/guias-api/api-community.md new file mode 100644 index 0000000..4eb0a65 --- /dev/null +++ b/docs/wiki/guias-api/api-community.md @@ -0,0 +1,376 @@ +# API de Comunidades + +Documentação dos endpoints para gerenciar Comunidades WhatsApp. + +## 📋 Índice + +- [Criar Comunidade](#criar-comunidade) +- [Adicionar Grupos](#adicionar-grupos) +- [Remover Grupos](#remover-grupos) + +--- + +## O que são Comunidades? + +**Comunidades** são um recurso do WhatsApp que permite agrupar vários grupos relacionados sob uma única estrutura. É como um "grupo de grupos". + +**Características**: +- Uma comunidade pode conter **até 50 grupos** +- Cada comunidade tem um **canal de anúncios** (grupo pai) +- Membros da comunidade veem todos os grupos vinculados +- Facilita organização de organizações, escolas, condomínios, etc. + +--- + +## Criar Comunidade + +Cria uma nova comunidade WhatsApp. + +**Endpoint**: `POST /community/create` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "communityName": "Escola ABC" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `communityName` | string | ✅ Sim | Nome da comunidade | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "JID": "120363XXXXXXXXXX@g.us", + "OwnerJID": "5511999999999@s.whatsapp.net", + "GroupName": { + "Name": "Escola ABC", + "NameSetAt": "2025-11-11T10:30:00Z", + "NameSetBy": "5511999999999@s.whatsapp.net" + }, + "GroupCreated": "2025-11-11T10:30:00Z", + "GroupParent": { + "IsParent": true + } + } +} +``` + +**Campos da Resposta**: +- `JID`: ID único da comunidade (formato de grupo @g.us) +- `OwnerJID`: Criador da comunidade +- `GroupName`: Nome e metadados +- `GroupParent.IsParent`: true (indica que é uma comunidade) + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/community/create \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "communityName": "Condomínio Residencial" + }' +``` + +--- + +## Adicionar Grupos + +Adiciona (vincula) grupos existentes a uma comunidade. + +**Endpoint**: `POST /community/add` + +**Body**: +```json +{ + "communityJid": "120363XXXXXXXXXX@g.us", + "groupJid": [ + "120363YYYYYYYYYY@g.us", + "120363ZZZZZZZZZZ@g.us" + ] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `communityJid` | string | ✅ Sim | JID da comunidade | +| `groupJid` | array | ✅ Sim | Array de JIDs de grupos para adicionar | + +**Nota**: Os grupos devem **já existir** e você deve ser **admin** de ambos (comunidade e grupos). + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "success": [ + "120363YYYYYYYYYY@g.us", + "120363ZZZZZZZZZZ@g.us" + ], + "failed": [] + } +} +``` + +**Campos da Resposta**: +- `success`: Array de grupos adicionados com sucesso +- `failed`: Array de grupos que falharam (não existe, sem permissão, etc) + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/community/add \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "communityJid": "120363XXXXXXXXXX@g.us", + "groupJid": [ + "120363YYYYYYYYYY@g.us" + ] + }' +``` + +--- + +## Remover Grupos + +Remove (desvincula) grupos de uma comunidade. + +**Endpoint**: `POST /community/remove` + +**Body**: +```json +{ + "communityJid": "120363XXXXXXXXXX@g.us", + "groupJid": [ + "120363YYYYYYYYYY@g.us" + ] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `communityJid` | string | ✅ Sim | JID da comunidade | +| `groupJid` | array | ✅ Sim | Array de JIDs de grupos para remover | + +**Nota**: Remover um grupo da comunidade **não deleta o grupo**, apenas o desvincula. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "success": [ + "120363YYYYYYYYYY@g.us" + ], + "failed": [] + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/community/remove \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "communityJid": "120363XXXXXXXXXX@g.us", + "groupJid": [ + "120363YYYYYYYYYY@g.us" + ] + }' +``` + +--- + +## Fluxo Completo de Gerenciamento + +### 1. Criar Comunidade e Organizar Grupos + +**Fluxo completo**: + +1. **Criar a comunidade** usando `POST /community/create` +2. **Criar os grupos** que farão parte da comunidade usando `POST /group/create` +3. **Adicionar os grupos à comunidade** usando `POST /community/add` com os JIDs obtidos nos passos anteriores + +Exemplo: +- Primeiro, crie uma comunidade "Escola Municipal" e guarde o `JID` retornado +- Depois, crie dois grupos "1º Ano A" e "2º Ano B" e guarde os JIDs +- Por fim, adicione os grupos à comunidade usando os JIDs + +### 2. Reorganizar Comunidade + +Para reorganizar uma comunidade (remover grupos antigos e adicionar novos): + +1. Use `POST /community/remove` para remover grupos que não fazem mais parte +2. Use `POST /community/add` para adicionar novos grupos + +Exemplo: Se você precisa substituir o grupo "120363OLD1@g.us" por dois novos grupos, primeiro remova o antigo e depois adicione os novos usando os respectivos endpoints. + +--- + +## Casos de Uso + +### 1. Escola / Universidade + +``` +Comunidade: "Universidade XYZ" +├── Grupo: Administração +├── Grupo: Engenharia - 1º Ano +├── Grupo: Engenharia - 2º Ano +├── Grupo: Medicina - 1º Ano +└── Grupo: Eventos +``` + +### 2. Condomínio + +``` +Comunidade: "Condomínio Residencial" +├── Grupo: Síndico e Zeladores +├── Grupo: Bloco A +├── Grupo: Bloco B +├── Grupo: Churrasqueira (Reservas) +└── Grupo: Comunicados Gerais +``` + +### 3. Empresa + +``` +Comunidade: "Empresa LTDA" +├── Grupo: Diretoria +├── Grupo: TI +├── Grupo: Vendas +├── Grupo: Marketing +└── Grupo: RH +``` + +### 4. Igreja / Instituição Religiosa + +``` +Comunidade: "Igreja Central" +├── Grupo: Liderança +├── Grupo: Jovens +├── Grupo: Mulheres +├── Grupo: Eventos +└── Grupo: Voluntários +``` + +--- + +## Permissões e Limitações + +### Permissões Necessárias + +Para gerenciar comunidades, você precisa ser: +1. **Criador** da comunidade (para adicionar/remover grupos) +2. **Admin** dos grupos que deseja vincular + +### Limitações do WhatsApp + +| Limitação | Valor | +|-----------|-------| +| Máximo de grupos por comunidade | 50 | +| Máximo de participantes por grupo | 1024 | +| Máximo de admins por grupo | Ilimitado | + +### Comportamento + +- **Desvincular grupo**: Não deleta o grupo, apenas remove da comunidade +- **Deletar comunidade**: Não deleta os grupos vinculados +- **Sair da comunidade**: Você sai de todos os grupos vinculados + +--- + +## Códigos de Erro Comuns + +| Código | Erro | Solução | +|--------|------|---------| +| 400 | `community name is required` | Forneça o nome da comunidade | +| 400 | `community jid is required` | Forneça o JID da comunidade | +| 400 | `group jid is required` | Forneça array de JIDs de grupos | +| 500 | `instance not found` | Instância não conectada | +| 500 | `error parse community jid` | JID inválido | +| 500 | `error link group` | Sem permissão ou grupo não existe | + +--- + +## Boas Práticas + +### 1. Planeje a Estrutura + +Antes de criar, defina a organização: +``` +Comunidade (Tema geral) +├── Grupo 1 (Categoria específica) +├── Grupo 2 (Categoria específica) +└── Grupo 3 (Categoria específica) +``` + +### 2. Nomeação Clara + +Use nomes descritivos: +- ✅ "Escola ABC - 1º Ano A" +- ✅ "Condomínio XYZ - Bloco A" +- ❌ "Grupo 1" +- ❌ "ABC" + +### 3. Canal de Anúncios + +A comunidade em si funciona como canal de anúncios para todos os grupos. Use-a para: +- Comunicados gerais +- Eventos importantes +- Informações que afetam todos + +### 4. Organize por Hierarquia + +``` +Comunidade (Nível mais alto) +└── Grupos (Nível específico) + └── Participantes (Nível individual) +``` + +### 5. Limite de Grupos + +Não exceda 50 grupos por comunidade. Se precisar de mais: +- Crie múltiplas comunidades +- Reorganize grupos por temas +- Arquive grupos inativos + +--- + +## Diferenças: Comunidade vs Grupo + +| Aspecto | Comunidade | Grupo | +|---------|------------|-------| +| Função | Agrupar grupos relacionados | Conversação direta | +| Limite de membros | 50 grupos × 1024 = 51.200 | 1024 | +| Estrutura | Hierárquica (pais) | Plana (participantes) | +| Mensagens | Canal de anúncios | Conversa completa | +| Admin | Admin da comunidade | Admin do grupo | + +--- + +## Próximos Passos + +- [API de Grupos](./api-groups.md) - Criar e gerenciar grupos +- [API de Mensagens](./api-messages.md) - Enviar anúncios +- [API de Usuários](./api-user.md) - Gerenciar contatos +- [Visão Geral da API](./api-overview.md) + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/guias-api/api-groups.md b/docs/wiki/guias-api/api-groups.md new file mode 100644 index 0000000..de41ed7 --- /dev/null +++ b/docs/wiki/guias-api/api-groups.md @@ -0,0 +1,808 @@ +# API de Grupos + +Documentação completa dos endpoints para gerenciar grupos WhatsApp. + +## 📋 Índice + +- [Listar Grupos](#listar-grupos) +- [Informações do Grupo](#informações-do-grupo) +- [Link de Convite](#link-de-convite) +- [Criar Grupo](#criar-grupo) +- [Gerenciar Participantes](#gerenciar-participantes) +- [Configurações do Grupo](#configurações-do-grupo) + - [Alterar Foto](#alterar-foto) + - [Alterar Nome](#alterar-nome) + - [Alterar Descrição](#alterar-descrição) +- [Meus Grupos (Admin)](#meus-grupos-admin) +- [Entrar via Link](#entrar-via-link) +- [Sair do Grupo](#sair-do-grupo) + +--- + +## Listar Grupos + +Lista todos os grupos que você participa. + +**Endpoint**: `GET /group/list` + +**Headers**: +``` +apikey: SUA-CHAVE-API +``` + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": [ + { + "JID": "120363XXXXXXXXXX@g.us", + "OwnerJID": "5511999999999@s.whatsapp.net", + "GroupName": { + "Name": "Equipe de Vendas", + "NameSetAt": "2025-01-15T10:30:00Z", + "NameSetBy": "5511999999999@s.whatsapp.net" + }, + "GroupTopic": { + "Topic": "Discussões sobre vendas e metas", + "TopicID": "abc123", + "TopicSetAt": "2025-01-15T10:35:00Z", + "TopicSetBy": "5511999999999@s.whatsapp.net" + }, + "GroupCreated": "2025-01-15T10:00:00Z", + "Participants": [ + { + "JID": "5511999999999@s.whatsapp.net", + "IsAdmin": true, + "IsSuperAdmin": true + }, + { + "JID": "5511888888888@s.whatsapp.net", + "IsAdmin": false, + "IsSuperAdmin": false + } + ], + "ParticipantVersionID": "abc123" + } + ] +} +``` + +**Campos da Resposta**: +- `JID`: ID único do grupo (sempre termina com @g.us) +- `OwnerJID`: Criador do grupo +- `GroupName`: Nome e metadados +- `GroupTopic`: Descrição do grupo +- `Participants`: Lista de participantes com permissões + +**Exemplo cURL**: +```bash +curl -X GET http://localhost:4000/group/list \ + -H "apikey: SUA-CHAVE-API" +``` + +--- + +## Informações do Grupo + +Obtém informações detalhadas de um grupo específico. + +**Endpoint**: `POST /group/info` + +**Body**: +```json +{ + "groupJid": "120363XXXXXXXXXX@g.us" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupJid` | string | ✅ Sim | JID do grupo | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "JID": "120363XXXXXXXXXX@g.us", + "OwnerJID": "5511999999999@s.whatsapp.net", + "GroupName": { + "Name": "Equipe de Vendas", + "NameSetAt": "2025-01-15T10:30:00Z", + "NameSetBy": "5511999999999@s.whatsapp.net" + }, + "GroupTopic": { + "Topic": "Discussões sobre vendas", + "TopicID": "abc123", + "TopicSetAt": "2025-01-15T10:35:00Z", + "TopicSetBy": "5511999999999@s.whatsapp.net" + }, + "GroupCreated": "2025-01-15T10:00:00Z", + "Participants": [ + { + "JID": "5511999999999@s.whatsapp.net", + "IsAdmin": true, + "IsSuperAdmin": true + } + ] + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/group/info \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us" + }' +``` + +--- + +## Link de Convite + +Obtém ou regenera o link de convite do grupo. + +**Endpoint**: `POST /group/invitelink` + +**Body**: +```json +{ + "groupJid": "120363XXXXXXXXXX@g.us", + "reset": false +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupJid` | string | ✅ Sim | JID do grupo | +| `reset` | bool | ❌ Não | Se true, gera um novo link (invalida o anterior) | + +**Nota**: Apenas admins podem obter/resetar links de convite. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP" +} +``` + +**Exemplo cURL**: +```bash +# Obter link existente +curl -X POST http://localhost:4000/group/invitelink \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "reset": false + }' + +# Gerar novo link +curl -X POST http://localhost:4000/group/invitelink \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "reset": true + }' +``` + +--- + +## Criar Grupo + +Cria um novo grupo WhatsApp. + +**Endpoint**: `POST /group/create` + +**Body**: +```json +{ + "groupName": "Equipe de Vendas", + "participants": [ + "5511999999999", + "5511888888888", + "5511777777777" + ] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupName` | string | ✅ Sim | Nome do grupo | +| `participants` | array | ✅ Sim | Array de números dos participantes (mínimo 1) | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "jid": "120363XXXXXXXXXX@g.us", + "name": "Equipe de Vendas", + "owner": "5511999999999@s.whatsapp.net", + "added": [ + "5511999999999@s.whatsapp.net", + "5511888888888@s.whatsapp.net" + ], + "failed": [ + "5511777777777@s.whatsapp.net" + ] + } +} +``` + +**Campos da Resposta**: +- `jid`: ID do grupo criado +- `name`: Nome do grupo +- `owner`: Criador (você) +- `added`: Participantes adicionados com sucesso +- `failed`: Participantes que falharam (número inválido, bloqueado, etc) + +**Nota**: É normal que alguns participantes falhem (números inexistentes, bloqueados, etc). + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/group/create \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupName": "Meu Grupo", + "participants": ["5511999999999", "5511888888888"] + }' +``` + +--- + +## Gerenciar Participantes + +Adiciona, remove ou promove participantes do grupo. + +**Endpoint**: `POST /group/participant` + +**Body**: +```json +{ + "groupJid": "120363XXXXXXXXXX@g.us", + "action": "add", + "participants": ["5511999999999", "5511888888888"] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupJid` | string | ✅ Sim | JID do grupo | +| `action` | string | ✅ Sim | Ação a executar | +| `participants` | array | ✅ Sim | Array de números | + +**Ações Disponíveis**: + +| Action | Descrição | Requer Admin | +|--------|-----------|--------------| +| `add` | Adicionar participantes | ✅ Sim | +| `remove` | Remover participantes | ✅ Sim | +| `promote` | Promover a admin | ✅ Sim | +| `demote` | Remover admin | ✅ Sim | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Resposta de Erro (500)**: +```json +{ + "error": "error create group: 403 forbidden" +} +``` + +**Exemplos cURL**: + +```bash +# Adicionar participantes +curl -X POST http://localhost:4000/group/participant \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "action": "add", + "participants": ["5511999999999"] + }' + +# Remover participantes +curl -X POST http://localhost:4000/group/participant \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "action": "remove", + "participants": ["5511888888888"] + }' + +# Promover a admin +curl -X POST http://localhost:4000/group/participant \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "action": "promote", + "participants": ["5511999999999"] + }' + +# Remover admin (rebaixar) +curl -X POST http://localhost:4000/group/participant \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "action": "demote", + "participants": ["5511999999999"] + }' +``` + +--- + +## Configurações do Grupo + +### Alterar Foto + +Define a foto do grupo. + +**Endpoint**: `POST /group/photo` + +**Body**: +```json +{ + "groupJid": "120363XXXXXXXXXX@g.us", + "image": "https://exemplo.com/logo.jpg" +} +``` + +Ou com base64: + +```json +{ + "groupJid": "120363XXXXXXXXXX@g.us", + "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg..." +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupJid` | string | ✅ Sim | JID do grupo | +| `image` | string | ✅ Sim | URL ou base64 da imagem | + +**Formatos Aceitos**: +- URL (http:// ou https://) +- Base64 (data:image/jpeg;base64,... ou data:image/png;base64,...) + +**Nota**: Apenas admins podem alterar a foto. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": "abc123" +} +``` + +O campo `data` contém o ID da nova foto. + +**Exemplo cURL**: +```bash +# Com URL +curl -X POST http://localhost:4000/group/photo \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "image": "https://exemplo.com/logo.jpg" + }' + +# Com base64 +curl -X POST http://localhost:4000/group/photo \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg..." + }' +``` + +--- + +### Alterar Nome + +Altera o nome do grupo. + +**Endpoint**: `POST /group/name` + +**Body**: +```json +{ + "groupJid": "120363XXXXXXXXXX@g.us", + "name": "Novo Nome do Grupo" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupJid` | string | ✅ Sim | JID do grupo | +| `name` | string | ✅ Sim | Novo nome (máx 25 caracteres) | + +**Nota**: Apenas admins podem alterar o nome. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/group/name \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "name": "Equipe Marketing 2025" + }' +``` + +--- + +### Alterar Descrição + +Altera a descrição do grupo. + +**Endpoint**: `POST /group/description` + +**Body**: +```json +{ + "groupJid": "120363XXXXXXXXXX@g.us", + "description": "Grupo para discussões sobre marketing e estratégias de vendas." +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupJid` | string | ✅ Sim | JID do grupo | +| `description` | string | ✅ Sim | Nova descrição (máx 512 caracteres) | + +**Nota**: Apenas admins podem alterar a descrição. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/group/description \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "description": "Grupo oficial da empresa - Apenas assuntos profissionais" + }' +``` + +--- + +## Meus Grupos (Admin) + +Lista apenas os grupos onde você é o **proprietário/criador**. + +**Endpoint**: `GET /group/myall` + +**Headers**: +``` +apikey: SUA-CHAVE-API +``` + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": [ + { + "JID": "120363XXXXXXXXXX@g.us", + "OwnerJID": "5511999999999@s.whatsapp.net", + "GroupName": { + "Name": "Meu Grupo", + "NameSetAt": "2025-01-15T10:30:00Z", + "NameSetBy": "5511999999999@s.whatsapp.net" + }, + "Participants": [...] + } + ] +} +``` + +**Diferença**: +- `/group/list` - Todos os grupos que você participa +- `/group/myall` - Apenas grupos que você criou (owner) + +**Exemplo cURL**: +```bash +curl -X GET http://localhost:4000/group/myall \ + -H "apikey: SUA-CHAVE-API" +``` + +--- + +## Entrar via Link + +Entra em um grupo através de um link de convite. + +**Endpoint**: `POST /group/join` + +**Body**: +```json +{ + "code": "ABCDEFGHIJKLMNOP" +} +``` + +Ou com URL completa: + +```json +{ + "code": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `code` | string | ✅ Sim | Código do link ou URL completa | + +**Nota**: O código é a parte após `https://chat.whatsapp.com/`. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Resposta de Erro (500)**: +```json +{ + "error": "error create group: 404 not found" +} +``` + +Erros comuns: +- `404 not found` - Link inválido ou expirado +- `403 forbidden` - Você foi banido ou removido +- `406 not acceptable` - Grupo cheio (256 participantes) + +**Exemplo cURL**: +```bash +# Com código +curl -X POST http://localhost:4000/group/join \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "code": "ABCDEFGHIJKLMNOP" + }' + +# Com URL completa +curl -X POST http://localhost:4000/group/join \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "code": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP" + }' +``` + +--- + +## Sair do Grupo + +Sai de um grupo WhatsApp. + +**Endpoint**: `POST /group/leave` + +**Body**: +```json +{ + "groupJid": "120363XXXXXXXXXX@g.us" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupJid` | string | ✅ Sim | JID do grupo | + +**Nota**: Se você for o único admin, o grupo ficará sem admins até que outro seja promovido ou o grupo seja excluído. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/group/leave \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us" + }' +``` + +--- + +## Fluxo Completo de Gerenciamento + +### 1. Criar e Configurar Grupo + +```bash +# 1. Criar grupo +GROUP_JID=$(curl -X POST http://localhost:4000/group/create \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupName": "Meu Grupo", + "participants": ["5511999999999"] + }' | jq -r '.data.jid') + +# 2. Adicionar foto +curl -X POST http://localhost:4000/group/photo \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d "{ + "groupJid": "$GROUP_JID", + "image": "https://exemplo.com/logo.jpg" + }" + +# 3. Adicionar descrição +curl -X POST http://localhost:4000/group/description \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d "{ + "groupJid": "$GROUP_JID", + "description": "Grupo oficial da empresa" + }" + +# 4. Obter link de convite +curl -X POST http://localhost:4000/group/invitelink \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d "{ + "groupJid": "$GROUP_JID", + "reset": false + }" +``` + +### 2. Gerenciar Participantes + +```bash +# Adicionar novos membros +curl -X POST http://localhost:4000/group/participant \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "action": "add", + "participants": ["5511888888888", "5511777777777"] + }' + +# Promover a admin +curl -X POST http://localhost:4000/group/participant \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "action": "promote", + "participants": ["5511888888888"] + }' +``` + +--- + +## Códigos de Erro Comuns + +| Código | Erro | Solução | +|--------|------|---------| +| 400 | `groupJid is required` | Forneça o JID do grupo | +| 400 | `groupName is required` | Forneça o nome do grupo | +| 400 | `participants are required` | Forneça array de participantes | +| 400 | `action is required` | Especifique a ação (add/remove/promote/demote) | +| 500 | `invalid group jid` | JID de grupo inválido (deve terminar com @g.us) | +| 500 | `403 forbidden` | Sem permissão (não é admin) | +| 500 | `404 not found` | Grupo não existe ou link inválido | + +--- + +## Boas Práticas + +### 1. Verificar Permissões +Sempre verifique se você é admin antes de tentar alterar configurações: +```bash +# 1. Obter info do grupo +INFO=$(curl -s -X POST http://localhost:4000/group/info \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"groupJid": "120363XXXXXXXXXX@g.us"}') + +# 2. Verificar se você é admin +echo $INFO | jq '.data.Participants[] | select(.IsAdmin == true)' +``` + +### 2. Validar Números +Valide números antes de adicionar ao grupo: +```bash +# 1. Verificar se número existe +curl -X POST http://localhost:4000/user/check \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"number": ["5511999999999"]}' + +# 2. Se IsInWhatsapp=true, adicionar ao grupo +curl -X POST http://localhost:4000/group/participant \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupJid": "120363XXXXXXXXXX@g.us", + "action": "add", + "participants": ["5511999999999"] + }' +``` + +### 3. Limites do WhatsApp +Respeite os limites do WhatsApp: +- **256 participantes** por grupo +- **25 caracteres** para nome do grupo +- **512 caracteres** para descrição +- Não adicione mais de **20 participantes de uma vez** + +### 4. Tratamento de Falhas +Ao criar grupo, sempre verifique o campo `failed` na resposta: +- O campo `added` contém os participantes adicionados com sucesso +- O campo `failed` contém os que falharam (número inválido, não tem WhatsApp, etc) +- Se houver falhas, você pode tentar adicionar novamente após verificação + +--- + +## Próximos Passos + +- [API de Mensagens](./api-messages.md) - Enviar mensagens em grupos +- [API de Usuários](./api-user.md) - Gerenciar contatos +- [API de Chats](./api-chats.md) - Gerenciar conversas +- [Visão Geral da API](./api-overview.md) + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/guias-api/api-instances.md b/docs/wiki/guias-api/api-instances.md new file mode 100644 index 0000000..946b15f --- /dev/null +++ b/docs/wiki/guias-api/api-instances.md @@ -0,0 +1,853 @@ +# API de Instâncias + +Documentação completa dos endpoints para gerenciar instâncias WhatsApp. + +## Visão Geral + +Uma **instância** representa uma conexão individual com o WhatsApp. Cada instância mantém sua própria sessão, autenticação e configurações independentes. + +**Importante**: A maioria das rotas identifica a instância automaticamente através do header `apikey` (token da instância). Apenas rotas administrativas usam `:instanceId` na URL e exigem a `GLOBAL_API_KEY` configurada no ambiente. + +## Endpoints Disponíveis + +### Gerenciamento Básico (Administrativo - usa GLOBAL_API_KEY) +- `POST /instance/create` - Criar nova instância +- `GET /instance/all` - Listar todas as instâncias +- `GET /instance/info/:instanceId` - Informações da instância +- `DELETE /instance/delete/:instanceId` - Deletar instância + +### Conexão (usa token da instância) +- `POST /instance/connect` - Conectar via QR Code +- `GET /instance/qr` - Obter QR Code +- `POST /instance/pair` - Conectar via código de pareamento +- `GET /instance/status` - Status da conexão +- `POST /instance/disconnect` - Desconectar +- `POST /instance/reconnect` - Reconectar +- `DELETE /instance/logout` - Fazer logout + +### Gerenciamento Avançado (Administrativo - usa GLOBAL_API_KEY) +- `POST /instance/proxy/:instanceId` - Configurar proxy +- `DELETE /instance/proxy/:instanceId` - Remover proxy +- `POST /instance/forcereconnect/:instanceId` - Forçar reconexão +- `GET /instance/logs/:instanceId` - Obter logs +- `GET /instance/:instanceId/advanced-settings` - Configurações avançadas +- `PUT /instance/:instanceId/advanced-settings` - Atualizar configurações + +--- + +## Criar Instância + +Cria uma nova instância WhatsApp. + +### Endpoint +``` +POST /instance/create +``` + +### Headers +``` +Content-Type: application/json +apikey: SUA-GLOBAL-API-KEY +``` + +**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (variável de ambiente), não o token da instância. + +### Body +```json +{ + "name": "vendas", + "token": "token-seguro-unico", + "webhook": "https://seu-servidor.com/webhook", + "webhookEvents": ["messages.upsert", "connection.update"], + "proxy": { + "host": "proxy.exemplo.com", + "port": "8080", + "username": "usuario", + "password": "senha" + } +} +``` + +### Parâmetros + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| name | string | ✅ Sim | Nome único da instância | +| token | string | ✅ Sim | Token de autenticação da instância | +| webhook | string | ❌ Não | URL para receber webhooks | +| webhookEvents | array | ❌ Não | Eventos específicos para webhook | +| proxy | object | ❌ Não | Configuração de proxy | + +### Resposta Sucesso (200) +```json +{ + "message": "success", + "data": { + "name": "vendas", + "token": "token-seguro-unico", + "webhook": "https://seu-servidor.com/webhook", + "status": "created", + "createdAt": "2025-01-15T10:30:00Z" + } +} +``` + +### Resposta Erro (400) +```json +{ + "error": "name is required" +} +``` + +### Exemplo cURL +```bash +curl -X POST http://localhost:4000/instance/create -H "Content-Type: application/json" -H "apikey: SUA-CHAVE-API" -d '{ + "name": "vendas", + "token": "meu-token-seguro" + }' +``` + +--- + +## Conectar Instância + +Inicia o processo de conexão via QR Code. + +### Endpoint +``` +POST /instance/connect +``` + +### Headers +``` +Content-Type: application/json +apikey: TOKEN-DA-INSTANCIA +``` + +**⚠️ Atenção**: Use o `token` que você definiu ao criar a instância, NÃO a `GLOBAL_API_KEY`. + +### Body +```json +{ + "webhookUrl": "https://seu-servidor.com/webhook", + "subscribe": ["messages.upsert", "connection.update"] +} +``` + +### Resposta Sucesso (200) +```json +{ + "message": "success", + "data": { + "jid": "5511999999999@s.whatsapp.net", + "webhookUrl": "https://seu-servidor.com/webhook", + "eventString": "messages.upsert,connection.update" + } +} +``` + +### Exemplo cURL +```bash +curl -X POST http://localhost:4000/instance/connect \ + -H "Content-Type: application/json" \ + -H "apikey: token-da-instancia-vendas" \ + -d '{ + "webhookUrl": "https://seu-servidor.com/webhook", + "subscribe": ["messages.upsert"] + }' +``` + +--- + +## Obter QR Code + +Retorna o QR Code para escanear com WhatsApp. + +### Endpoint +``` +GET /instance/qr +``` + +### Headers +``` +apikey: TOKEN-DA-INSTANCIA +``` + +**Importante**: A instância é identificada automaticamente pelo token no header. + +### Resposta Sucesso (200) +```json +{ + "message": "success", + "data": { + "qrcode": "2@abcd1234...", + "code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." + } +} +``` + +### Exemplo cURL +```bash +curl "http://localhost:4000/instance/qr" \ + -H "apikey: token-da-instancia-vendas" +``` + +--- + +## Conectar via Código de Pareamento + +Conecta usando código de 8 dígitos em vez de QR Code. + +### Endpoint +``` +POST /instance/pair +``` + +### Headers +``` +Content-Type: application/json +apikey: TOKEN-DA-INSTANCIA +``` + +### Body +```json +{ + "phone": "5511999999999" +} +``` + +### Resposta Sucesso (200) +```json +{ + "message": "success", + "data": { + "code": "12345678" + } +} +``` + +### Como Usar +1. Faça a requisição com seu número +2. Receba o código de 8 dígitos +3. No WhatsApp: Aparelhos conectados > Conectar dispositivo > Conectar com número de telefone +4. Digite o código recebido + +### Exemplo cURL +```bash +curl -X POST http://localhost:4000/instance/pair \ + -H "Content-Type: application/json" \ + -H "apikey: token-da-instancia-vendas" \ + -d '{"phone": "5511999999999"}' +``` + +--- + +## Status da Conexão + +Verifica o status atual da instância. + +### Endpoint +``` +GET /instance/status +``` + +### Headers +``` +apikey: TOKEN-DA-INSTANCIA +``` + +### Resposta Sucesso (200) +```json +{ + "message": "success", + "data": { + "connected": true, + "loggedIn": true, + "name": "Minha Empresa", + "myJid": "5511999999999@s.whatsapp.net" + } +} +``` + +### Status Possíveis +- `connected: false, loggedIn: false` - Instância criada mas não conectada +- `connected: true, loggedIn: false` - Conectando (aguardando QR Code) +- `connected: true, loggedIn: true` - Conectado e ativo +- `connected: false, loggedIn: true` - Sessão válida mas desconectado temporariamente + +### Exemplo cURL +```bash +curl "http://localhost:4000/instance/status" \ + -H "apikey: token-da-instancia-vendas" +``` + +--- + +## Listar Todas as Instâncias + +Retorna todas as instâncias cadastradas. + +### Endpoint +``` +GET /instance/all +``` + +### Headers +``` +apikey: SUA-GLOBAL-API-KEY +``` + +**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa). + +### Resposta Sucesso (200) +```json +{ + "message": "success", + "data": [ + { + "id": "abc123", + "name": "vendas", + "connected": true, + "jid": "5511999999999@s.whatsapp.net" + }, + { + "id": "def456", + "name": "suporte", + "connected": false, + "jid": null + } + ] +} +``` + +### Exemplo cURL +```bash +curl "http://localhost:4000/instance/all" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +--- + +## Informações da Instância + +Obtém informações detalhadas de uma instância específica. + +### Endpoint +``` +GET /instance/info/:instanceId +``` + +### Headers +``` +apikey: SUA-GLOBAL-API-KEY +``` + +**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa) e o ID da instância no path. + +### Resposta Sucesso (200) +```json +{ + "message": "success", + "data": { + "id": "abc123", + "name": "vendas", + "token": "token-seguro", + "webhook": "https://seu-servidor.com/webhook", + "events": "messages.upsert,connection.update", + "connected": true, + "jid": "5511999999999@s.whatsapp.net", + "createdAt": "2025-01-15T10:30:00Z" + } +} +``` + +### Exemplo cURL +```bash +curl "http://localhost:4000/instance/info/vendas" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +--- + +## Desconectar Instância + +Desconecta a instância mas mantém os dados. + +### Endpoint +``` +POST /instance/disconnect +``` + +### Headers +``` +apikey: TOKEN-DA-INSTANCIA +``` + +### Body +```json +{} +``` + +**Nota**: O body pode ser vazio. A instância é identificada pelo header apikey. + +### Resposta Sucesso (200) +```json +{ + "message": "success" +} +``` + +### Exemplo cURL +```bash +curl -X POST http://localhost:4000/instance/disconnect \ + -H "Content-Type: application/json" \ + -H "apikey: token-da-instancia-vendas" \ + -d '{}' +``` + +--- + +## Reconectar Instância + +Reconecta uma instância desconectada. + +### Endpoint +``` +POST /instance/reconnect +``` + +### Headers +``` +apikey: TOKEN-DA-INSTANCIA +``` + +### Body +```json +{} +``` + +### Resposta Sucesso (200) +```json +{ + "message": "success" +} +``` + +### Exemplo cURL +```bash +curl -X POST http://localhost:4000/instance/reconnect \ + -H "Content-Type: application/json" \ + -H "apikey: token-da-instancia-vendas" \ + -d '{}' +``` + +--- + +## Logout + +Faz logout completo, removendo a sessão WhatsApp. + +### Endpoint +``` +DELETE /instance/logout +``` + +### Headers +``` +apikey: TOKEN-DA-INSTANCIA +``` + +### Body +```json +{} +``` + +### Resposta Sucesso (200) +```json +{ + "message": "success" +} +``` + +**⚠️ Atenção**: Após logout, será necessário escanear QR Code novamente. + +### Exemplo cURL +```bash +curl -X DELETE http://localhost:4000/instance/logout \ + -H "Content-Type: application/json" \ + -H "apikey: token-da-instancia-vendas" \ + -d '{}' +``` + +--- + +## Deletar Instância + +Remove completamente a instância e todos os seus dados. + +### Endpoint +``` +DELETE /instance/delete/:instanceId +``` + +### Headers +``` +apikey: SUA-GLOBAL-API-KEY +``` + +**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa). Esta ação é irreversível! + +### Resposta Sucesso (200) +```json +{ + "message": "success" +} +``` + +### Exemplo cURL +```bash +curl -X DELETE "http://localhost:4000/instance/delete/vendas" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +--- + +## Configurar Proxy + +Configura proxy HTTP para a instância. + +### Endpoint +``` +POST /instance/proxy/:instanceId +``` + +### Headers +``` +Content-Type: application/json +apikey: SUA-GLOBAL-API-KEY +``` + +### Body +```json +{ + "host": "proxy.exemplo.com", + "port": "8080", + "username": "usuario", + "password": "senha" +} +``` + +### Resposta Sucesso (200) +```json +{ + "message": "success", + "data": { + "host": "proxy.exemplo.com", + "port": "8080", + "hasAuth": true + } +} +``` + +### Exemplo cURL +```bash +curl -X POST "http://localhost:4000/instance/proxy/vendas" \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-GLOBAL-API-KEY" \ + -d '{ + "host": "proxy.exemplo.com", + "port": "8080", + "username": "usuario", + "password": "senha" + }' +``` + +--- + +## Remover Proxy + +Remove configuração de proxy da instância. + +### Endpoint +``` +DELETE /instance/proxy/:instanceId +``` + +### Headers +``` +apikey: SUA-GLOBAL-API-KEY +``` + +### Resposta Sucesso (200) +```json +{ + "message": "success" +} +``` + +### Exemplo cURL +```bash +curl -X DELETE "http://localhost:4000/instance/proxy/vendas" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +--- + +## Forçar Reconexão + +Força reconexão com número específico (útil para resolver problemas). + +### Endpoint +``` +POST /instance/forcereconnect/:instanceId +``` + +### Headers +``` +Content-Type: application/json +apikey: SUA-GLOBAL-API-KEY +``` + +### Body +```json +{ + "number": "5511999999999" +} +``` + +### Resposta Sucesso (200) +```json +{ + "message": "success" +} +``` + +### Exemplo cURL +```bash +curl -X POST "http://localhost:4000/instance/forcereconnect/vendas" \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-GLOBAL-API-KEY" \ + -d '{"number": "5511999999999"}' +``` + +--- + +## Obter Logs + +Obtém logs da instância. + +### Endpoint +``` +GET /instance/logs/:instanceId?start_date=DATA&end_date=DATA&level=NIVEL&limit=N +``` + +### Headers +``` +apikey: SUA-GLOBAL-API-KEY +``` + +### Query Parameters +| Parâmetro | Tipo | Obrigatório | Descrição | +|-----------|------|-------------|-----------| +| start_date | string | ❌ Não | Data inicial (YYYY-MM-DD) | +| end_date | string | ❌ Não | Data final (YYYY-MM-DD) | +| level | string | ❌ Não | Nível do log (INFO, DEBUG, ERROR) | +| limit | integer | ❌ Não | Número de registros (padrão: 100) | + +### Resposta Sucesso (200) +```json +[ + { + "timestamp": "2025-01-15T10:30:00Z", + "level": "INFO", + "message": "Instance connected successfully", + "instanceId": "vendas" + } +] +``` + +### Exemplo cURL +```bash +curl "http://localhost:4000/instance/logs/vendas?start_date=2025-01-01&limit=50" \ + -H "apikey: SUA-GLOBAL-API-KEY" +``` + +--- + +## Configurações Avançadas + +### Obter Configurações + +``` +GET /instance/:instanceId/advanced-settings +``` + +### Headers +``` +apikey: SUA-GLOBAL-API-KEY +``` + +### Resposta (200) +```json +{ + "rejectCall": false, + "msgCall": "Não estou disponível para chamadas", + "groupsIgnore": true, + "alwaysOnline": false, + "readMessages": false, + "readStatus": false, + "syncFullHistory": false +} +``` + +### Atualizar Configurações + +``` +PUT /instance/:instanceId/advanced-settings +``` + +### Headers +``` +Content-Type: application/json +apikey: SUA-GLOBAL-API-KEY +``` + +### Body +```json +{ + "rejectCall": true, + "msgCall": "Por favor, envie mensagem", + "groupsIgnore": false, + "alwaysOnline": true, + "readMessages": true, + "readStatus": true, + "syncFullHistory": false +} +``` + +### Exemplo cURL +```bash +curl -X PUT "http://localhost:4000/instance/vendas/advanced-settings" \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-GLOBAL-API-KEY" \ + -d '{ + "rejectCall": true, + "alwaysOnline": true + }' +``` + +--- + +## Fluxo Completo de Uso + +### 1. Criar Instância (Administrativo) +```bash +curl -X POST http://localhost:4000/instance/create \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-GLOBAL-API-KEY" \ + -d '{ + "name": "vendas", + "token": "token-vendas-123" + }' +``` + +### 2. Conectar (Usando Token da Instância) +```bash +curl -X POST http://localhost:4000/instance/connect \ + -H "Content-Type: application/json" \ + -H "apikey: token-vendas-123" \ + -d '{ + "webhookUrl": "https://meu-servidor.com/webhook", + "subscribe": ["messages.upsert"] + }' +``` + +### 3. Obter QR Code +```bash +curl "http://localhost:4000/instance/qr" \ + -H "apikey: token-vendas-123" +``` + +### 4. Escanear QR Code com WhatsApp + +Abra o WhatsApp → Aparelhos conectados → Conectar um aparelho → Escanear QR Code + +### 5. Verificar Status +```bash +curl "http://localhost:4000/instance/status" \ + -H "apikey: token-vendas-123" +``` + +--- + +## Boas Práticas + +### 1. Gestão de Tokens + +**GLOBAL_API_KEY**: +- Use para rotas administrativas (criar, deletar, listar instâncias) +- Mantenha em segredo (variável de ambiente) +- Nunca exponha em código frontend +- Rotacione periodicamente + +**Token da Instância**: +- Defina ao criar a instância (`token` no body) +- Use para operações da instância específica (enviar mensagens, obter status) +- Um token único por instância +- Use UUIDs: `uuidgen` ou `python3 -c "import uuid; print(uuid.uuid4())"` + +### 2. Nome de Instância +- Use nomes descritivos e únicos +- Apenas letras, números e hífen +- Exemplo: `vendas-empresa`, `suporte-01` + +### 3. Webhooks +- Configure webhook para receber eventos em tempo real +- Use HTTPS em produção +- Valide os eventos recebidos +- Retorne status 200 rapidamente + +### 4. Gerenciamento +- Monitore o status das instâncias regularmente +- Configure reconexão automática se necessário +- Mantenha logs para debug +- Use configurações avançadas conforme necessário + +--- + +## Erros Comuns + +### "not authorized" +**Causa**: API key incorreta ou ausente +**Solução**: +- Rotas administrativas: Use `GLOBAL_API_KEY` +- Rotas de operação: Use token da instância + +### "instance not found" +**Causa**: Instância não existe ou token incorreto +**Solução**: Verifique se a instância foi criada e se está usando o token correto + +### "name is required" +**Causa**: Campo obrigatório não enviado +**Solução**: Inclua todos os campos obrigatórios no body + +### QR Code Expira +**Causa**: QR Code tem validade de ~40 segundos +**Solução**: Use `/instance/reconnect` para gerar novo QR + +### "session already logged in" +**Causa**: Tentou obter QR Code de instância já conectada +**Solução**: Instância já está conectada, não precisa de QR Code + +--- + +## Próximos Passos + +- [API de Mensagens](./api-messages.md) - Enviar diferentes tipos de mensagens +- [API de Usuários](./api-user.md) - Gerenciar perfil e contatos +- [Sistema de Eventos](../recursos-avancados/events-system.md) - Webhooks e eventos +- [Configuração](../fundamentos/configuration.md) - Variáveis de ambiente + +--- + +**Dica**: Use o Swagger em `http://localhost:4000/swagger/index.html` para testar os endpoints interativamente! diff --git a/docs/wiki/guias-api/api-labels.md b/docs/wiki/guias-api/api-labels.md new file mode 100644 index 0000000..09b275f --- /dev/null +++ b/docs/wiki/guias-api/api-labels.md @@ -0,0 +1,540 @@ +# API de Labels + +Documentação completa dos endpoints para organizar chats e mensagens com etiquetas (labels). + +## 📋 Índice + +- [Adicionar Label em Chat](#adicionar-label-em-chat) +- [Adicionar Label em Mensagem](#adicionar-label-em-mensagem) +- [Editar Label](#editar-label) +- [Remover Label de Chat](#remover-label-de-chat) +- [Remover Label de Mensagem](#remover-label-de-mensagem) +- [Listar Todas as Labels](#listar-todas-as-labels) + +--- + +## Adicionar Label em Chat + +Adiciona uma etiqueta (label) a um chat. + +**Endpoint**: `POST /label/chat` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "1" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `jid` | string | ✅ Sim | JID do chat (individual ou grupo) | +| `labelId` | string | ✅ Sim | ID da label | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/label/chat \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "1" + }' +``` + +--- + +## Adicionar Label em Mensagem + +Adiciona uma etiqueta a uma mensagem específica. + +**Endpoint**: `POST /label/message` + +**Body**: +```json +{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "2", + "messageId": "3EB0C5A277F7F9B6C599" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `jid` | string | ✅ Sim | JID do chat | +| `labelId` | string | ✅ Sim | ID da label | +| `messageId` | string | ✅ Sim | ID da mensagem | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/label/message \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "2", + "messageId": "3EB0C5A277F7F9B6C599" + }' +``` + +--- + +## Editar Label + +Edita nome, cor ou deleta uma label existente. + +**Endpoint**: `POST /label/edit` + +**Body**: +```json +{ + "labelId": "1", + "name": "Clientes VIP", + "color": 0, + "deleted": false +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `labelId` | string | ✅ Sim | ID da label a editar | +| `name` | string | ✅ Sim | Novo nome da label | +| `color` | int | ❌ Não | Código de cor (0-19) | +| `deleted` | bool | ❌ Não | Se true, marca label como deletada | + +**Cores Disponíveis** (0-19): + +| Código | Cor | +|--------|-----| +| 0 | Azul | +| 1 | Rosa | +| 2 | Roxo | +| 3 | Verde | +| 4 | Laranja | +| 5 | Cinza | +| 6 | Vermelho | +| 7 | Marrom | +| 8 | Verde água | +| 9 | Amarelo | +| 10-19 | Variações | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +# Renomear label +curl -X POST http://localhost:4000/label/edit \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "labelId": "1", + "name": "Clientes VIP", + "color": 3 + }' + +# Deletar label +curl -X POST http://localhost:4000/label/edit \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "labelId": "1", + "name": "Label antiga", + "deleted": true + }' +``` + +--- + +## Remover Label de Chat + +Remove uma etiqueta de um chat. + +**Endpoint**: `POST /unlabel/chat` + +**Body**: +```json +{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "1" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `jid` | string | ✅ Sim | JID do chat | +| `labelId` | string | ✅ Sim | ID da label a remover | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/unlabel/chat \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "1" + }' +``` + +--- + +## Remover Label de Mensagem + +Remove uma etiqueta de uma mensagem específica. + +**Endpoint**: `POST /unlabel/message` + +**Body**: +```json +{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "2", + "messageId": "3EB0C5A277F7F9B6C599" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `jid` | string | ✅ Sim | JID do chat | +| `labelId` | string | ✅ Sim | ID da label | +| `messageId` | string | ✅ Sim | ID da mensagem | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/unlabel/message \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "2", + "messageId": "3EB0C5A277F7F9B6C599" + }' +``` + +--- + +## Listar Todas as Labels + +Obtém todas as labels da instância. + +**Endpoint**: `GET /label` + +**Headers**: +``` +apikey: SUA-CHAVE-API +``` + +**Resposta de Sucesso (200)**: +```json +[ + { + "ID": 1, + "LabelID": "1", + "Name": "Clientes VIP", + "Color": 3, + "Deleted": false, + "PredefinedID": 0, + "InstanceID": "minha-instancia" + }, + { + "ID": 2, + "LabelID": "2", + "Name": "Suporte", + "Color": 6, + "Deleted": false, + "PredefinedID": 0, + "InstanceID": "minha-instancia" + } +] +``` + +**Campos da Resposta**: +- `ID`: ID interno do banco de dados +- `LabelID`: ID da label no WhatsApp +- `Name`: Nome da label +- `Color`: Código da cor (0-19) +- `Deleted`: Se foi deletada +- `PredefinedID`: ID de label pré-definida (0 se customizada) +- `InstanceID`: ID da instância + +**Exemplo cURL**: +```bash +curl -X GET http://localhost:4000/label \ + -H "apikey: SUA-CHAVE-API" +``` + +--- + +## Fluxos Completos de Uso + +### 1. Sistema de Categorização de Clientes + +```bash +# 1. Listar labels existentes +LABELS=$(curl -s -X GET http://localhost:4000/label \ + -H "apikey: SUA-CHAVE-API") + +echo $LABELS | jq '.' + +# 2. Criar nova label (via edição) +curl -X POST http://localhost:4000/label/edit \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "labelId": "10", + "name": "Lead Qualificado", + "color": 3, + "deleted": false + }' + +# 3. Etiquetar chats de clientes +CLIENTES=("5511999999999@s.whatsapp.net" "5511888888888@s.whatsapp.net") + +for cliente in "\${CLIENTES[@]}"; do + curl -X POST http://localhost:4000/label/chat \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d "{ + "jid": "$cliente", + "labelId": "10" + }" +done +``` + +### 2. Marcar Mensagens Importantes + +```bash +# Etiquetar mensagem específica como "Urgente" +curl -X POST http://localhost:4000/label/message \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "5511999999999@s.whatsapp.net", + "labelId": "5", + "messageId": "3EB0C5A277F7F9B6C599" + }' +``` + +### 3. Gerenciar Labels de Suporte + +```bash +# Criar labels de status de atendimento +LABELS=( + "1:Aguardando:0" + "2:Em Atendimento:3" + "3:Resolvido:4" + "4:Cancelado:6" +) + +for label_data in "\${LABELS[@]}"; do + IFS=':' read -r id name color <<< "$label_data" + + curl -X POST http://localhost:4000/label/edit \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d "{ + "labelId": "$id", + "name": "$name", + "color": $color, + "deleted": false + }" +done +``` + +### 4. Reorganizar Labels + +```bash +# Renomear label existente +curl -X POST http://localhost:4000/label/edit \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "labelId": "1", + "name": "Clientes Premium", + "color": 1 + }' + +# Deletar label obsoleta +curl -X POST http://localhost:4000/label/edit \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "labelId": "99", + "name": "Label Antiga", + "deleted": true + }' +``` + +--- + +## Casos de Uso Práticos + +### CRM Simples +Use labels para categorizar clientes: +- **Label 1**: Leads +- **Label 2**: Clientes Ativos +- **Label 3**: Clientes Inativos +- **Label 4**: VIP + +### Suporte ao Cliente +Organize tickets por status: +- **Label 1**: Aberto +- **Label 2**: Em Progresso +- **Label 3**: Aguardando Cliente +- **Label 4**: Resolvido + +### E-commerce +Categorize conversas por estágio: +- **Label 1**: Interessado +- **Label 2**: Pedido Realizado +- **Label 3**: Enviado +- **Label 4**: Entregue + +### Equipes +Atribua conversas para departamentos: +- **Label 1**: Vendas +- **Label 2**: Suporte +- **Label 3**: Financeiro +- **Label 4**: Diretoria + +--- + +## Códigos de Erro Comuns + +| Código | Erro | Solução | +|--------|------|---------| +| 400 | `jid is required` | Forneça o JID do chat | +| 400 | `label id is required` | Forneça o ID da label | +| 400 | `message id is required` | Forneça o ID da mensagem | +| 400 | `name is required` | Forneça o nome da label (ao editar) | +| 500 | `instance not found` | Instância não conectada | +| 500 | `error parse community jid` | JID inválido | + +--- + +## Boas Práticas + +### 1. Planeje suas Labels +Defina um sistema de categorização antes de começar. Exemplo: +- **Label 1**: "Novo Lead" (cor: azul/0) +- **Label 2**: "Qualificado" (cor: verde/3) +- **Label 3**: "Cliente" (cor: rosa/1) +- **Label 4**: "Inativo" (cor: marrom/5) + +### 2. Use Cores Consistentes +Mantenha um padrão de cores: +- **Verde (3)**: Status positivo +- **Vermelho (6)**: Urgente/Problema +- **Azul (0)**: Novo/Neutro +- **Laranja (4)**: Em progresso + +### 3. Documente IDs +Mantenha uma tabela de referência: +``` +ID | Nome | Cor | Descrição +---|------|-----|---------- +1 | VIP | 1 | Clientes premium +2 | Lead | 0 | Novos contatos +3 | Urg | 6 | Requer atenção +``` + +### 4. Não Abuse de Labels +Limite-se a **10-15 labels** no máximo. Muitas labels dificultam a organização. + +### 5. Limpe Labels Antigas +Periodicamente, revise e delete labels não utilizadas: +```bash +# Listar todas +curl -s http://localhost:4000/label -H "apikey: KEY" | jq '.' + +# Deletar obsoletas +curl -X POST http://localhost:4000/label/edit \ + -H "Content-Type: application/json" \ + -H "apikey: KEY" \ + -d '{"labelId": "99", "name": "Old", "deleted": true}' +``` + +### 6. Labels em Mensagens +Use labels em mensagens apenas para casos especiais: +- Mensagens com pedidos +- Informações importantes para referência +- Reclamações/Problemas + +**Evite**: Etiquetar todas as mensagens (cria poluição visual). + +--- + +## Limitações do WhatsApp + +### Limites Conhecidos +- **Máximo de labels**: Não documentado oficialmente, mas recomenda-se não ultrapassar 100 +- **Labels por chat**: Sem limite conhecido +- **Labels por mensagem**: 1 label por mensagem + +### Sincronização +Labels são sincronizadas entre dispositivos via WhatsApp Multi-Device. Mudanças podem levar alguns segundos para aparecer em outros dispositivos. + +### Visibilidade +Labels são **privadas** - apenas você vê suas labels. O destinatário não vê que você etiquetou o chat ou mensagem. + +--- + +## Próximos Passos + +- [API de Chats](./api-chats.md) - Gerenciar conversas (pin, archive, mute) +- [API de Mensagens](./api-messages.md) - Enviar e gerenciar mensagens +- [API de Usuários](./api-user.md) - Gerenciar perfil e contatos +- [Visão Geral da API](./api-overview.md) + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/guias-api/api-messages.md b/docs/wiki/guias-api/api-messages.md new file mode 100644 index 0000000..394c17e --- /dev/null +++ b/docs/wiki/guias-api/api-messages.md @@ -0,0 +1,1261 @@ +# API de Mensagens + +Documentação completa dos endpoints para enviar e gerenciar mensagens WhatsApp. + +## 📋 Índice + +### Enviar Mensagens +- [Enviar Texto](#enviar-texto) +- [Enviar Link com Preview](#enviar-link-com-preview) +- [Enviar Mídia](#enviar-mídia) +- [Enviar Enquete (Poll)](#enviar-enquete) +- [Enviar Sticker](#enviar-sticker) +- [Enviar Localização](#enviar-localização) +- [Enviar Contato](#enviar-contato) +- [~~Enviar Botões~~](#enviar-botões) ⚠️ **DEPRECIADO** +- [~~Enviar Lista~~](#enviar-lista) ⚠️ **DEPRECIADO** + +### Gerenciar Mensagens +- [Reagir a Mensagem](#reagir-a-mensagem) +- [Marcar como Lida](#marcar-como-lida) +- [Editar Mensagem](#editar-mensagem) +- [Deletar Mensagem](#deletar-mensagem) +- [Presença no Chat](#presença-no-chat) +- [Download de Mídia](#download-de-mídia) +- [Status da Mensagem](#status-da-mensagem) + +--- + +## Enviar Mensagens + +### Enviar Texto + +Envia uma mensagem de texto simples. + +**Endpoint**: `POST /send/text` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "number": "5511999999999", + "text": "Olá! Como posso ajudar?", + "id": "msg-custom-123", + "delay": 1000, + "mentionedJid": "5511888888888@s.whatsapp.net", + "mentionAll": false, + "formatJid": true, + "quoted": { + "messageId": "BAE5...", + "participant": "5511999999999@s.whatsapp.net" + } +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário (formato: DDI + DDD + número) | +| `text` | string | ✅ Sim | Texto da mensagem | +| `id` | string | ❌ Não | ID customizado (se vazio, será gerado automaticamente) | +| `delay` | int32 | ❌ Não | Delay em milissegundos antes de enviar | +| `mentionedJid` | string | ❌ Não | JID do usuário a mencionar | +| `mentionAll` | bool | ❌ Não | Mencionar todos os participantes (apenas grupos) | +| `formatJid` | bool | ❌ Não | Formatar número automaticamente (padrão: true) | +| `quoted` | object | ❌ Não | Mensagem a ser citada | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "ServerID": 12345, + "Timestamp": "2025-11-11T10:30:00Z", + "Type": "ExtendedTextMessage" + } + } +} +``` + +**Resposta de Erro (400)**: +```json +{ + "error": "phone number is required" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/send/text \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "text": "Olá! Esta é uma mensagem de teste." + }' +``` + +--- + +### Enviar Link com Preview + +Envia uma mensagem com preview de link (título, descrição, imagem). + +**Endpoint**: `POST /send/link` + +**Body**: +```json +{ + "number": "5511999999999", + "text": "Confira este artigo: https://example.com/artigo", + "title": "Título do Link", + "url": "https://example.com/artigo", + "description": "Descrição do conteúdo", + "imgUrl": "https://example.com/imagem.jpg" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `text` | string | ✅ Sim | Texto com URL | +| `title` | string | ❌ Não | Título do preview (extraído automaticamente se vazio) | +| `url` | string | ❌ Não | URL do link | +| `description` | string | ❌ Não | Descrição (extraída automaticamente se vazia) | +| `imgUrl` | string | ❌ Não | URL da imagem de preview | + +**Nota**: Se `title`, `description` ou `imgUrl` não forem fornecidos, o sistema tentará extrair automaticamente os metadados Open Graph da URL. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "ExtendedTextMessage" + } + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/send/link \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "text": "Veja esta notícia: https://g1.globo.com/tecnologia" + }' +``` + +--- + +### Enviar Mídia + +Envia imagem, vídeo, áudio ou documento. Suporta envio via **URL** ou **arquivo local** (multipart/form-data). + +**Endpoint**: `POST /send/media` + +#### Opção 1: Enviar por URL + +**Body (JSON)**: +```json +{ + "number": "5511999999999", + "url": "https://example.com/imagem.jpg", + "type": "image", + "caption": "Confira esta imagem!", + "filename": "foto.jpg" +} +``` + +#### Opção 2: Enviar Arquivo (multipart/form-data) + +**Body (form-data)**: +``` +number: 5511999999999 +type: image +caption: Confira esta imagem! +filename: foto.jpg +file: [arquivo binário] +delay: 0 +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `type` | string | ✅ Sim | Tipo: `image`, `video`, `audio`, `document` | +| `url` | string | ✅ Sim (URL) | URL da mídia (se não enviar arquivo) | +| `file` | binary | ✅ Sim (arquivo) | Arquivo binário (se não enviar URL) | +| `caption` | string | ❌ Não | Legenda da mídia | +| `filename` | string | ❌ Não | Nome do arquivo | + +**Tipos de Mídia Aceitos**: + +| Tipo | Formatos Aceitos | Observações | +|------|------------------|-------------| +| `image` | JPG, PNG, WebP | WebP convertido para JPEG | +| `video` | MP4 | Apenas MP4 | +| `audio` | Qualquer | Convertido para Opus (PTT) automaticamente | +| `document` | Qualquer | Qualquer tipo de arquivo | + +**Áudio**: O sistema converte automaticamente qualquer formato de áudio para **Opus** (formato PTT do WhatsApp). Pode usar conversor local (ffmpeg) ou API externa (configurável via `API_AUDIO_CONVERTER`). + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "ImageMessage" + } + } +} +``` + +**Resposta de Erro (400)**: +```json +{ + "error": "Invalid file format: 'image/gif'. Only 'image/jpeg', 'image/png' and 'image/webp' are accepted" +} +``` + +**Exemplo cURL (URL)**: +```bash +curl -X POST http://localhost:4000/send/media \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "url": "https://exemplo.com/produto.jpg", + "type": "image", + "caption": "Novo produto disponível!" + }' +``` + +**Exemplo cURL (Arquivo)**: +```bash +curl -X POST http://localhost:4000/send/media \ + -H "apikey: SUA-CHAVE-API" \ + -F "number=5511999999999" \ + -F "type=image" \ + -F "caption=Foto enviada" \ + -F "file=@/caminho/para/imagem.jpg" +``` + +--- + +### Enviar Enquete + +Cria uma enquete (poll) com múltiplas opções. + +**Endpoint**: `POST /send/poll` + +**Body**: +```json +{ + "number": "5511999999999", + "question": "Qual seu horário preferido?", + "maxAnswer": 1, + "options": [ + "Manhã (8h-12h)", + "Tarde (13h-18h)", + "Noite (19h-22h)" + ] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `question` | string | ✅ Sim | Pergunta da enquete | +| `options` | array | ✅ Sim | Opções (mínimo 2) | +| `maxAnswer` | int | ❌ Não | Número máximo de respostas permitidas | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "PollCreationMessage" + } + } +} +``` + +**Resposta de Erro (400)**: +```json +{ + "error": "minimum 2 options are required" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/send/poll \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "question": "Qual plano você prefere?", + "maxAnswer": 1, + "options": ["Básico", "Intermediário", "Premium"] + }' +``` + +--- + +### Enviar Sticker + +Envia um sticker (figurinha) via URL. + +**Endpoint**: `POST /send/sticker` + +**Body**: +```json +{ + "number": "5511999999999", + "sticker": "https://example.com/sticker.webp" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `sticker` | string | ✅ Sim | URL da imagem (convertida para WebP automaticamente) | + +**Nota**: O sistema converte automaticamente a imagem para o formato WebP (formato de sticker do WhatsApp). + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "StickerMessage" + } + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/send/sticker \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "sticker": "https://exemplo.com/figurinha.png" + }' +``` + +--- + +### Enviar Localização + +Envia uma localização geográfica. + +**Endpoint**: `POST /send/location` + +**Body**: +```json +{ + "number": "5511999999999", + "name": "Escritório Central", + "address": "Av. Paulista, 1000 - São Paulo, SP", + "latitude": -23.5505199, + "longitude": -46.6333094 +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `latitude` | float64 | ✅ Sim | Latitude da localização | +| `longitude` | float64 | ✅ Sim | Longitude da localização | +| `name` | string | ✅ Sim | Nome do local | +| `address` | string | ✅ Sim | Endereço do local | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "LocationMessage" + } + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/send/location \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "name": "Teatro Municipal", + "address": "Praça Ramos de Azevedo, São Paulo", + "latitude": -23.5454614, + "longitude": -46.6369813 + }' +``` + +--- + +### Enviar Contato + +Envia um cartão de contato (VCard). + +**Endpoint**: `POST /send/contact` + +**Body**: +```json +{ + "number": "5511999999999", + "vcard": { + "fullName": "João Silva", + "phone": "5511888888888", + "organization": "Empresa LTDA" + } +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `vcard.fullName` | string | ✅ Sim | Nome completo do contato | +| `vcard.phone` | string | ✅ Sim | Telefone do contato | +| `vcard.organization` | string | ❌ Não | Empresa/organização | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "ContactMessage" + } + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/send/contact \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "vcard": { + "fullName": "Maria Santos", + "phone": "5511777777777", + "organization": "Vendas LTDA" + } + }' +``` + +--- + +### Enviar Botões + +> ⚠️ **ENDPOINT DEPRECIADO** +> +> Este endpoint **não funciona mais**. O WhatsApp descontinuou o suporte a botões interativos para contas que não são Business API oficial. +> +> **Alternativas**: +> - Use **Enquetes (Polls)** para coleta de respostas +> - Use **mensagens de texto** com instruções +> - Para soluções avançadas, migre para WhatsApp Business API oficial + +~~Envia mensagem com botões interativos. Suporta diferentes tipos de botões.~~ + +**Endpoint**: ~~`POST /send/button`~~ + +**Body**: +```json +{ + "number": "5511999999999", + "title": "Escolha uma opção", + "description": "Selecione o que deseja fazer", + "footer": "Powered by Evolution GO", + "buttons": [ + { + "type": "reply", + "displayText": "Ver Produtos", + "id": "btn_produtos" + }, + { + "type": "url", + "displayText": "Site Oficial", + "url": "https://exemplo.com" + }, + { + "type": "call", + "displayText": "Ligar", + "phoneNumber": "5511999999999" + } + ] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `title` | string | ✅ Sim | Título da mensagem | +| `description` | string | ✅ Sim | Descrição/corpo da mensagem | +| `footer` | string | ✅ Sim | Rodapé da mensagem | +| `buttons` | array | ✅ Sim | Array de botões (máx 3 para tipo reply) | + +**Tipos de Botões**: + +| Tipo | Campos Necessários | Descrição | Limitações | +|------|-------------------|-----------|------------| +| `reply` | `displayText`, `id` | Botão de resposta rápida | Máx 3, não pode misturar com outros tipos | +| `copy` | `displayText`, `copyCode` | Copiar texto | - | +| `url` | `displayText`, `url` | Abrir URL | - | +| `call` | `displayText`, `phoneNumber` | Ligar para número | - | +| `pix` | `name`, `key`, `keyType`, `currency` | Pagamento PIX (Brasil) | Não pode combinar com outros | + +**Botão PIX**: +```json +{ + "type": "pix", + "name": "Loja Exemplo", + "key": "exemplo@pix.com", + "keyType": "email", + "currency": "BRL" +} +``` + +Tipos de chave PIX: `phone`, `email`, `cpf`, `cnpj`, `random` (EVP). + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "ButtonMessage" + } + } +} +``` + +**Resposta de Erro (400)**: +```json +{ + "error": "máximo de 3 botões do tipo 'reply' permitidos" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/send/button \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "title": "Atendimento", + "description": "Como podemos ajudar?", + "footer": "Suporte 24h", + "buttons": [ + {"type": "reply", "displayText": "Falar com Vendas", "id": "vendas"}, + {"type": "reply", "displayText": "Suporte Técnico", "id": "suporte"} + ] + }' +``` + +--- + +### Enviar Lista + +> ⚠️ **ENDPOINT DEPRECIADO** +> +> Este endpoint **não funciona mais**. O WhatsApp descontinuou o suporte a listas interativas para contas que não são Business API oficial. +> +> **Alternativas**: +> - Use **Enquetes (Polls)** para seleção de opções +> - Use **mensagens de texto** com numeração +> - Para soluções avançadas, migre para WhatsApp Business API oficial + +~~Envia mensagem com menu de lista interativo.~~ + +**Endpoint**: ~~`POST /send/list`~~ + +**Body**: +```json +{ + "number": "5511999999999", + "title": "Nossos Serviços", + "description": "Selecione um serviço", + "buttonText": "Ver Opções", + "footerText": "Atendimento 24h", + "sections": [ + { + "title": "Planos", + "rows": [ + { + "title": "Plano Básico", + "description": "R$ 29,90/mês", + "rowId": "plano_basico" + }, + { + "title": "Plano Premium", + "description": "R$ 59,90/mês", + "rowId": "plano_premium" + } + ] + }, + { + "title": "Suporte", + "rows": [ + { + "title": "Falar com Atendente", + "description": "Chat ao vivo", + "rowId": "atendente" + } + ] + } + ] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do destinatário | +| `title` | string | ✅ Sim | Título da mensagem | +| `description` | string | ✅ Sim | Descrição/corpo | +| `buttonText` | string | ✅ Sim | Texto do botão que abre a lista | +| `footerText` | string | ✅ Sim | Rodapé da mensagem | +| `sections` | array | ✅ Sim | Seções da lista | + +**Estrutura de Section**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `title` | string | ✅ Sim | Título da seção | +| `rows` | array | ✅ Sim | Linhas da seção | + +**Estrutura de Row**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `title` | string | ✅ Sim | Título da opção | +| `description` | string | ❌ Não | Descrição da opção | +| `rowId` | string | ✅ Sim | ID único da opção | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "ListMessage" + } + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/send/list \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "title": "Menu Principal", + "description": "Escolha uma categoria", + "buttonText": "Ver Menu", + "footerText": "Delivery 24h", + "sections": [ + { + "title": "Pratos", + "rows": [ + {"title": "Pizza", "description": "A partir de R$ 35", "rowId": "pizza"}, + {"title": "Hambúrguer", "description": "A partir de R$ 25", "rowId": "burger"} + ] + } + ] + }' +``` + +--- + +## Gerenciar Mensagens + +### Reagir a Mensagem + +Adiciona ou remove uma reação (emoji) em uma mensagem. + +**Endpoint**: `POST /message/react` + +**Body**: +```json +{ + "number": "5511999999999", + "reaction": "👍", + "id": "3EB0C5A277F7F9B6C599", + "fromMe": false, + "participant": "5511888888888@s.whatsapp.net" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do chat (individual ou grupo) | +| `reaction` | string | ✅ Sim | Emoji da reação (ou "remove" para remover) | +| `id` | string | ✅ Sim | ID da mensagem a reagir | +| `fromMe` | bool | ✅ Sim | Se a mensagem foi enviada por você (true/false) | +| `participant` | string | ❌ Não | JID do autor (obrigatório em grupos quando fromMe=false) | + +**Nota**: Para remover uma reação, use `"reaction": "remove"`. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Info": { + "ID": "3EB0C5A277F7F9B6C599", + "Type": "ReactionMessage" + } + } +} +``` + +**Exemplo cURL**: +```bash +# Adicionar reação +curl -X POST http://localhost:4000/message/react \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "reaction": "❤️", + "id": "3EB0C5A277F7F9B6C599", + "fromMe": false + }' + +# Remover reação +curl -X POST http://localhost:4000/message/react \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "reaction": "remove", + "id": "3EB0C5A277F7F9B6C599", + "fromMe": false + }' +``` + +--- + +### Marcar como Lida + +Marca mensagem(ns) como lida(s). + +**Endpoint**: `POST /message/markread` + +**Body**: +```json +{ + "number": "5511999999999", + "id": [ + "3EB0C5A277F7F9B6C599", + "3EB0C5A277F7F9B6C600" + ] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do chat | +| `id` | array | ✅ Sim | Array de IDs de mensagens para marcar como lidas | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/message/markread \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "id": ["3EB0C5A277F7F9B6C599"] + }' +``` + +--- + +### Editar Mensagem + +Edita o conteúdo de uma mensagem enviada. + +**Endpoint**: `POST /message/edit` + +**Body**: +```json +{ + "chat": "5511999999999@s.whatsapp.net", + "messageId": "3EB0C5A277F7F9B6C599", + "message": "Texto editado da mensagem" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `chat` | string | ✅ Sim | JID do chat | +| `messageId` | string | ✅ Sim | ID da mensagem a editar | +| `message` | string | ✅ Sim | Novo texto da mensagem | + +**Nota**: Só é possível editar mensagens de texto enviadas por você (fromMe=true). + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "messageId": "3EB0C5A277F7F9B6C599", + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/message/edit \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "5511999999999@s.whatsapp.net", + "messageId": "3EB0C5A277F7F9B6C599", + "message": "Mensagem corrigida" + }' +``` + +--- + +### Deletar Mensagem + +Deleta uma mensagem para todos (revoke). + +**Endpoint**: `POST /message/delete` + +**Body**: +```json +{ + "chat": "5511999999999@s.whatsapp.net", + "messageId": "3EB0C5A277F7F9B6C599" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `chat` | string | ✅ Sim | JID do chat | +| `messageId` | string | ✅ Sim | ID da mensagem a deletar | + +**Nota**: Só é possível deletar mensagens enviadas por você. O WhatsApp tem limite de tempo para deletar mensagens (geralmente até 1 hora). + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "messageId": "3EB0C5A277F7F9B6C599", + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/message/delete \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "chat": "5511999999999@s.whatsapp.net", + "messageId": "3EB0C5A277F7F9B6C599" + }' +``` + +--- + +### Presença no Chat + +Define o status de presença no chat (digitando, gravando áudio, online). + +**Endpoint**: `POST /message/presence` + +**Body**: +```json +{ + "number": "5511999999999", + "state": "composing", + "isAudio": false +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do chat | +| `state` | string | ✅ Sim | Estado: `composing`, `paused`, `recording`, `available`, `unavailable` | +| `isAudio` | bool | ❌ Não | Se true, mostra "gravando áudio" (apenas com state=composing) | + +**Estados Disponíveis**: +- `composing` - Digitando... +- `paused` - Para de digitar +- `recording` - Gravando áudio (use isAudio=true) +- `available` - Online +- `unavailable` - Offline + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +# Mostrar "digitando..." +curl -X POST http://localhost:4000/message/presence \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "state": "composing", + "isAudio": false + }' + +# Mostrar "gravando áudio..." +curl -X POST http://localhost:4000/message/presence \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "state": "composing", + "isAudio": true + }' + +# Parar de digitar +curl -X POST http://localhost:4000/message/presence \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "state": "paused" + }' +``` + +--- + +### Download de Mídia + +Faz download de mídia de uma mensagem recebida e retorna em base64. + +**Endpoint**: `POST /message/downloadimage` + +**Body**: +```json +{ + "message": { + "imageMessage": { + "url": "...", + "mimetype": "image/jpeg", + "fileSha256": "...", + "fileLength": "..." + } + } +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `message` | object | ✅ Sim | Objeto de mensagem completo (do webhook) | + +**Tipos de Mídia Suportados**: +- `imageMessage` - Imagens +- `videoMessage` - Vídeos +- `audioMessage` - Áudios +- `documentMessage` - Documentos +- `stickerMessage` - Stickers (convertido para PNG) + +**Nota**: O objeto `message` deve ser o mesmo recebido via webhook/event. Contém todas as informações necessárias para download (URL, chaves de criptografia, etc). + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "base64": "data:image/jpeg;base64,/9j/4AAQSkZJRg...", + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/message/downloadimage \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "message": { + "imageMessage": { + "url": "https://mmg.whatsapp.net/...", + "mimetype": "image/jpeg", + "fileSha256": "...", + "fileLength": 123456 + } + } + }' +``` + +--- + +### Status da Mensagem + +Consulta o status de entrega/leitura de uma mensagem no banco de dados. + +**Endpoint**: `POST /message/status` + +**Body**: +```json +{ + "id": "3EB0C5A277F7F9B6C599" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `id` | string | ✅ Sim | ID da mensagem | + +**Nota**: Requer `DATABASE_SAVE_MESSAGES=true` para funcionar. O sistema precisa estar salvando mensagens no banco. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "result": { + "id": "3EB0C5A277F7F9B6C599", + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": true, + "messageType": "conversation", + "status": "READ", + "timestamp": "2025-11-11T10:30:00Z" + }, + "timestamp": "2025-11-11T10:31:00Z" + } +} +``` + +**Status Possíveis**: +- `PENDING` - Enviando +- `SENT` - Enviada +- `DELIVERED` - Entregue +- `READ` - Lida + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/message/status \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "id": "3EB0C5A277F7F9B6C599" + }' +``` + +--- + +## Recursos Adicionais + +### Citação de Mensagens (Quoted) + +Para citar/responder uma mensagem, adicione o objeto `quoted` em qualquer endpoint de envio: + +```json +{ + "number": "5511999999999", + "text": "Respondendo sua mensagem", + "quoted": { + "messageId": "3EB0C5A277F7F9B6C599", + "participant": "5511999999999@s.whatsapp.net" + } +} +``` + +### Menções em Grupos + +Para mencionar usuários em grupos, use `mentionedJid` ou `mentionAll`: + +```json +{ + "number": "120363XXXXXXXXXX@g.us", + "text": "Olá @usuario, tudo bem?", + "mentionedJid": "5511888888888@s.whatsapp.net" +} +``` + +Ou mencionar todos: + +```json +{ + "number": "120363XXXXXXXXXX@g.us", + "text": "@todos Reunião às 15h!", + "mentionAll": true +} +``` + +### Delay e Presença + +Simule digitação antes de enviar: + +```json +{ + "number": "5511999999999", + "text": "Mensagem com delay", + "delay": 3000 +} +``` + +Isso mostrará "digitando..." por 3 segundos antes de enviar a mensagem. + +### Verificação de Número + +Por padrão, o sistema verifica se o número existe no WhatsApp antes de enviar (configurável via `CHECK_USER_EXISTS`). Se desabilitado, mensagens podem falhar silenciosamente. + +### Formatação de Números + +O parâmetro `formatJid` (padrão: true) normaliza automaticamente o número: +- Remove caracteres especiais +- Adiciona sufixo @s.whatsapp.net +- Valida formato + +Para enviar para JIDs já formatados (grupos, etc), use `formatJid: false`. + +--- + +## Códigos de Erro Comuns + +| Código | Erro | Solução | +|--------|------|---------| +| 400 | `phone number is required` | Forneça o campo `number` | +| 400 | `message body is required` | Forneça o campo `text` ou conteúdo | +| 400 | `minimum 2 options are required` | Enquetes precisam de pelo menos 2 opções | +| 400 | `Invalid file format` | Formato de arquivo não suportado | +| 500 | `instance not found` | Instância não existe ou não está conectada | +| 500 | `client disconnected` | Instância desconectada, reconecte | +| 500 | `number X is not registered on WhatsApp` | Número não existe no WhatsApp | + +--- + +## Boas Práticas + +### 1. Usar Delay em Múltiplas Mensagens +Ao enviar várias mensagens seguidas, use o parâmetro `delay` para parecer mais natural: +- Primeira mensagem: `"delay": 1000` (1 segundo) +- Segunda mensagem: `"delay": 2000` (2 segundos) +- Terceira mensagem: `"delay": 1500` (1.5 segundos) + +Isso simula o tempo que uma pessoa levaria para digitar cada mensagem. + +### 2. Verificar Status de Conexão +Antes de enviar mensagens em massa, verifique se a instância está conectada: +```bash +curl "http://localhost:4000/instance/status" \ + -H "apikey: TOKEN-DA-INSTANCIA" +``` + +### 3. Tratamento de Erros +Sempre trate erros HTTP 4xx (validação) e 5xx (servidor): +- **400**: Erro de validação (campos obrigatórios faltando, formato inválido) +- **500**: Erro no servidor (instância desconectada, número inválido, etc) + +Sempre verifique o status code da resposta e o campo `error` no JSON retornado. + +### 4. Usar Webhooks +Para receber mensagens, configure webhooks em vez de polling: +```env +WEBHOOK_URL=https://seu-servidor.com/webhook +``` + +### 5. Gerenciar Mídias +Para áudio, configure conversor externo para melhor performance: +```env +API_AUDIO_CONVERTER=https://seu-conversor.com/convert +API_AUDIO_CONVERTER_KEY=sua-chave +``` + +--- + +## Próximos Passos + +- [API de Usuários](./api-user.md) - Gerenciar perfil e contatos +- [API de Grupos](./api-groups.md) - Criar e administrar grupos +- [Sistema de Eventos](../recursos-avancados/events-system.md) - Receber webhooks +- [Referência Completa da API](../guias-api/api-overview.md) + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/guias-api/api-newsletter.md b/docs/wiki/guias-api/api-newsletter.md new file mode 100644 index 0000000..6825ac4 --- /dev/null +++ b/docs/wiki/guias-api/api-newsletter.md @@ -0,0 +1,593 @@ +# API de Newsletters + +Documentação dos endpoints para gerenciar Newsletters (Canais) do WhatsApp. + +## 📋 Índice + +- [Criar Newsletter](#criar-newsletter) +- [Listar Newsletters Inscritas](#listar-newsletters-inscritas) +- [Informações da Newsletter](#informações-da-newsletter) +- [Obter Newsletter por Link](#obter-newsletter-por-link) +- [Inscrever em Newsletter](#inscrever-em-newsletter) +- [Listar Mensagens](#listar-mensagens) + +--- + +## O que são Newsletters? + +**Newsletters** (também chamadas de **Canais**) são um recurso do WhatsApp para transmissão unidirecional de mensagens. Similar a um canal de broadcast. + +**Características**: +- **Transmissão unidirecional**: Apenas admins postam, seguidores apenas leem +- **Sem limite de seguidores**: Diferente de grupos (1024) ou listas de transmissão (256) +- **Privacidade**: Seguidores não veem quem mais segue o canal +- **Reações**: Seguidores podem reagir às mensagens +- **Conteúdo público ou privado**: Configurável + +--- + +## Criar Newsletter + +Cria um novo canal (newsletter) no WhatsApp. + +**Endpoint**: `POST /newsletter/create` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "name": "Notícias da Empresa", + "description": "Canal oficial de comunicados e novidades" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `name` | string | ✅ Sim | Nome do canal | +| `description` | string | ❌ Não | Descrição do canal | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "ID": "120363XXXXXXXXXX@newsletter", + "Name": "Notícias da Empresa", + "Description": "Canal oficial de comunicados e novidades", + "SubscriberCount": 0, + "CreationTime": 1699000000, + "Settings": { + "ReactionCodes": ["👍", "❤️", "😂", "😮", "😢", "🙏"] + }, + "ThreadMetadata": { + "CreationTime": 1699000000 + } + } +} +``` + +**Campos da Resposta**: +- `ID`: JID único do canal (formato @newsletter) +- `Name`: Nome do canal +- `Description`: Descrição +- `SubscriberCount`: Número de seguidores +- `Settings.ReactionCodes`: Reações permitidas + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/newsletter/create \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "name": "Canal de Ofertas", + "description": "Promoções e ofertas exclusivas" + }' +``` + +--- + +## Listar Newsletters Inscritas + +Lista todos os canais que você está seguindo. + +**Endpoint**: `GET /newsletter/list` + +**Headers**: +``` +apikey: SUA-CHAVE-API +``` + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": [ + { + "ID": "120363XXXXXXXXXX@newsletter", + "Name": "Canal de Ofertas", + "Description": "Promoções exclusivas", + "SubscriberCount": 1523, + "Role": "SUBSCRIBER", + "Settings": { + "ReactionCodes": ["👍", "❤️", "😂"] + } + }, + { + "ID": "120363YYYYYYYYYY@newsletter", + "Name": "Notícias Tech", + "Description": "Últimas novidades em tecnologia", + "SubscriberCount": 5420, + "Role": "OWNER", + "Settings": { + "ReactionCodes": ["👍", "❤️"] + } + } + ] +} +``` + +**Roles Possíveis**: +- `OWNER`: Você é o criador/dono do canal +- `ADMIN`: Você é administrador +- `SUBSCRIBER`: Você é apenas seguidor + +**Exemplo cURL**: +```bash +curl -X GET http://localhost:4000/newsletter/list \ + -H "apikey: SUA-CHAVE-API" +``` + +--- + +## Informações da Newsletter + +Obtém informações detalhadas de um canal específico. + +**Endpoint**: `POST /newsletter/info` + +**Body**: +```json +{ + "jid": "120363XXXXXXXXXX@newsletter" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `jid` | string (JID) | ✅ Sim | JID do canal | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "ID": "120363XXXXXXXXXX@newsletter", + "State": "ACTIVE", + "Name": "Canal de Ofertas", + "Description": "Promoções exclusivas", + "SubscriberCount": 1523, + "VerificationState": "VERIFIED", + "Role": "SUBSCRIBER", + "Settings": { + "ReactionCodes": ["👍", "❤️", "😂", "😮", "😢", "🙏"] + }, + "ThreadMetadata": { + "CreationTime": 1699000000 + }, + "ViewerMetadata": { + "MuteState": "UNMUTED", + "ViewerRole": "SUBSCRIBER" + } + } +} +``` + +**Campos Adicionais**: +- `State`: ACTIVE, SUSPENDED, GEOSUSPENDED +- `VerificationState`: VERIFIED (canal verificado) ou não +- `ViewerMetadata.MuteState`: MUTED ou UNMUTED + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/newsletter/info \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "120363XXXXXXXXXX@newsletter" + }' +``` + +--- + +## Obter Newsletter por Link + +Obtém informações de um canal através do link de convite. + +**Endpoint**: `POST /newsletter/link` + +**Body**: +```json +{ + "key": "ABC123XYZ" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `key` | string | ✅ Sim | Código do link de convite | + +**Nota**: O `key` é a parte após `https://whatsapp.com/channel/` no link do canal. + +**Exemplo de Link**: +``` +https://whatsapp.com/channel/ABC123XYZ + ↑ + Este é o key +``` + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "ID": "120363XXXXXXXXXX@newsletter", + "Name": "Canal Público", + "Description": "Nosso canal oficial", + "SubscriberCount": 2547, + "VerificationState": "VERIFIED", + "Settings": { + "ReactionCodes": ["👍", "❤️"] + } + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/newsletter/link \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "key": "ABC123XYZ" + }' +``` + +--- + +## Inscrever em Newsletter + +Inscreve-se (segue) um canal do WhatsApp. + +**Endpoint**: `POST /newsletter/subscribe` + +**Body**: +```json +{ + "jid": "120363XXXXXXXXXX@newsletter" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `jid` | string (JID) | ✅ Sim | JID do canal | + +**Nota**: Para obter o JID, primeiro use `/newsletter/link` com o código do convite. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/newsletter/subscribe \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "120363XXXXXXXXXX@newsletter" + }' +``` + +--- + +## Listar Mensagens + +Obtém mensagens de um canal. + +**Endpoint**: `POST /newsletter/messages` + +**Body**: +```json +{ + "jid": "120363XXXXXXXXXX@newsletter", + "count": 20, + "before_id": 0 +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `jid` | string (JID) | ✅ Sim | JID do canal | +| `count` | int | ❌ Não | Número de mensagens (padrão: 20, máx: 100) | +| `before_id` | int | ❌ Não | ID da mensagem para paginação (0 = mais recentes) | + +**Paginação**: Use o `ServerID` da última mensagem como `before_id` para buscar mensagens mais antigas. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": [ + { + "MessageServerID": 12345, + "ViewsCount": 1234, + "Message": { + "conversation": "Bem-vindos ao nosso canal!" + }, + "ReactionCounts": { + "👍": 45, + "❤️": 89 + } + }, + { + "MessageServerID": 12344, + "ViewsCount": 2156, + "Message": { + "imageMessage": { + "url": "https://...", + "caption": "Promoção imperdível!" + } + }, + "ReactionCounts": { + "👍": 124, + "😮": 23 + } + } + ] +} +``` + +**Campos da Resposta**: +- `MessageServerID`: ID único da mensagem +- `ViewsCount`: Número de visualizações +- `Message`: Conteúdo da mensagem (texto, imagem, etc) +- `ReactionCounts`: Contagem de cada reação + +**Exemplo cURL**: +```bash +# Buscar últimas 20 mensagens +curl -X POST http://localhost:4000/newsletter/messages \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "120363XXXXXXXXXX@newsletter", + "count": 20 + }' + +# Buscar 20 mensagens anteriores (paginação) +curl -X POST http://localhost:4000/newsletter/messages \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "jid": "120363XXXXXXXXXX@newsletter", + "count": 20, + "before_id": 12340 + }' +``` + +--- + +## Fluxos Completos + +### 1. Criar e Configurar Canal + +```bash +# 1. Criar canal +NEWSLETTER_JID=$(curl -s -X POST http://localhost:4000/newsletter/create \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "name": "Ofertas Especiais", + "description": "Promoções exclusivas para você" + }' | jq -r '.data.ID') + +echo "Canal criado: $NEWSLETTER_JID" + +# 2. Obter informações +curl -X POST http://localhost:4000/newsletter/info \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d "{"jid": "$NEWSLETTER_JID"}" +``` + +### 2. Inscrever-se via Link + +Para se inscrever em um canal usando um link de convite: + +1. **Obter informações do canal**: + - Use `POST /newsletter/link` com a `key` do convite + - A resposta inclui nome, descrição, contador de seguidores e o JID do canal + +2. **Inscrever-se**: + - Use `POST /newsletter/subscribe` com o JID obtido + - Se retornar status 200, a inscrição foi bem-sucedida + +### 3. Ler Mensagens Recentes + +Para buscar mensagens publicadas em um canal: + +1. Use `POST /newsletter/messages` com: + - `jid`: JID do canal + - `count`: Quantas mensagens buscar (ex: 20) + - `before_id`: ID da mensagem anterior (use 0 para as mais recentes) + +2. A resposta inclui para cada mensagem: + - `MessageServerID`: ID da mensagem + - `ViewsCount`: Número de visualizações + - `Message`: Conteúdo da mensagem + - `ReactionCounts`: Contadores de reações por emoji + +--- + +## Casos de Uso + +### 1. Empresa / Marca + +- **Lançamentos**: Anunciar novos produtos +- **Promoções**: Divulgar ofertas exclusivas +- **Novidades**: Comunicados corporativos +- **Blog**: Compartilhar artigos + +### 2. Influencer / Criador de Conteúdo + +- **Conteúdo exclusivo**: Posts para seguidores +- **Bastidores**: Fotos e vídeos dos bastidores +- **Anúncios**: Novos vídeos, lives, eventos + +### 3. Mídia / Jornalismo + +- **Notícias**: Breaking news +- **Análises**: Artigos de opinião +- **Entretenimento**: Conteúdo exclusivo + +### 4. Educação + +- **Dicas**: Conteúdo educativo +- **Aulas**: Links para aulas ao vivo +- **Materiais**: Compartilhar PDFs, links + +--- + +## Enviar Mensagens no Canal + +Para enviar mensagens no seu canal, use a **API de Mensagens** normal, passando o JID do canal: + +```bash +curl -X POST http://localhost:4000/send/text \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "120363XXXXXXXXXX@newsletter", + "text": "🔥 Promoção Relâmpago! 50% OFF em todos os produtos!" + }' +``` + +Funciona com todos os tipos de mensagem: +- Texto +- Imagem +- Vídeo +- Documento +- Localização +- Poll (enquete) + +--- + +## Limitações e Observações + +### Permissões + +- **Criar canal**: Qualquer usuário +- **Postar**: Apenas OWNER e ADMIN +- **Ver mensagens**: Todos os seguidores +- **Reagir**: Todos os seguidores (se permitido) + +### Limitações do WhatsApp + +| Aspecto | Limitação | +|---------|-----------| +| Número de seguidores | Ilimitado | +| Mensagens por dia | Não documentado | +| Tamanho da descrição | ~255 caracteres | +| Reações | Até 7 emojis configuráveis | + +### Diferenças: Newsletter vs Grupo vs Lista + +| Aspecto | Newsletter | Grupo | Lista de Transmissão | +|---------|-----------|-------|---------------------| +| Seguidores | Ilimitado | 1024 | 256 | +| Comunicação | Unidirecional | Bidirecional | Unidirecional | +| Privacidade | Anônimo | Todos veem todos | Anônimo | +| Reações | Sim | Sim | Não | +| Respostas | Não | Sim | Sim (privado) | + +--- + +## Códigos de Erro Comuns + +| Código | Erro | Solução | +|--------|------|---------| +| 400 | `name is required` | Forneça o nome do canal | +| 400 | `jid is required` | Forneça o JID do canal | +| 400 | `key is required` | Forneça o código do link | +| 500 | `instance not found` | Instância não conectada | +| 500 | `error create newsletter` | Falha ao criar (tente nome diferente) | +| 500 | `error list newsletter` | Falha ao buscar canais | + +--- + +## Boas Práticas + +### 1. Nome e Descrição Claros + +```json +{ + "name": "Tech News Daily", + "description": "Últimas notícias de tecnologia todos os dias às 9h" +} +``` + +### 2. Consistência de Postagens + +- Defina frequência (diária, semanal) +- Mantenha horários regulares +- Avise se houver pausas + +### 3. Conteúdo de Qualidade + +- Textos concisos +- Imagens de alta qualidade +- Informações relevantes +- Evite spam + +### 4. Engajamento + +- Use enquetes +- Permita reações relevantes +- Responda dúvidas (em outros canais) + +### 5. Divulgação + +Compartilhe o link do canal: +``` +https://whatsapp.com/channel/ABC123XYZ +``` + +--- + +## Próximos Passos + +- [API de Mensagens](./api-messages.md) - Enviar conteúdo no canal +- [API de Grupos](./api-groups.md) - Comparar com grupos +- [API de Comunidades](./api-community.md) - Organizar múltiplos canais +- [Visão Geral da API](./api-overview.md) + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/guias-api/api-overview.md b/docs/wiki/guias-api/api-overview.md new file mode 100644 index 0000000..978644d --- /dev/null +++ b/docs/wiki/guias-api/api-overview.md @@ -0,0 +1,342 @@ +# Visão Geral da API + +Guia completo para usar a API REST do Evolution GO. + +## Base URL + +``` +http://localhost:4000 +``` + +## Autenticação + +Todas as requisições precisam do header `apikey`: + +```bash +curl -H "apikey: SUA-CHAVE-API" http://localhost:4000/endpoint +``` + +**Tipos de API Key**: +- **GLOBAL_API_KEY**: Configurada na variável de ambiente, usada para operações administrativas (criar/deletar instâncias) +- **Token da Instância**: Definido ao criar a instância, usado para operações da instância (enviar mensagens, conectar, etc) + +## Formato das Requisições + +### Content-Type + +``` +Content-Type: application/json +``` + +### Exemplo de Requisição + +```bash +curl -X POST http://localhost:4000/instance/create \ + -H "Content-Type: application/json" \ + -H "apikey: GLOBAL_API_KEY" \ + -d '{ + "name": "teste", + "token": "token-teste-123" + }' +``` + +## Formato das Respostas + +### Sucesso (HTTP 200/201) + +```json +{ + "message": "success", + "data": { + "id": "uuid-abc-123", + "name": "teste", + "token": "token-teste-123", + "connected": false + } +} +``` + +### Erro (HTTP 4xx/5xx) + +```json +{ + "error": "Instance not found", + "message": "A instância especificada não existe" +} +``` + +## Códigos de Status HTTP + +| Código | Significado | +|--------|-------------| +| 200 | OK - Requisição bem-sucedida | +| 201 | Created - Recurso criado com sucesso | +| 400 | Bad Request - Dados inválidos | +| 401 | Unauthorized - API key inválida | +| 404 | Not Found - Recurso não encontrado | +| 500 | Internal Server Error - Erro no servidor | + +## Estrutura da API + +A API está organizada em módulos: + +### Instâncias +Gerenciar conexões WhatsApp +- `POST /instance/create` - Criar instância +- `POST /instance/connect` - Conectar via QR Code +- `GET /instance/status` - Ver status +- `DELETE /instance/delete/:id` - Deletar + +### Mensagens +Enviar e gerenciar mensagens +- `POST /send/text` - Texto simples +- `POST /send/link` - Link com preview +- `POST /send/media` - Mídia (imagem, vídeo, áudio, documento) +- `POST /send/sticker` - Sticker/figurinha +- `POST /send/location` - Localização +- `POST /send/contact` - Contato +- `POST /send/poll` - Enquete +- `POST /send/button` - Botões interativos +- `POST /send/list` - Lista de opções + +### Gerenciar Mensagens +Interagir com mensagens enviadas/recebidas +- `POST /message/react` - Reagir a mensagem +- `POST /message/markread` - Marcar como lida +- `POST /message/delete` - Deletar para todos +- `POST /message/edit` - Editar mensagem +- `POST /message/presence` - Definir presença (digitando, gravando) +- `POST /message/downloadmedia` - Baixar mídia +- `POST /message/status` - Ver status de entrega + +### Usuários +Gerenciar perfil e contatos +- `POST /user/info` - Informações do usuário +- `POST /user/check` - Verificar se número existe +- `POST /user/avatar` - Obter avatar +- `GET /user/contacts` - Listar contatos +- `GET /user/privacy` - Ver configurações de privacidade +- `POST /user/privacy` - Configurar privacidade +- `POST /user/block` - Bloquear contato +- `POST /user/unblock` - Desbloquear contato +- `GET /user/blocklist` - Ver lista de bloqueados +- `POST /user/profilePicture` - Alterar foto de perfil +- `POST /user/profileName` - Alterar nome +- `POST /user/profileStatus` - Alterar status/recado + +### Grupos +Gerenciar grupos WhatsApp +- `GET /group/list` - Listar todos os grupos +- `POST /group/create` - Criar grupo +- `POST /group/info` - Informações do grupo +- `POST /group/invitelink` - Obter link de convite +- `POST /group/photo` - Alterar foto do grupo +- `POST /group/name` - Alterar nome +- `POST /group/description` - Alterar descrição +- `POST /group/participant` - Gerenciar participantes (adicionar/remover/promover) +- `POST /group/join` - Entrar via link +- `POST /group/leave` - Sair do grupo + +### Chats +Gerenciar conversas +- `POST /chat/pin` - Fixar conversa +- `POST /chat/unpin` - Desfixar conversa +- `POST /chat/archive` - Arquivar conversa +- `POST /chat/unarchive` - Desarquivar +- `POST /chat/mute` - Silenciar notificações +- `POST /chat/unmute` - Reativar notificações +- `POST /chat/history-sync` - Solicitar sincronização de histórico + +### Labels (Etiquetas) +Organizar conversas com etiquetas +- `POST /label/chat` - Adicionar etiqueta a chat +- `POST /label/message` - Adicionar etiqueta a mensagem +- `POST /label/edit` - Criar/editar etiqueta +- `GET /label/list` - Listar todas as etiquetas +- `POST /unlabel/chat` - Remover etiqueta de chat +- `POST /unlabel/message` - Remover etiqueta de mensagem + +### Chamadas +Gerenciar chamadas +- `POST /call/reject` - Rejeitar chamada + +### Newsletter (Canais) +Gerenciar newsletters/canais +- `POST /newsletter/create` - Criar newsletter +- `GET /newsletter/list` - Listar newsletters +- `POST /newsletter/info` - Informações da newsletter +- `POST /newsletter/link` - Obter link de convite +- `POST /newsletter/subscribe` - Inscrever-se +- `POST /newsletter/messages` - Ver mensagens + +### Community (Comunidades) +Gerenciar comunidades +- `POST /community/create` - Criar comunidade +- `POST /community/add` - Adicionar grupo à comunidade +- `POST /community/remove` - Remover grupo da comunidade + +## Parâmetros Comuns + +### number +Número do WhatsApp (DDI + DDD + Número) +- Formato: Apenas dígitos +- Exemplo: `"5511999999999"` (Brasil) +- Exemplo: `"1234567890"` (EUA) + +## Formato de Números + +### Número Individual +```json +{ + "number": "5511999999999" +} +``` + +### Grupo +```json +{ + "number": "120363XXXXXXXXXX@g.us" +} +``` + +O Evolution GO formata automaticamente números quando necessário. + +## Paginação + +Endpoints que retornam listas suportam paginação: + +```bash +GET /endpoint?page=1&limit=50 +``` + +## WebSocket + +Para receber eventos em tempo real via WebSocket: + +``` +ws://localhost:4000/ws?token=SUA-CHAVE-API&instanceId=minha-instancia +``` + +## Webhooks + +Configure webhooks via variável de ambiente: + +```env +WEBHOOK_URL=https://seu-servidor.com/webhook +``` + +Eventos serão enviados via POST para a URL configurada. + +## Rate Limiting + +Atualmente não há rate limiting configurado, mas é recomendado: +- Máximo 50 requisições por segundo por instância +- Aguarde resposta antes de enviar próxima mensagem + +## Swagger/OpenAPI + +Documentação interativa disponível em: + +``` +http://localhost:4000/swagger/index.html +``` + +Recursos do Swagger: +- Testar endpoints diretamente +- Ver todos os parâmetros +- Exemplos de request/response +- Autenticação integrada + +## Exemplos Práticos + +### Criar e Conectar Instância + +```bash +# 1. Criar instância (usa GLOBAL_API_KEY) +curl -X POST http://localhost:4000/instance/create \ + -H "Content-Type: application/json" \ + -H "apikey: GLOBAL_API_KEY" \ + -d '{ + "name": "vendas", + "token": "token-vendas-123" + }' + +# 2. Conectar (usa token da instância) +curl -X POST http://localhost:4000/instance/connect \ + -H "Content-Type: application/json" \ + -H "apikey: token-vendas-123" \ + -d '{ + "webhookUrl": "https://meu-servidor.com/webhook" + }' + +# 3. Ver QR Code (usa token da instância) +curl -X GET http://localhost:4000/instance/qr \ + -H "apikey: token-vendas-123" +``` + +### Enviar Mensagem com Mídia + +```bash +curl -X POST http://localhost:4000/send/media \ + -H "Content-Type: application/json" \ + -H "apikey: token-vendas-123" \ + -d '{ + "number": "5511999999999", + "url": "https://exemplo.com/produto.jpg", + "type": "image", + "caption": "Confira nosso produto!" + }' +``` + +### Criar Grupo + +```bash +curl -X POST http://localhost:4000/group/create \ + -H "Content-Type: application/json" \ + -H "apikey: token-vendas-123" \ + -d '{ + "name": "Equipe de Vendas", + "participants": ["5511999999999", "5511888888888"] + }' +``` + +## Boas Práticas + +### 1. Validar Números +Use `/user/check` para verificar se número existe no WhatsApp + +### 2. Gerenciar Erros +Sempre trate erros HTTP 4xx e 5xx + +### 3. Usar Webhooks +Para receber mensagens, configure webhooks em vez de polling + +### 4. Múltiplas Instâncias +Use uma instância por número WhatsApp + +### 5. Logs +Configure logs adequadamente para debug + +## Troubleshooting + +### Erro 401 Unauthorized +Verifique se a `apikey` está correta + +### Erro 404 Instance not found +Certifique-se de que criou a instância primeiro + +### Mensagem não enviada +1. Verifique status da conexão +2. Confirme formato do número +3. Verifique se número existe no WhatsApp + +## Próximos Passos + +- [API de Instâncias](./api-instances.md) - Gerenciar instâncias +- [API de Mensagens](./api-messages.md) - Enviar mensagens +- [API de Grupos](./api-groups.md) - Gerenciar grupos +- [Sistema de Eventos](../recursos-avancados/events-system.md) - Webhooks e eventos + +--- + +**Dica**: Use o Swagger para explorar todos os endpoints disponíveis! diff --git a/docs/wiki/guias-api/api-user.md b/docs/wiki/guias-api/api-user.md new file mode 100644 index 0000000..748b301 --- /dev/null +++ b/docs/wiki/guias-api/api-user.md @@ -0,0 +1,755 @@ +# API de Usuários + +Documentação completa dos endpoints para gerenciar perfil, contatos e privacidade. + +## 📋 Índice + +- [Informações do Usuário](#informações-do-usuário) +- [Verificar Usuário no WhatsApp](#verificar-usuário-no-whatsapp) +- [Avatar do Usuário](#avatar-do-usuário) +- [Listar Contatos](#listar-contatos) +- [Privacidade](#privacidade) + - [Consultar Privacidade](#consultar-privacidade) + - [Configurar Privacidade](#configurar-privacidade) +- [Bloqueio de Contatos](#bloqueio-de-contatos) + - [Bloquear Contato](#bloquear-contato) + - [Desbloquear Contato](#desbloquear-contato) + - [Listar Bloqueados](#listar-bloqueados) +- [Perfil](#perfil) + - [Alterar Foto de Perfil](#alterar-foto-de-perfil) + - [Alterar Nome](#alterar-nome) + - [Alterar Status/Recado](#alterar-statusrecado) + +--- + +## Informações do Usuário + +Obtém informações detalhadas de um ou mais usuários WhatsApp. + +**Endpoint**: `POST /user/info` + +**Headers**: +``` +Content-Type: application/json +apikey: SUA-CHAVE-API +``` + +**Body**: +```json +{ + "number": ["5511999999999", "5511888888888"] +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | array | ✅ Sim | Array de números a consultar | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Users": { + "5511999999999@s.whatsapp.net": { + "VerifiedName": { + "Certificate": {...}, + "Details": { + "Serial": 123, + "Issuer": "WhatsApp", + "VerifiedName": "Empresa Verificada LTDA" + } + }, + "Status": "Olá! Estou usando WhatsApp.", + "PictureID": "abc123", + "Devices": ["5511999999999.0:1@s.whatsapp.net"], + "LID": "lid_string" + } + } + } +} +``` + +**Campos da Resposta**: +- `VerifiedName`: Nome verificado (empresas) ou null +- `Status`: Recado/status do usuário +- `PictureID`: ID da foto de perfil +- `Devices`: Lista de dispositivos conectados +- `LID`: Local ID (se disponível) + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/info \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": ["5511999999999"] + }' +``` + +--- + +## Verificar Usuário no WhatsApp + +Verifica se um número existe no WhatsApp e retorna o JID correto para mensagens. + +**Endpoint**: `POST /user/check` + +**Body**: +```json +{ + "number": ["5511999999999", "11999999999", "+55 11 99999-9999"], + "formatJid": false +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | array | ✅ Sim | Array de números em qualquer formato | +| `formatJid` | bool | ❌ Não | Formatar número (padrão: false) | + +**Nota Importante**: Por padrão, `formatJid=false` para verificação. O sistema tenta automaticamente ambos os formatos se o primeiro falhar. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "Users": [ + { + "Query": "5511999999999", + "IsInWhatsapp": true, + "JID": "5511999999999@s.whatsapp.net", + "RemoteJID": "5511999999999@s.whatsapp.net", + "LID": "lid_string", + "VerifiedName": "Empresa LTDA" + }, + { + "Query": "5511888888888", + "IsInWhatsapp": false, + "JID": "", + "RemoteJID": "5511888888888", + "LID": null, + "VerifiedName": "" + } + ] + } +} +``` + +**Campos da Resposta**: +- `Query`: Número original consultado +- `IsInWhatsapp`: Se existe no WhatsApp +- `JID`: JID do usuário (vazio se não existe) +- `RemoteJID`: JID recomendado para envio de mensagens +- `LID`: Local ID +- `VerifiedName`: Nome verificado (empresas) + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/check \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": ["5511999999999", "11888888888"] + }' +``` + +--- + +## Avatar do Usuário + +Obtém a URL da foto de perfil de um usuário. + +**Endpoint**: `POST /user/avatar` + +**Body**: +```json +{ + "number": "5511999999999", + "preview": false +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do usuário | +| `preview` | bool | ❌ Não | Se true, retorna preview (menor resolução) | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "URL": "https://pps.whatsapp.net/v/...", + "ID": "abc123", + "Type": "image", + "DirectPath": "/v/..." + } +} +``` + +**Resposta de Erro (500)**: +```json +{ + "error": "no profile picture found" +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/avatar \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999", + "preview": true + }' +``` + +--- + +## Listar Contatos + +Obtém todos os contatos salvos na conta WhatsApp. + +**Endpoint**: `GET /user/contacts` + +**Headers**: +``` +apikey: SUA-CHAVE-API +``` + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": [ + { + "Jid": "5511999999999@s.whatsapp.net", + "Found": true, + "FirstName": "João", + "FullName": "João Silva", + "PushName": "João", + "BusinessName": "" + }, + { + "Jid": "5511888888888@s.whatsapp.net", + "Found": true, + "FirstName": "Maria", + "FullName": "Maria Santos", + "PushName": "Maria", + "BusinessName": "Loja da Maria" + } + ] +} +``` + +**Campos da Resposta**: +- `Jid`: JID do contato +- `Found`: Se foi encontrado no WhatsApp +- `FirstName`: Primeiro nome +- `FullName`: Nome completo +- `PushName`: Nome exibido no WhatsApp +- `BusinessName`: Nome da empresa (se for conta comercial) + +**Exemplo cURL**: +```bash +curl -X GET http://localhost:4000/user/contacts \ + -H "apikey: SUA-CHAVE-API" +``` + +--- + +## Privacidade + +### Consultar Privacidade + +Obtém as configurações atuais de privacidade da conta. + +**Endpoint**: `GET /user/privacy` + +**Headers**: +``` +apikey: SUA-CHAVE-API +``` + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "GroupAdd": "all", + "LastSeen": "contacts", + "Status": "contacts", + "Profile": "all", + "ReadReceipts": "all", + "CallAdd": "all", + "Online": "all" + } +} +``` + +**Valores Possíveis**: +- `all` - Todos +- `contacts` - Apenas contatos +- `contact_blacklist` - Meus contatos exceto... +- `none` - Ninguém +- `match_last_seen` - Mesmo de "Visto por último" + +**Exemplo cURL**: +```bash +curl -X GET http://localhost:4000/user/privacy \ + -H "apikey: SUA-CHAVE-API" +``` + +--- + +### Configurar Privacidade + +Define as configurações de privacidade da conta. + +**Endpoint**: `POST /user/privacy` + +**Body**: +```json +{ + "groupAdd": "contacts", + "lastSeen": "contacts", + "status": "contacts", + "profile": "all", + "readReceipts": "all", + "callAdd": "all", + "online": "all" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `groupAdd` | string | ✅ Sim | Quem pode me adicionar em grupos | +| `lastSeen` | string | ✅ Sim | Quem vê meu "visto por último" | +| `status` | string | ✅ Sim | Quem vê meu recado/status | +| `profile` | string | ✅ Sim | Quem vê minha foto de perfil | +| `readReceipts` | string | ✅ Sim | Confirmações de leitura | +| `callAdd` | string | ✅ Sim | Quem pode me ligar | +| `online` | string | ✅ Sim | Quem vê quando estou online | + +**Valores Permitidos**: `all`, `contacts`, `contact_blacklist`, `none`, `match_last_seen` + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "GroupAdd": "contacts", + "LastSeen": "contacts", + "Status": "contacts", + "Profile": "all", + "ReadReceipts": "all", + "CallAdd": "all", + "Online": "all" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/privacy \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupAdd": "contacts", + "lastSeen": "contacts", + "status": "contacts", + "profile": "all", + "readReceipts": "all", + "callAdd": "all", + "online": "all" + }' +``` + +--- + +## Bloqueio de Contatos + +### Bloquear Contato + +Bloqueia um contato no WhatsApp. + +**Endpoint**: `POST /user/block` + +**Body**: +```json +{ + "number": "5511999999999" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do contato a bloquear | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "DHash": "abc123", + "PrevDHash": "def456", + "Modifications": [ + { + "JID": "5511999999999@s.whatsapp.net", + "Action": "block" + } + ] + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/block \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999" + }' +``` + +--- + +### Desbloquear Contato + +Desbloqueia um contato previamente bloqueado. + +**Endpoint**: `POST /user/unblock` + +**Body**: +```json +{ + "number": "5511999999999" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `number` | string | ✅ Sim | Número do contato a desbloquear | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "DHash": "abc123", + "PrevDHash": "def456", + "Modifications": [ + { + "JID": "5511999999999@s.whatsapp.net", + "Action": "unblock" + } + ] + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/unblock \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999" + }' +``` + +--- + +### Listar Bloqueados + +Obtém a lista de todos os contatos bloqueados. + +**Endpoint**: `GET /user/blocklist` + +**Headers**: +``` +apikey: SUA-CHAVE-API +``` + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "DHash": "abc123", + "Modifications": [ + { + "JID": "5511999999999@s.whatsapp.net", + "Action": "block" + }, + { + "JID": "5511888888888@s.whatsapp.net", + "Action": "block" + } + ] + } +} +``` + +**Exemplo cURL**: +```bash +curl -X GET http://localhost:4000/user/blocklist \ + -H "apikey: SUA-CHAVE-API" +``` + +--- + +## Perfil + +### Alterar Foto de Perfil + +Define a foto de perfil da conta WhatsApp. + +**Endpoint**: `POST /user/profilePicture` + +**Body**: +```json +{ + "image": "https://exemplo.com/foto.jpg" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `image` | string | ✅ Sim | URL da imagem | + +**Nota**: A imagem deve ser acessível via HTTP/HTTPS. Formatos aceitos: JPG, PNG. + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "image": "https://exemplo.com/foto.jpg" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/profilePicture \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "image": "https://exemplo.com/minha-foto.jpg" + }' +``` + +--- + +### Alterar Nome + +Define o nome de exibição da conta WhatsApp. + +**Endpoint**: `POST /user/profileName` + +**Body**: +```json +{ + "name": "João Silva" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `name` | string | ✅ Sim | Novo nome de exibição | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "name": "João Silva" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/profileName \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "name": "Meu Novo Nome" + }' +``` + +--- + +### Alterar Status/Recado + +Define o recado (status) da conta WhatsApp. + +**Endpoint**: `POST /user/profileStatus` + +**Body**: +```json +{ + "status": "Disponível para atendimento 24h!" +} +``` + +**Parâmetros**: + +| Campo | Tipo | Obrigatório | Descrição | +|-------|------|-------------|-----------| +| `status` | string | ✅ Sim | Novo recado/status | + +**Resposta de Sucesso (200)**: +```json +{ + "message": "success", + "data": { + "status": "Disponível para atendimento 24h!" + } +} +``` + +**Exemplo cURL**: +```bash +curl -X POST http://localhost:4000/user/profileStatus \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "status": "Olá! Como posso ajudar?" + }' +``` + +--- + +## Casos de Uso Comuns + +### Validar Números Antes de Enviar + +Sempre verifique se o número existe antes de tentar enviar mensagem: + +```bash +# 1. Verificar número +curl -X POST http://localhost:4000/user/check \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": ["5511999999999"] + }' + +# 2. Se IsInWhatsapp=true, use RemoteJID para enviar +curl -X POST http://localhost:4000/send/text \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "number": "5511999999999@s.whatsapp.net", + "text": "Olá!", + "formatJid": false + }' +``` + +### Configurar Privacidade Máxima + +```bash +curl -X POST http://localhost:4000/user/privacy \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{ + "groupAdd": "contacts", + "lastSeen": "none", + "status": "contacts", + "profile": "contacts", + "readReceipts": "all", + "callAdd": "contacts", + "online": "none" + }' +``` + +### Personalizar Perfil Completo + +```bash +# 1. Foto de perfil +curl -X POST http://localhost:4000/user/profilePicture \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"image": "https://exemplo.com/logo.jpg"}' + +# 2. Nome +curl -X POST http://localhost:4000/user/profileName \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"name": "Empresa LTDA"}' + +# 3. Status +curl -X POST http://localhost:4000/user/profileStatus \ + -H "Content-Type: application/json" \ + -H "apikey: SUA-CHAVE-API" \ + -d '{"status": "Atendimento 24h - (11) 99999-9999"}' +``` + +--- + +## Códigos de Erro Comuns + +| Código | Erro | Solução | +|--------|------|---------| +| 400 | `phone number is required` | Forneça o campo `number` | +| 400 | `image is required` | Forneça uma URL de imagem válida | +| 500 | `instance not found` | Instância não conectada | +| 500 | `no profile picture found` | Usuário não tem foto de perfil | +| 500 | `invalid phone number` | Formato de número inválido | + +--- + +## Boas Práticas + +### 1. Cache de Verificações +Evite verificar o mesmo número múltiplas vezes. Implemente um sistema de cache na sua aplicação: +- Armazene o resultado da verificação por algumas horas +- Antes de chamar a API, verifique se já tem o resultado em cache +- Isso reduz requisições desnecessárias e melhora a performance + +### 2. Privacidade Responsável +Configure privacidade adequada para contas comerciais: +- `readReceipts: all` - Envie confirmações de leitura +- `online: contacts` - Evite mostrar online para todos +- `groupAdd: contacts` - Evite spam de grupos + +### 3. Validação de Imagens +Ao alterar foto de perfil, certifique-se que a imagem: +- Está acessível publicamente (HTTP/HTTPS) +- É JPG ou PNG +- Tem tamanho adequado (recomendado: 640x640px) + +--- + +## Próximos Passos + +- [API de Mensagens](./api-messages.md) - Enviar e gerenciar mensagens +- [API de Grupos](./api-groups.md) - Gerenciar grupos WhatsApp +- [API de Chats](./api-chats.md) - Gerenciar conversas +- [Visão Geral da API](./api-overview.md) + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/recursos-avancados/events-system.md b/docs/wiki/recursos-avancados/events-system.md new file mode 100644 index 0000000..ef65300 --- /dev/null +++ b/docs/wiki/recursos-avancados/events-system.md @@ -0,0 +1,1046 @@ +# Sistema de Eventos + +Sistema completo de notificações em tempo real do Evolution GO. Receba eventos do WhatsApp através de múltiplos canais: Webhooks, RabbitMQ, NATS e WebSocket. + +## 📋 Índice + +- [Visão Geral](#visão-geral) +- [Canais Disponíveis](#canais-disponíveis) +- [Webhook](#webhook) +- [RabbitMQ](#rabbitmq) +- [NATS](#nats) +- [WebSocket](#websocket) +- [Configuração](#configuração) +- [Tipos de Eventos](#tipos-de-eventos) +- [Formato de Payload](#formato-de-payload) +- [Múltiplos Canais Simultâneos](#múltiplos-canais-simultâneos) +- [Exemplos Práticos](#exemplos-práticos) + +--- + +## Visão Geral + +O Evolution GO envia notificações de eventos do WhatsApp em tempo real através de diferentes canais de comunicação: + +- **Webhook (HTTP POST)**: Ideal para integração simples com APIs externas +- **RabbitMQ (AMQP)**: Message broker para arquiteturas empresariais e filas confiáveis +- **NATS**: Message broker leve para comunicação de alta performance +- **WebSocket**: Conexão persistente para dashboards e aplicações web + +Você pode ativar múltiplos canais simultaneamente - os eventos serão enviados para todos os canais configurados. + +### Arquitetura + +``` +┌─────────────────────────────────────────────────────────┐ +│ WhatsApp Event │ +│ (mensagem recebida) │ +└────────────────────┬────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ Whatsmeow Event Handler │ +│ (detecta evento do WhatsApp) │ +└────────────────────┬────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ Event Router/Dispatcher │ +│ (filtra eventos subscritos) │ +└─────┬──────┬──────┬──────┬────────────────────────────┘ + │ │ │ │ + │ │ │ │ + ▼ ▼ ▼ ▼ + ┌────┐ ┌────┐ ┌────┐ ┌─────┐ + │Web │ │AMQP│ │NATS│ │Web │ + │hook│ │MQ │ │ │ │Socket│ + └─┬──┘ └─┬──┘ └─┬──┘ └──┬──┘ + │ │ │ │ + │ │ │ │ + ▼ ▼ ▼ ▼ + ┌────┐ ┌────┐ ┌────┐ ┌─────┐ + │HTTP│ │Queue│ │Topic│ │WS │ + │POST│ │ │ │ │ │Conn │ + └────┘ └────┘ └────┘ └─────┘ +``` + +--- + +## Canais Disponíveis + +### Comparação de Canais + +| Produtor | Latência | Throughput | Persistência | Complexidade | Caso de Uso | +|----------|----------|------------|--------------|--------------|-------------| +| **Webhook** | Baixa | Média | Não | Baixa | Integração simples com APIs | +| **RabbitMQ** | Média | Alta | Sim | Alta | Arquiteturas distribuídas, filas | +| **NATS** | Muito Baixa | Muito Alta | Opcional | Média | Real-time, pub/sub, microserviços | +| **WebSocket** | Muito Baixa | Alta | Não | Média | Aplicações web, dashboards | + +--- + +## Webhook + +### Visão Geral + +Envia eventos via HTTP POST para uma URL que você configurar. É o método mais simples para integrar o Evolution GO com suas aplicações. + +### Características + +- **Retry automático**: 5 tentativas com intervalo de 30 segundos entre cada tentativa +- **Timeout**: Configurável +- **Content-Type**: `application/json` +- **Método**: HTTP POST + +### Configuração + +**Variáveis de Ambiente**: +```env +# Webhook global (recebe eventos de todas as instâncias) +WEBHOOK_URL=https://meu-servidor.com/webhook +``` + +**Por instância** (via Connect): +```bash +curl -X POST http://localhost:4000/instance/connect \ + -H "apikey: token-da-instancia" \ + -H "Content-Type: application/json" \ + -d '{ + "webhookUrl": "https://meu-servidor.com/webhook-vendas", + "subscribe": ["MESSAGE", "READ_RECEIPT", "GROUP", "CALL"], + "rabbitmqEnabled": "disabled", + "websocketEnable": "disabled", + "natsEnabled": "disabled" + }' +``` + +> **Nota**: A instância é identificada pelo token no header `apikey`, não por `instanceName` no body. + +### Funcionamento + +Quando um evento ocorre no WhatsApp: + +1. **Webhook Global**: Se configurado via `WEBHOOK_URL`, todos os eventos são enviados para esta URL +2. **Webhook por Instância**: Se configurado no `POST /instance/connect`, eventos daquela instância vão para a URL específica +3. **Retry Automático**: Se a requisição falhar, o Evolution GO tenta novamente até 5 vezes +4. **Intervalo**: 30 segundos entre cada tentativa + +### Requisição HTTP + +**Headers**: +``` +POST /webhook HTTP/1.1 +Host: meu-servidor.com +Content-Type: application/json +``` + +**Body**: +```json +{ + "event": "MESSAGE", + "instance": "vendas", + "data": { + "key": { + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": false, + "id": "3EB0C5A277F7F9B6C599" + }, + "message": { + "conversation": "Olá!" + }, + "messageTimestamp": "1699999999" + } +} +``` + +### Implementação no Servidor Receptor + +**Node.js (Express)**: +```javascript +const express = require('express'); +const app = express(); + +app.use(express.json()); + +app.post('/webhook', (req, res) => { + const { event, instance, data } = req.body; + + console.log(`Evento recebido: ${event} da instância ${instance}`); + console.log('Dados:', JSON.stringify(data, null, 2)); + + // Processa evento + if (event === 'MESSAGE') { + const message = data.message.conversation; + const from = data.key.remoteJid; + console.log(`Mensagem de ${from}: ${message}`); + } + + // IMPORTANTE: Retorne 200 OK rapidamente + res.status(200).json({ received: true }); +}); + +app.listen(3000, () => console.log('Webhook server rodando na porta 3000')); +``` + +**Python (Flask)**: +```python +from flask import Flask, request, jsonify + +app = Flask(__name__) + +@app.route('/webhook', methods=['POST']) +def webhook(): + data = request.json + event = data.get('event') + instance = data.get('instance') + payload = data.get('data') + + print(f"Evento recebido: {event} da instância {instance}") + + if event == 'MESSAGE': + message = payload.get('message', {}).get('conversation') + from_jid = payload.get('key', {}).get('remoteJid') + print(f"Mensagem de {from_jid}: {message}") + + return jsonify({'received': True}), 200 + +if __name__ == '__main__': + app.run(port=3000) +``` + +--- + +## RabbitMQ + +### Visão Geral + +Publica eventos em filas RabbitMQ (AMQP). Ideal para arquiteturas distribuídas que precisam de filas confiáveis e persistentes. + +### Características + +- **Filas duráveis**: Mensagens não se perdem mesmo após reinicialização do servidor +- **Alta disponibilidade**: Replicação automática entre nós +- **Retry automático**: 3 tentativas com intervalo crescente +- **Confirmações de entrega**: Garantia de que a mensagem foi recebida +- **Heartbeat**: Monitoramento de conexão a cada 30 segundos +- **Reconexão automática**: Reconecta automaticamente em caso de falha + +### Configuração + +**Variáveis de Ambiente**: +```env +# URL de conexão RabbitMQ +AMQP_URL=amqp://user:password@localhost:5672/ + +# Habilitar RabbitMQ global +AMQP_GLOBAL_ENABLED=true + +# Eventos globais (modo fallback) +AMQP_GLOBAL_EVENTS=MESSAGE,SEND_MESSAGE,GROUP,CALL + +# Eventos específicos (prioridade sobre global) +AMQP_SPECIFIC_EVENTS=message,sendmessage,groupinfo,calloffer +``` + +### Tipos de Filas + +#### Modo 1: AMQP_SPECIFIC_EVENTS (Recomendado) + +Cria filas específicas para eventos exatos: + +```env +AMQP_SPECIFIC_EVENTS=message,sendmessage,receipt,presence +``` + +**Filas criadas**: +- `message` - Mensagens recebidas +- `sendmessage` - Mensagens enviadas +- `receipt` - Confirmações de leitura +- `presence` - Status online/offline + +#### Modo 2: AMQP_GLOBAL_EVENTS (Fallback) + +Mapeia eventos globais para múltiplas filas: + +```env +AMQP_GLOBAL_EVENTS=MESSAGE,CALL,CONNECTION +``` + +**Mapeamento de Eventos**: +- `MESSAGE` → fila `message` +- `SEND_MESSAGE` → fila `sendmessage` +- `READ_RECEIPT` → fila `receipt` +- `PRESENCE` → fila `presence` +- `CALL` → filas `calloffer`, `callaccept`, `callterminate` +- `CONNECTION` → filas `connected`, `disconnected`, `loggedout` +- `GROUP` → filas `groupinfo`, `joinedgroup` +- `QRCODE` → filas `qrcode`, `qrtimeout`, `qrsuccess` + +### Propriedades das Filas + +As filas RabbitMQ criadas pelo Evolution GO são configuradas com: + +- **Quorum queues**: Replicação automática para alta disponibilidade +- **Durabilidade**: Mensagens persistem após restart do servidor +- **Persistência**: Todas as mensagens são marcadas como persistentes + +### Consumindo Mensagens + +**Go (amqp091-go)**: +```go +package main + +import ( + "fmt" + "log" + amqp "github.com/rabbitmq/amqp091-go" +) + +func main() { + conn, err := amqp.Dial("amqp://user:password@localhost:5672/") + if err != nil { + log.Fatal(err) + } + defer conn.Close() + + ch, err := conn.Channel() + if err != nil { + log.Fatal(err) + } + defer ch.Close() + + msgs, err := ch.Consume( + "message", // queue + "", // consumer + true, // auto-ack + false, // exclusive + false, // no-local + false, // no-wait + nil, // args + ) + if err != nil { + log.Fatal(err) + } + + forever := make(chan bool) + + go func() { + for d := range msgs { + fmt.Printf("Recebido: %s +", d.Body) + } + }() + + fmt.Println("Aguardando mensagens...") + <-forever +} +``` + +**Python (pika)**: +```python +import pika +import json + +connection = pika.BlockingConnection( + pika.ConnectionParameters('localhost')) +channel = connection.channel() + +def callback(ch, method, properties, body): + data = json.loads(body) + print(f"Evento recebido: {data}") + + if data.get('event') == 'MESSAGE': + message = data.get('data', {}).get('message', {}).get('conversation') + print(f"Mensagem: {message}") + +channel.basic_consume(queue='message', on_message_callback=callback, auto_ack=True) + +print('Aguardando mensagens...') +channel.start_consuming() +``` + +--- + +## NATS + +### Visão Geral + +Publica eventos em tópicos NATS. Ideal para comunicação em tempo real com latência mínima. + +### Características + +- **Latência ultra-baixa**: Comunicação extremamente rápida +- **Pub/Sub nativo**: Vários consumidores podem receber o mesmo evento +- **Leve e rápido**: Menor overhead que RabbitMQ +- **Clustering**: Suporte nativo a clusters distribuídos + +### Configuração + +```env +# URL de conexão NATS +NATS_URL=nats://localhost:4222 + +# Habilitar NATS +NATS_ENABLED=true +``` + +### Tópicos + +Eventos são publicados em tópicos no formato: + +``` +evolution.{instance}.{event_type} +``` + +**Exemplos**: +- `evolution.vendas.message` - Mensagens da instância "vendas" +- `evolution.suporte.calloffer` - Chamadas da instância "suporte" +- `evolution.*.message` - Mensagens de todas as instâncias (wildcard) + +### Consumindo Eventos + +**Go (nats.go)**: +```go +package main + +import ( + "fmt" + "log" + "github.com/nats-io/nats.go" +) + +func main() { + nc, err := nats.Connect("nats://localhost:4222") + if err != nil { + log.Fatal(err) + } + defer nc.Close() + + // Subscrever a eventos de mensagens de todas as instâncias + sub, err := nc.Subscribe("evolution.*.message", func(m *nats.Msg) { + fmt.Printf("Recebido no tópico %s: %s +", m.Subject, string(m.Data)) + }) + if err != nil { + log.Fatal(err) + } + defer sub.Unsubscribe() + + // Manter rodando + select {} +} +``` + +--- + +## WebSocket + +### Visão Geral + +Envia eventos através de uma conexão WebSocket persistente. Ideal para dashboards e aplicações web que precisam de atualizações em tempo real. + +### Características + +- **Conexão bidirecional**: Comunicação em duas vias +- **Baixa latência**: Perfeito para interfaces em tempo real +- **Gerenciamento seguro**: Múltiplas conexões simultâneas +- **Dois modos**: Broadcast (todos os eventos) ou específico por instância + +### Tipos de Conexão + +#### 1. Conexão Específica (Por Instância) + +Recebe apenas eventos de uma instância: + +``` +ws://localhost:4000/ws?token=TOKEN_DA_INSTANCIA&instanceId=vendas +``` + +#### 2. Conexão Broadcast + +Recebe eventos de **todas as instâncias**: + +``` +ws://localhost:4000/ws?token=GLOBAL_API_KEY +``` + +### Gerenciamento de Conexões + +O Evolution GO gerencia automaticamente as conexões WebSocket: + +- **Conexões específicas**: Cada instância pode ter sua própria conexão +- **Conexões broadcast**: Recebem eventos de todas as instâncias +- **Desconexão automática**: Detecta e remove conexões inativas +- **Thread-safe**: Múltiplas conexões podem ser gerenciadas simultaneamente + +### Cliente JavaScript + +```javascript +// Conectar a instância específica +const token = 'token-da-instancia-vendas'; +const instanceId = 'vendas'; +const ws = new WebSocket(`ws://localhost:4000/ws?token=${token}&instanceId=${instanceId}`); + +ws.onopen = () => { + console.log('WebSocket conectado!'); +}; + +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + console.log('Evento recebido:', data.queue); + console.log('Payload:', JSON.parse(data.payload)); + + if (data.queue === 'message') { + const message = JSON.parse(data.payload); + console.log('Nova mensagem:', message.data.message.conversation); + } +}; + +ws.onerror = (error) => { + console.error('Erro no WebSocket:', error); +}; + +ws.onclose = () => { + console.log('WebSocket desconectado'); + // Reconectar após 5 segundos + setTimeout(() => { + console.log('Reconectando...'); + // Criar nova conexão + }, 5000); +}; +``` + +### Cliente Python + +```python +import asyncio +import websockets +import json + +async def listen_events(): + uri = "ws://localhost:4000/ws?token=TOKEN&instanceId=vendas" + + async with websockets.connect(uri) as websocket: + print("WebSocket conectado!") + + async for message in websocket: + data = json.loads(message) + queue = data.get('queue') + payload = json.loads(data.get('payload')) + + print(f"Evento: {queue}") + + if queue == 'message': + msg_text = payload.get('data', {}).get('message', {}).get('conversation') + print(f"Mensagem recebida: {msg_text}") + +asyncio.run(listen_events()) +``` + +--- + +## Configuração + +### Exemplo Completo (.env) + +```env +# ===== WEBHOOK ===== +WEBHOOK_URL=https://meu-servidor.com/webhook-global + +# ===== RABBITMQ ===== +AMQP_URL=amqp://admin:password@rabbitmq:5672/ +AMQP_GLOBAL_ENABLED=true +AMQP_SPECIFIC_EVENTS=message,sendmessage,receipt,presence,calloffer + +# ===== NATS ===== +NATS_URL=nats://nats:4222 +NATS_ENABLED=true + +# ===== WEBSOCKET ===== +# WebSocket é habilitado automaticamente +# Acesse: ws://localhost:4000/ws +``` + +### Configuração por Instância + +```bash +curl -X POST http://localhost:4000/instance/connect \ + -H "apikey: token-da-instancia-vendas" \ + -H "Content-Type: application/json" \ + -d '{ + "webhookUrl": "https://meu-servidor.com/webhook-vendas", + "subscribe": ["MESSAGE", "GROUP", "CALL"], + "rabbitmqEnabled": "enabled", + "websocketEnable": "disabled", + "natsEnabled": "enabled" + }' +``` + +**Comportamento**: +- `rabbitmqEnabled: "enabled"` ou `"disabled"` - Habilita/desabilita RabbitMQ para esta instância +- `websocketEnable: "disabled"` ou outro valor - Habilita/desabilita WebSocket +- `natsEnabled: "enabled"` ou `"disabled"` - Habilita/desabilita NATS +- `webhookUrl` - URL específica para esta instância +- `subscribe` - Array com categorias de eventos: `MESSAGE`, `READ_RECEIPT`, `PRESENCE`, `HISTORY_SYNC`, `CHAT_PRESENCE`, `CALL`, `CONNECTION`, `QRCODE`, `LABEL`, `CONTACT`, `GROUP`, `NEWSLETTER`, ou `ALL` + +--- + +## Tipos de Eventos + +### Categorias vs Eventos Individuais + +O Evolution GO usa dois níveis de classificação de eventos: + +**Categorias de Eventos** (usadas no `subscribe`): +- São escritas em **MAIÚSCULAS**: `MESSAGE`, `GROUP`, `CALL`, etc. +- Agrupam múltiplos eventos relacionados +- Usadas para filtrar quais categorias você quer receber no `subscribe` + +**Eventos Individuais** (nomes dos eventos emitidos): +- São escritos em **minúsculas**: `message`, `groupinfo`, `calloffer`, etc. +- São os eventos específicos que você receberá no webhook/fila +- Cada categoria pode gerar múltiplos eventos individuais + +**Exemplo de mapeamento**: + +| Categoria (`subscribe`) | Eventos Individuais Emitidos | +|------------------------|------------------------------| +| `MESSAGE` | `Message` (evento recebido no webhook) | +| `SEND_MESSAGE` | `SendMessage` | +| `READ_RECEIPT` | `Receipt` | +| `GROUP` | `GroupInfo`, `JoinedGroup` | +| `CALL` | `CallOffer`, `CallAccept`, `CallTerminate` | +| `CONNECTION` | `Connected`, `Disconnected`, `LoggedOut` | +| `QRCODE` | `PairSuccess`, `Disconnected` (com QR) | +| `ALL` | Todos os eventos | + +**Exemplo prático**: +```json +// No connect, você filtra por categoria: +{ + "subscribe": ["MESSAGE", "GROUP", "CALL"] +} + +// No webhook, você recebe o evento individual: +{ + "event": "Message", // ou "GroupInfo", "CallOffer", etc + "data": { ... } +} +``` + +### Eventos de Mensagens + +**Categoria**: `MESSAGE` e `SEND_MESSAGE` + +- `Message` - Mensagem recebida +- `SendMessage` - Mensagem enviada +- `Receipt` - Confirmação de leitura (`READ_RECEIPT`) +- Reações, edições, deleções de mensagens + +### Eventos de Grupos + +**Categoria**: `GROUP` + +- `GroupInfo` - Informações do grupo atualizadas (nome, descrição, participantes) +- `JoinedGroup` - Bot adicionado a um grupo + +### Eventos de Chamadas + +**Categoria**: `CALL` + +- `CallOffer` - Chamada recebida +- `CallAccept` - Chamada aceita +- `CallTerminate` - Chamada encerrada + +### Eventos de Conexão + +**Categoria**: `CONNECTION` + +- `Connected` - Instância conectada com sucesso +- `Disconnected` - Instância desconectada +- `LoggedOut` - Logout realizado (por outra sessão ou WhatsApp) +- `TemporaryBan` - Conta temporariamente banida + +### Eventos de QR Code + +**Categoria**: `QRCODE` + +- `PairSuccess` - QR Code escaneado com sucesso +- `Disconnected` - Desconectado (pode incluir informações de QR) + +### Eventos de Presença + +**Categoria**: `PRESENCE` e `CHAT_PRESENCE` + +- `Presence` - Status online/offline de contato +- `ChatPresence` - Digitando/gravando áudio + +### Eventos de Contatos + +**Categoria**: `CONTACT` + +- `Contact` - Informações de contato atualizadas +- `PushName` - Nome do contato alterado + +### Eventos de Labels + +**Categoria**: `LABEL` + +- `LabelEdit` - Label criada/editada/deletada +- `LabelAssociationChat` - Label associada a chat +- `LabelAssociationMessage` - Label associada a mensagem + +### Eventos de Newsletter + +**Categoria**: `NEWSLETTER` + +- `NewsletterJoin` - Inscrito em newsletter +- `NewsletterLeave` - Saiu de newsletter + +### Sincronização de Histórico + +**Categoria**: `HISTORY_SYNC` + +- `HistorySync` - Sincronização de histórico do telefone +- `OfflineSyncCompleted` - Sincronização offline concluída + +--- + +## Formato de Payload + +> **📚 Exemplos Detalhados de Webhooks** +> +> Para exemplos completos de JSON de todos os eventos de webhook, consulte nossa documentação detalhada: +> +> 🔗 **[Webhook - Exemplos Completos (Notion)](https://atendai.notion.site/Webhook-11b50bf742da80d99acafe4d92ccd054?pvs=74)** +> +> Este guia contém exemplos reais de payload para todos os tipos de eventos, incluindo mensagens de texto, mídia, grupos, chamadas, e muito mais. + +### Estrutura Padrão + +```json +{ + "event": "MESSAGE", + "instance": "nome-da-instancia", + "data": { + // ... dados específicos do evento + } +} +``` + +### Exemplo: Mensagem Recebida + +```json +{ + "event": "MESSAGE", + "instance": "vendas", + "data": { + "key": { + "remoteJid": "5511999999999@s.whatsapp.net", + "fromMe": false, + "id": "3EB0C5A277F7F9B6C599" + }, + "message": { + "conversation": "Olá! Gostaria de informações sobre produtos." + }, + "messageTimestamp": "1699999999", + "pushName": "João Silva" + } +} +``` + +### Exemplo: Grupo Criado + +```json +{ + "event": "GROUP_UPDATE", + "instance": "suporte", + "data": { + "jid": "120363XXXXXXXXXX@g.us", + "subject": "Suporte Técnico", + "announce": false, + "participants": [ + "5511999999999@s.whatsapp.net", + "5511888888888@s.whatsapp.net" + ] + } +} +``` + +### Exemplo: Chamada Recebida + +```json +{ + "event": "CALL", + "instance": "vendas", + "data": { + "id": "ABC123", + "from": "5511999999999@s.whatsapp.net", + "timestamp": "1699999999", + "isVideo": false, + "isGroup": false + } +} +``` + +--- + +## Múltiplos Canais Simultâneos + +### Cenário: Todos os Canais Ativos + +```env +# Habilitar tudo +WEBHOOK_URL=https://api.exemplo.com/webhook +AMQP_URL=amqp://localhost:5672/ +AMQP_GLOBAL_ENABLED=true +NATS_URL=nats://localhost:4222 +NATS_ENABLED=true +``` + +```bash +curl -X POST http://localhost:4000/instance/connect \ + -H "apikey: token-vendas" \ + -H "Content-Type: application/json" \ + -d '{ + "webhookUrl": "https://api.exemplo.com/webhook-vendas", + "rabbitmqEnabled": "enabled", + "websocketEnable": "disabled", + "natsEnabled": "enabled", + "subscribe": ["MESSAGE"] + }' +``` + +**Resultado**: Ao receber 1 mensagem, o evento será enviado para: +1. ✅ Webhook global (`WEBHOOK_URL`) +2. ✅ Webhook da instância (`webhookUrl`) +3. ✅ Fila RabbitMQ `message` +4. ✅ Tópico NATS `evolution.vendas.message` +5. ✅ Clientes WebSocket conectados + +**Total**: **5 destinos** para o mesmo evento! + +--- + +## Exemplos Práticos + +### 1. Setup Básico com Webhook + +```bash +# .env +WEBHOOK_URL=https://meu-dominio.com/webhook + +# Conectar instância +curl -X POST http://localhost:4000/instance/connect \ + -H "Content-Type: application/json" \ + -H "apikey: token-bot-123" \ + -d '{ + "subscribe": ["MESSAGE"] + }' + +# Servidor receptor +node webhook-server.js +``` + +### 2. Arquitetura Distribuída com RabbitMQ + +```bash +# Docker Compose +docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management + +# .env +AMQP_URL=amqp://guest:guest@localhost:5672/ +AMQP_GLOBAL_ENABLED=true +AMQP_SPECIFIC_EVENTS=message,sendmessage + +# Consumidor em Python +python rabbitmq-consumer.py +``` + +### 3. Dashboard em Tempo Real com WebSocket + +```html + + + + Evolution GO Dashboard + + +

Mensagens em Tempo Real

+
+ + + + +``` + +### 4. Microserviços com NATS + +```bash +# Serviço 1: Processar mensagens +nats-consumer-messages.py + +# Serviço 2: Processar chamadas +nats-consumer-calls.py + +# Serviço 3: Analytics +nats-consumer-analytics.py + +# Todos consomem independentemente +``` + +--- + +## Boas Práticas + +### 1. Escolha o Canal Adequado + +**Webhook** é ideal para: +- Integração simples com APIs existentes +- Aplicações que não precisam de garantias de entrega complexas +- Quando você tem controle sobre o servidor receptor + +**RabbitMQ** é ideal para: +- Arquiteturas distribuídas com múltiplos consumidores +- Quando precisa garantir que nenhuma mensagem seja perdida +- Sistemas que exigem alta disponibilidade + +**NATS** é ideal para: +- Comunicação em tempo real com latência mínima +- Arquiteturas de microserviços +- Quando você precisa de alto volume de mensagens + +**WebSocket** é ideal para: +- Dashboards e painéis de controle +- Aplicações web que mostram dados em tempo real +- Quando você precisa de atualização instantânea na interface + +### 2. Subscreva Apenas aos Eventos Necessários + +Configure apenas os eventos que sua aplicação realmente vai processar: + +```javascript +// ❌ Evite: subscrever a todos os eventos +{"subscribe": ["ALL"]} + +// ✅ Melhor: especifique apenas o que você precisa +{"subscribe": ["MESSAGE", "GROUP_UPDATE"]} +``` + +### 3. Implemente Idempotência + +Em casos de retry, o mesmo evento pode ser recebido mais de uma vez. Implemente lógica para evitar processamento duplicado: + +```python +processed_messages = set() + +def process_event(message_id, content): + # Verifica se já foi processado + if message_id in processed_messages: + print(f"Evento {message_id} já processado, ignorando duplicata") + return + + # Processa o evento + print(f"Processando evento: {content}") + + # Marca como processado + processed_messages.add(message_id) +``` + +### 4. Monitore Filas + +**RabbitMQ**: +```bash +# Verificar filas +rabbitmqctl list_queues name messages consumers + +# Interface web +http://localhost:15672 +``` + +**NATS**: +```bash +nats server list +nats sub "evolution.>" +``` + +### 5. Configure Dead Letter Queue + +Para RabbitMQ, configure uma fila de mensagens com falha (Dead Letter Queue) para capturar eventos que não puderam ser processados após várias tentativas. Consulte a documentação do RabbitMQ para detalhes de configuração. + +--- + +## Troubleshooting + +### Webhook não está sendo chamado + +**Diagnóstico**: +```bash +# Verificar logs da instância +GET /instance/logs/:instanceId?level=ERROR +``` + +**Causas comuns**: +1. URL inválida ou inacessível +2. Firewall bloqueando requisições +3. Servidor não retornando 2xx + +**Solução**: +```bash +# Testar URL manualmente +curl -X POST https://seu-webhook.com/endpoint -H "Content-Type: application/json" -d '{"test": true}' +``` + +### RabbitMQ não conecta + +**Erro**: `failed to connect to RabbitMQ` + +**Soluções**: +1. Verificar se RabbitMQ está rodando: `docker ps | grep rabbitmq` +2. Testar conexão: `telnet localhost 5672` +3. Verificar credenciais em `AMQP_URL` + +### WebSocket desconecta constantemente + +**Causas**: +- Proxy/load balancer não suporta WebSocket +- Timeout de idle connection + +**Solução (Nginx)**: +```nginx +location /ws { + proxy_pass http://localhost:4000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 86400; # 24 horas +} +``` + +--- + +## Próximos Passos + +- [Armazenamento de Mídia](./media-storage.md) - MinIO/S3 para arquivos +- [Conexão QR Code](./qrcode-connection.md) - Processo de autenticação +- [Multi-Dispositivo](./multi-device.md) - Suporte Multi-Device +- [API de Webhooks](../guias-api/api-webhooks.md) - Configurar webhooks via API + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/recursos-avancados/media-storage.md b/docs/wiki/recursos-avancados/media-storage.md new file mode 100644 index 0000000..5051c76 --- /dev/null +++ b/docs/wiki/recursos-avancados/media-storage.md @@ -0,0 +1,474 @@ +# Armazenamento de Mídia + +Sistema de armazenamento de arquivos de mídia do Evolution GO. Suporta MinIO, Amazon S3 e outros serviços compatíveis com S3. + +## 📋 Índice + +- [Visão Geral](#visão-geral) +- [Configuração](#configuração) +- [Estrutura de Arquivos](#estrutura-de-arquivos) +- [URLs Presignadas](#urls-presignadas) +- [Provedores Compatíveis](#provedores-compatíveis) +- [Exemplos Práticos](#exemplos-práticos) +- [Boas Práticas](#boas-práticas) + +--- + +## Visão Geral + +O Evolution GO armazena arquivos de mídia (imagens, vídeos, áudios, documentos) em **object storage** compatível com S3. Isso inclui serviços como MinIO, Amazon S3, Backblaze B2, DigitalOcean Spaces e outros. + +### Por que Object Storage? + +**Vantagens**: +- ✅ Escalável: suporta terabytes ou petabytes de dados +- ✅ Distribuído: alta disponibilidade e redundância +- ✅ Custo-efetivo: preços competitivos comparados a armazenamento tradicional +- ✅ Integração com CDN: acesso rápido globalmente +- ✅ Políticas de ciclo de vida: limpeza automática de arquivos antigos + +**Comparado com armazenamento local (disco)**: +- ❌ Armazenamento local não escala horizontalmente +- ❌ Risco de perda de dados se o servidor falhar +- ❌ Complica deploys em clusters +- ❌ Sem redundância geográfica + +### Arquitetura + +``` +┌─────────────┐ +│ WhatsApp │ Envia mídia +└──────┬──────┘ + │ + ▼ +┌──────────────┐ +│ Evolution GO │ Recebe arquivo +└──────┬───────┘ + │ + ▼ +┌──────────────────────────────────────┐ +│ MediaStorage Interface │ +└───────────────┬──────────────────────┘ + │ + ▼ +┌─────────────────────────────────────┐ +│ MinIO Storage Impl │ +│ (S3-Compatible Object Storage) │ +└───────────────┬─────────────────────┘ + │ + ▼ + ┌───────────────────────┐ + │ MinIO Server │ + │ (ou S3, B2, etc) │ + └───────────────────────┘ + │ + ▼ + ┌──────────────┐ + │ Bucket │ + │ evolution- │ + │ go-medias/ │ + └──────────────┘ +``` + +--- + +## Configuração + +### Variáveis de Ambiente + +```env +# MinIO/S3 Endpoint +MINIO_ENDPOINT=s3.amazonaws.com + +# Credenciais +MINIO_ACCESS_KEY=sua-access-key +MINIO_SECRET_KEY=sua-secret-key + +# Bucket +MINIO_BUCKET=evolution-go-media + +# Região (para AWS S3) +MINIO_REGION=us-east-1 + +# Usar SSL (true/false) +MINIO_USE_SSL=true +``` + +### Exemplo: MinIO Local (Docker) + +```bash +# Rodar MinIO server +docker run -d --name minio -p 9000:9000 -p 9001:9001 -e MINIO_ROOT_USER=admin -e MINIO_ROOT_PASSWORD=password -v minio_data:/data minio/minio server /data --console-address ":9001" + +# Criar bucket via mc (MinIO Client) +docker run --rm --network host minio/mc alias set local http://localhost:9000 admin password + +docker run --rm --network host minio/mc mb local/evolution-go-media + +# .env +MINIO_ENDPOINT=localhost:9000 +MINIO_ACCESS_KEY=admin +MINIO_SECRET_KEY=password +MINIO_BUCKET=evolution-go-media +MINIO_REGION=us-east-1 +MINIO_USE_SSL=false +``` + +**Acesso Web Console**: http://localhost:9001 + +### Exemplo: AWS S3 + +```env +MINIO_ENDPOINT=s3.amazonaws.com +MINIO_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE +MINIO_SECRET_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY +MINIO_BUCKET=meu-bucket-evolution +MINIO_REGION=us-east-1 +MINIO_USE_SSL=true +``` + +### Exemplo: Backblaze B2 + +```env +MINIO_ENDPOINT=s3.us-west-004.backblazeb2.com +MINIO_ACCESS_KEY=sua-key-id +MINIO_SECRET_KEY=sua-application-key +MINIO_BUCKET=meu-bucket +MINIO_REGION=us-west-004 +MINIO_USE_SSL=true +``` + +### Exemplo: DigitalOcean Spaces + +```env +MINIO_ENDPOINT=nyc3.digitaloceanspaces.com +MINIO_ACCESS_KEY=sua-spaces-key +MINIO_SECRET_KEY=sua-spaces-secret +MINIO_BUCKET=meu-space +MINIO_REGION=nyc3 +MINIO_USE_SSL=true +``` + +--- + +## Estrutura de Arquivos + +### Organização + +Arquivos são armazenados com estrutura organizada: + +``` +bucket-name/ +└── evolution-go-medias/ + ├── image-abc123.jpg + ├── video-def456.mp4 + ├── audio-ghi789.ogg + └── document-jkl012.pdf +``` + +### Caminho dos Arquivos + +Todos os arquivos são armazenados automaticamente no diretório `evolution-go-medias/`: + +**Exemplos**: +- Arquivo: `photo-123.jpg` → Caminho: `evolution-go-medias/photo-123.jpg` +- Arquivo: `video-456.mp4` → Caminho: `evolution-go-medias/video-456.mp4` +- Arquivo: `document-789.pdf` → Caminho: `evolution-go-medias/document-789.pdf` + +--- + +## URLs Presignadas + +### O que são? + +**URLs presignadas** são URLs temporárias que permitem acesso a arquivos privados sem expor suas credenciais de acesso. + +**Características**: +- ✅ Válidas por tempo limitado (padrão: 7 dias) +- ✅ Não requerem autenticação adicional +- ✅ Assinadas criptograficamente para segurança +- ✅ Podem ser compartilhadas publicamente durante o período de validade + +### Como Funcionam + +Quando você armazena ou solicita acesso a um arquivo, o Evolution GO gera automaticamente uma URL presignada com validade de 7 dias. + +**Exemplo de URL presignada**: +``` +https://s3.amazonaws.com/evolution-go-media/evolution-go-medias/photo-123.jpg? +X-Amz-Algorithm=AWS4-HMAC-SHA256& +X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20250111%2Fus-east-1%2Fs3%2Faws4_request& +X-Amz-Date=20250111T100000Z& +X-Amz-Expires=604800& +X-Amz-SignedHeaders=host& +X-Amz-Signature=abc123def456... +``` + +### Validade + +**Tempo de expiração**: 7 dias (168 horas) + +**Após expiração**: +- A URL retorna erro `403 Forbidden` +- É necessário gerar uma nova URL através da API + +--- + +## Provedores Compatíveis + +### Amazon S3 + +**Configuração**: +```env +MINIO_ENDPOINT=s3.amazonaws.com +MINIO_REGION=us-east-1 +MINIO_USE_SSL=true +``` + +**Vantagens**: +- ✅ Mais confiável e testado +- ✅ Integração com CloudFront (CDN) +- ✅ Lifecycle policies avançadas +- ✅ Versionamento de objetos + +**Desvantagens**: +- ❌ Mais caro que alternativas +- ❌ Vendor lock-in + +### MinIO (Self-hosted) + +**Configuração**: +```env +MINIO_ENDPOINT=minio.meu-dominio.com:9000 +MINIO_REGION=us-east-1 +MINIO_USE_SSL=true +``` + +**Vantagens**: +- ✅ Gratuito (self-hosted) +- ✅ Controle total +- ✅ Compatível com S3 API +- ✅ Bom para desenvolvimento + +**Desvantagens**: +- ❌ Você gerencia infraestrutura +- ❌ Requer configuração de HA + +### Backblaze B2 + +**Configuração**: +```env +MINIO_ENDPOINT=s3.us-west-004.backblazeb2.com +MINIO_REGION=us-west-004 +MINIO_USE_SSL=true +``` + +**Vantagens**: +- ✅ Muito mais barato que S3 (1/4 do preço) +- ✅ Egress gratuito (até 3x storage) +- ✅ S3-compatible + +**Desvantagens**: +- ❌ Não suporta bucket policies (usa presigned URLs) +- ❌ Menos integrações que AWS + +### DigitalOcean Spaces + +**Configuração**: +```env +MINIO_ENDPOINT=nyc3.digitaloceanspaces.com +MINIO_REGION=nyc3 +MINIO_USE_SSL=true +``` + +**Vantagens**: +- ✅ Preço fixo ($5/mês por 250GB) +- ✅ CDN incluso +- ✅ Fácil configuração + +**Desvantagens**: +- ❌ Limite de 250GB no plano básico +- ❌ Menos recursos que S3 + +### Wasabi + +**Configuração**: +```env +MINIO_ENDPOINT=s3.wasabisys.com +MINIO_REGION=us-east-1 +MINIO_USE_SSL=true +``` + +**Vantagens**: +- ✅ Sem custo de egress +- ✅ Preço competitivo +- ✅ S3-compatible + +--- + +## Exemplos Práticos + +### 1. Upload de Mídia + +Quando o WhatsApp recebe uma imagem, vídeo ou documento: +1. O Evolution GO baixa o arquivo +2. Armazena automaticamente no object storage configurado +3. Gera uma URL presignada de acesso +4. A URL é incluída na resposta da API ou evento + +### 2. Acesso a Mídia Armazenada + +Para acessar um arquivo já armazenado: +- Use a URL presignada retornada durante o upload +- Se a URL expirou (>7 dias), solicite uma nova através da API + +### 3. Limpeza de Arquivos Antigos + +Configure lifecycle policies no seu provedor para deletar automaticamente arquivos antigos: +- **AWS S3**: Configure regras de ciclo de vida no console +- **MinIO**: Use o comando `mc ilm` para configurar políticas +- **Outros**: Consulte a documentação do provedor + +--- + +## Boas Práticas + +### 1. Use Nomes de Arquivo Únicos + +Gere nomes únicos para cada arquivo para evitar sobrescrever arquivos existentes: + +**❌ Evite**: Usar nomes genéricos como `photo.jpg`, `video.mp4` + +**✅ Recomendado**: Usar identificadores únicos como UUID ou timestamp: +- `photo-abc123-def456-ghi789.jpg` +- `video-20250111-103045.mp4` +- `document-550e8400-e29b-41d4.pdf` + +### 2. Configure Content-Type Correto + +O Evolution GO configura automaticamente o Content-Type baseado na extensão do arquivo: +- `.jpg`, `.jpeg` → `image/jpeg` +- `.png` → `image/png` +- `.mp4` → `video/mp4` +- `.pdf` → `application/pdf` +- `.ogg` → `audio/ogg` + +### 3. Implemente Lifecycle Policies + +**AWS S3**: +```json +{ + "Rules": [ + { + "Id": "delete-old-media", + "Status": "Enabled", + "Prefix": "evolution-go-medias/", + "Expiration": { + "Days": 30 + } + } + ] +} +``` + +**MinIO**: +```bash +mc ilm add local/evolution-go-media --prefix "evolution-go-medias/" --expiry-days 30 +``` + +### 4. Use CDN para Distribuição + +**CloudFront (AWS)**: +1. Crie distribuição CloudFront +2. Aponte origin para bucket S3 +3. URLs ficam: `https://d123456.cloudfront.net/evolution-go-medias/photo.jpg` + +**DigitalOcean Spaces CDN** (automático): +``` +https://bucket-name.nyc3.cdn.digitaloceanspaces.com/file.jpg +``` + +### 5. Monitore Uso e Custos + +```bash +# AWS S3 - Tamanho total do bucket +aws s3 ls s3://bucket-name --recursive --summarize | grep "Total Size" + +# MinIO +mc du local/evolution-go-media +``` + +### 6. Comprima Imagens Quando Possível + +Para reduzir custos de armazenamento e transferência: +- Comprima imagens antes de armazenar +- Use formatos modernos como WebP quando possível +- Ajuste a qualidade JPEG para 80-90% (reduz tamanho sem perda significativa de qualidade) + +### 7. Monitore Uso e Custos + +Acompanhe regularmente: +- Tamanho total do bucket +- Número de arquivos armazenados +- Custos mensais de armazenamento e transferência +- URLs presignadas que expiraram + +--- + +## Troubleshooting + +### Erro: "failed to create MinIO client" + +**Causa**: Credenciais ou endpoint incorretos. + +**Solução**: +```bash +# Testar conexão com mc +mc alias set test https://endpoint access-key secret-key +mc ls test +``` + +### Erro: "bucket does not exist" + +**Causa**: Bucket não foi criado. + +**Solução**: +```bash +# Criar bucket +mc mb test/evolution-go-media + +# Ou via AWS CLI +aws s3 mb s3://evolution-go-media +``` + +### URLs retornam 403 Forbidden + +**Causa 1**: URL presignada expirou (>7 dias). + +**Solução**: Gere nova URL com `GetURL()`. + +**Causa 2**: Bucket policy incorreta. + +**Solução**: Use presigned URLs (funcionam independente de bucket policy). + +### Upload muito lento + +**Causa**: Latência de rede para região distante. + +**Solução**: +1. Use região mais próxima do servidor +2. Use multipart upload para arquivos grandes (>5MB) +3. Configure timeout adequado + +--- + +## Próximos Passos + +- [Sistema de Eventos](./events-system.md) - Receber notificações de uploads +- [Conexão QR Code](./qrcode-connection.md) - Autenticação WhatsApp +- [Multi-Dispositivo](./multi-device.md) - Suporte Multi-Device +- [API de Mensagens](../guias-api/api-messages.md) - Enviar mídias via API + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/recursos-avancados/multi-device.md b/docs/wiki/recursos-avancados/multi-device.md new file mode 100644 index 0000000..d686f31 --- /dev/null +++ b/docs/wiki/recursos-avancados/multi-device.md @@ -0,0 +1,395 @@ +# WhatsApp Multi-Device + +Entenda como funciona o protocolo Multi-Device do WhatsApp e como o Evolution GO o utiliza. + +## 📋 Índice + +- [Visão Geral](#visão-geral) +- [Arquitetura](#arquitetura) +- [Protocolo Signal](#protocolo-signal) +- [Sincronização de Dados](#sincronização-de-dados) +- [Criptografia](#criptografia) +- [Limitações](#limitações) +- [Vantagens](#vantagens) +- [Comparação com Versão Antiga](#comparação-com-versão-antiga) + +--- + +## Visão Geral + +WhatsApp **Multi-Device** é o protocolo que permite conectar até 4 dispositivos simultaneamente, sem necessidade do celular estar online após o pareamento inicial. + +### Antes vs Depois + +**Legacy (Antigo - Web WhatsApp)**: +``` +┌─────────────┐ +│ Celular │ ◄── SEMPRE precisa estar online +│ (Primary) │ +└──────┬──────┘ + │ + │ Relay + │ + ▼ +┌──────────────┐ +│ WhatsApp Web │ ◄── Depende 100% do celular +└──────────────┘ +``` + +**Multi-Device (Atual)**: +``` +┌─────────────┐ +│ Celular │ ◄── Dispositivo principal +│ (Primary) │ +└──────┬──────┘ + │ + │ Peer-to-Peer Sync + │ + ├────────────┬────────────┬────────────┐ + ▼ ▼ ▼ ▼ +┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ +│WhatsApp │ │Evolution │ │WhatsApp │ │WhatsApp │ +│Desktop │ │ GO │ │Web │ │Business │ +└──────────┘ └──────────┘ └──────────┘ └──────────┘ + +Todos funcionam INDEPENDENTEMENTE! +``` + +--- + +## Arquitetura + +### Componentes + +1. **Dispositivo Principal (Primary Device)** + - Celular com WhatsApp instalado + - Única fonte de verdade para contatos e configurações + - Pode funcionar offline após sincronização inicial + +2. **Dispositivos Companion (Companion Devices)** + - WhatsApp Web, Desktop, Business API, Evolution GO + - Até 4 dispositivos simultâneos + - Funcionam independentemente após pareamento + +3. **Servidores WhatsApp** + - Facilitam comunicação entre devices + - Armazenam mensagens criptografadas temporariamente + - Sincronizam estado entre dispositivos + +### Diagrama de Comunicação + +``` +┌──────────────────────────────────────────────────────────┐ +│ WhatsApp Servers │ +│ - Message Routing │ +│ - State Synchronization │ +│ - End-to-End Encryption Relay │ +└───────────────────┬──────────────────────────────────────┘ + │ + ┌──────────┼──────────┬──────────┬──────────┐ + │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ + ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ + │Primary │ │Device 1│ │Device 2│ │Device 3│ │Device 4│ + │(Phone) │ │Desktop │ │Evolution│ │ Web │ │Business│ + └────────┘ └────────┘ └────────┘ └────────┘ └────────┘ + │ │ │ │ │ + └──────────┴──────────┴──────────┴──────────┘ + │ + Direct Peer Sync + (quando ambos online) +``` + +### Funcionamento + +**Enviar Mensagem**: +1. Device 1 (Evolution GO) envia mensagem criptografada para WhatsApp servers +2. Servers encaminham para destinatário +3. Servers **também** sincronizam com outros devices do remetente +4. Primary device e outros companion devices recebem cópia + +**Receber Mensagem**: +1. WhatsApp servers recebem mensagem destinada ao seu número +2. Servers replicam para **todos os devices conectados** simultaneamente +3. Cada device descriptografa independentemente + +--- + +## Protocolo Signal + +### O que é Signal Protocol? + +**Signal Protocol** é o protocolo de criptografia ponta-a-ponta (E2EE) usado pelo WhatsApp Multi-Device. + +**Criado por**: Open Whisper Systems (agora Signal Foundation) + +**Usado em**: +- WhatsApp +- Signal Messenger +- Facebook Messenger (Secret Conversations) +- Google Messages (RCS) + +### Componentes do Signal Protocol + +#### 1. Identity Keys (Chaves de Identidade) + +Cada dispositivo tem um par de chaves únicas: +- **Chave Pública**: Compartilhada com outros dispositivos +- **Chave Privada**: Nunca sai do dispositivo, usada para descriptografia + +#### 2. Pre-Keys (Chaves Pré-geradas) + +Um conjunto de 100 chaves geradas automaticamente quando você conecta um dispositivo pela primeira vez. Essas chaves permitem que outros dispositivos iniciem conversas criptografadas com você, mesmo quando você está offline. + +**Renovação**: Novas pre-keys são geradas automaticamente conforme necessário. + +#### 3. Signed Pre-Keys (Chaves Assinadas) + +Uma pre-key especial assinada pela sua chave de identidade, provando autenticidade. + +**Renovação**: A cada 7 dias. + +#### 4. Session Keys (Chaves de Sessão) + +Chaves únicas para cada conversa que mudam automaticamente a cada mensagem enviada (conceito chamado "ratcheting"). + +**Segurança**: Se uma chave for comprometida, apenas aquela mensagem específica é afetada - mensagens anteriores e futuras permanecem seguras (Forward Secrecy). + +--- + +## Sincronização de Dados + +### Tipos de Sincronização + +#### 1. Mensagens + +**Histórico Inicial**: +- Últimos **3 meses** de conversas +- Mídia: Apenas thumbnails (mídia completa baixada on-demand) + +**Novas Mensagens**: +- Sincronizadas em tempo real +- Todos os dispositivos recebem simultaneamente + +#### 2. Contatos + +**Sincronização**: +- Lista completa de contatos do celular +- Atualizada automaticamente quando um contato muda nome ou número + +#### 3. Grupos + +**Informações sincronizadas**: +- Lista de todos os grupos que você participa +- Metadados (nome, descrição, foto, lista de participantes) +- Configurações (silenciado, fixado) + +#### 4. Chats + +**Estados sincronizados**: +- Chats fixados (pinned) +- Chats arquivados (archived) +- Chats silenciados (muted) +- Mensagens lidas/não lidas + +#### 5. Configurações + +**Sincronizadas**: +- Foto de perfil +- Nome de exibição +- Recado (status text) +- Configurações de privacidade + +**NÃO sincronizadas**: +- Notificações (específico por device) +- Tema/aparência (específico por device) + +### History Sync Request + +**Solicitação de histórico** (implementado via API): + +```bash +POST /chat/history-sync-request +{ + "messageInfo": { + "Chat": "5511999999999@s.whatsapp.net", + "IsFromMe": false, + "IsGroup": false, + "ID": "3EB0C5A277F7F9B6C599", + "Timestamp": "2025-11-11T10:00:00Z" + }, + "count": 50 +} +``` + +**Parâmetros**: +- `messageInfo`: Mensagem de referência (ponto de partida) +- `count`: Número de mensagens para buscar (máx 100) + +**Uso**: Carregar mensagens antigas de uma conversa. + +--- + +## Criptografia + +### End-to-End Encryption (Criptografia Ponta-a-Ponta) + +Todas as mensagens são criptografadas no dispositivo do remetente e só podem ser descriptografadas no dispositivo do destinatário. + +**Importante**: Os servidores do WhatsApp não conseguem ler o conteúdo das mensagens - eles apenas facilitam a entrega dos dados criptografados. + +### Fluxo de Criptografia + +``` +┌────────────┐ ┌────────────┐ +│ Remetente │ │Destinatário│ +│ (Device) │ │ (Device) │ +└─────┬──────┘ └──────┬─────┘ + │ │ + │ 1. Mensagem: "Olá!" │ + │──────────┐ │ + │ │ │ + │ 2. Criptografa com Session Key │ + │<─────────┘ │ + │ │ + │ 3. Envia encrypted blob │ + │───────────────────────────────────────────────>│ + │ (via WhatsApp Servers) │ + │ │ + │ │ 4. Descriptografa + │ │────────────┐ + │ │ │ + │ │ 5. "Olá!" │ + │ │<───────────┘ + │ │ +``` + +### Verificação de Segurança + +**Código de Segurança (Safety Number)**: +- É um código de 60 dígitos único para cada conversa +- Compara as chaves de identidade dos participantes +- Muda se um dos participantes trocar de dispositivo + +**Como verificar no WhatsApp**: +1. Abrir a conversa +2. Tocar no nome do contato +3. Selecionar "Criptografia" +4. Comparar o código com o contato pessoalmente ou por outro canal seguro + +--- + +## Limitações + +### Limite de Devices + +**Máximo**: 4 companion devices + 1 primary device (celular). + +**Exemplo**: +- ✅ Celular (Primary) +- ✅ WhatsApp Web (Device 1) +- ✅ WhatsApp Desktop (Device 2) +- ✅ Evolution GO (Device 3) +- ✅ WhatsApp Business API (Device 4) +- ❌ Outro device → Erro: "Máximo de devices atingido" + +**Solução**: Desconectar um device antes de conectar novo. + +### Histórico Limitado + +**Sincronização inicial**: Apenas últimos **3 meses**. + +**Mensagens mais antigas**: +- Não são sincronizadas automaticamente +- Podem ser buscadas via History Sync Request (se disponíveis) +- Mídia completa não é transferida (apenas thumbnails) + +### Chamadas + +**Limitação atual**: Evolution GO **não suporta atender** chamadas de voz/vídeo. + +**Suportado**: +- ✅ Receber notificação de chamada (evento `CALL`) +- ✅ Rejeitar chamada automaticamente + +**NÃO suportado**: +- ❌ Atender chamada +- ❌ Áudio/vídeo em tempo real + +### Sessão Expira + +**Inatividade**: Se device ficar offline por **>14 dias**, sessão expira. + +**Solução**: Novo pareamento via QR Code necessário. + +--- + +## Vantagens + +### 1. Independência do Celular + +**Evolution GO funciona mesmo com celular offline** (após sincronização inicial). + +**Casos de uso**: +- Celular sem bateria +- Celular sem internet +- Viagem internacional (celular desligado) + +### 2. Sincronização em Tempo Real + +**Todas as mensagens** aparecem em todos os devices simultaneamente. + +**Exemplo**: +- Enviar mensagem no Evolution GO +- Aparece instantaneamente no WhatsApp Web +- Aparece no celular +- Aparece no Desktop + +### 3. Múltiplas Contas Simultâneas + +**Com containers Docker**, você pode ter **N instâncias** do Evolution GO, cada uma conectada a um número WhatsApp diferente: + +```bash +docker run -d --name evo-vendas evolution-go +docker run -d --name evo-suporte evolution-go +docker run -d --name evo-marketing evolution-go +``` + +Cada container = 1 número WhatsApp separado. + +### 4. Alta Disponibilidade + +**Redundância**: Se um device falha, outros continuam funcionando. + +**Load Balancing**: Distribua carga entre múltiplos Evolution GO instances. + +--- + +## Comparação com Versão Antiga + +| Aspecto | Legacy (Web WhatsApp) | Multi-Device (Atual) | +|---------|----------------------|----------------------| +| **Celular precisa online?** | ✅ Sim, sempre | ❌ Não (após pareamento) | +| **Criptografia** | E2EE | E2EE (melhorada) | +| **Sincronização** | Relay via celular | Peer-to-peer + servers | +| **Histórico** | Depende do celular | 3 meses sincronizados | +| **Latência** | Alta (2 hops) | Baixa (direto) | +| **Devices simultâneos** | 1 (Web) | 4 companions | +| **Chamadas** | Não suportado | Não suportado* | +| **Mídia** | Relay via celular | Direct download | + +*Chamadas não suportadas em companion devices (limitação WhatsApp). + + +--- + +## Próximos Passos + +- [Conexão QR Code](./qrcode-connection.md) - Processo de pareamento +- [Sistema de Eventos](./events-system.md) - Receber eventos Multi-Device +- [Instâncias WhatsApp](../conceitos-core/instances.md) - Gerenciamento de devices +- [Banco de Dados](../conceitos-core/database.md) - Armazenamento de sessões + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/recursos-avancados/qrcode-connection.md b/docs/wiki/recursos-avancados/qrcode-connection.md new file mode 100644 index 0000000..23c046c --- /dev/null +++ b/docs/wiki/recursos-avancados/qrcode-connection.md @@ -0,0 +1,679 @@ +# Conexão QR Code + +Como funciona o processo de autenticação via QR Code no Evolution GO. + +## 📋 Índice + +- [Visão Geral](#visão-geral) +- [Fluxo de Conexão](#fluxo-de-conexão) +- [Geração do QR Code](#geração-do-qr-code) +- [Leitura do QR Code](#leitura-do-qr-code) +- [Pareamento por Código](#pareamento-por-código) +- [Estados da Conexão](#estados-da-conexão) +- [Reconexão Automática](#reconexão-automática) +- [Troubleshooting](#troubleshooting) +- [Boas Práticas](#boas-práticas) + +--- + +## Visão Geral + +O Evolution GO utiliza o protocolo Multi-Device do WhatsApp para autenticar instâncias. O processo é baseado em QR Code, similar ao WhatsApp Web. + +### Como Funciona + +1. **Gerar QR Code**: O Evolution GO cria um código único +2. **Escanear**: Você escaneia o código com o WhatsApp no celular +3. **Pareamento**: WhatsApp e Evolution GO trocam chaves de criptografia +4. **Sessão Ativa**: Conexão estabelecida e salva no banco de dados + +### Por que QR Code? + +**Vantagens**: +- ✅ Seguro: chaves criptográficas trocadas de forma protegida +- ✅ Não requer senha ou número de telefone +- ✅ Suporta múltiplos dispositivos conectados simultaneamente +- ✅ Processo simples e rápido + +**Importante**: O WhatsApp não oferece login com usuário e senha para APIs. A autenticação é exclusivamente via QR Code ou código de pareamento. + +--- + +## Fluxo de Conexão + +### Diagrama Completo + +``` +┌──────────────┐ ┌──────────────┐ +│ Evolution GO │ │ WhatsApp │ +│ Client │ │ Servers │ +└──────┬───────┘ └──────┬───────┘ + │ │ + │ 1. POST /instance/connect │ + │────────────────────────┐ │ + │ │ │ + │ 2. StartClient() │ │ + │<───────────────────────┘ │ + │ │ + │ 3. Connect WebSocket │ + │──────────────────────────────────────────────────────>│ + │ │ + │ 4. Request QR Code │ + │──────────────────────────────────────────────────────>│ + │ │ + │ 5. QR Code Data (ref + public key) │ + │<──────────────────────────────────────────────────────│ + │ │ + │ 6. Generate PNG QR Code │ + │────────────┐ │ + │ │ │ + │<───────────┘ │ + │ │ + │ 7. Save QR to Database (base64|text) │ + │────────────┐ │ + │ │ │ + │<───────────┘ │ + │ │ + │ 8. Emit QR_CODE Event │ + │────────────┐ │ + │ │ (Webhook/WebSocket) │ + │<───────────┘ │ + │ │ +┌──────▼───────┐ │ +│ User │ │ +│ (Smartphone) │ │ +└──────┬───────┘ │ + │ │ + │ 9. Open WhatsApp App │ + │ → Linked Devices │ + │ → Scan QR Code │ + │ │ + │ 10. Send Pairing Data (encrypted) │ + │──────────────────────────────────────────────────────>│ + │ │ + │ 11. Pairing Success │ + │<──────────────────────────────────────────────────────│ + │ │ +┌──────▼───────┐ │ +│ Evolution GO │ │ +└──────┬───────┘ │ + │ │ + │ 12. Receive Pairing Success Event │ + │<──────────────────────────────────────────────────────│ + │ │ + │ 13. Generate Identity & Pre-Keys │ + │────────────┐ │ + │ │ │ + │<───────────┘ │ + │ │ + │ 14. Save Session to Database │ + │────────────┐ │ + │ │ (JID, Keys, Device Info) │ + │<───────────┘ │ + │ │ + │ 15. Update Instance (connected=true, jid=...) │ + │────────────┐ │ + │ │ │ + │<───────────┘ │ + │ │ + │ 16. Emit CONNECTED Event │ + │────────────┐ │ + │ │ │ + │<───────────┘ │ + │ │ + │ 17. Start Message Sync │ + │<─────────────────────────────────────────────────────>│ + │ (bidirectional) │ + │ │ +``` + +### Passos Detalhados + +#### 1. Conectar Instância + +**API Call**: +```bash +POST /instance/connect +{ + "instanceName": "vendas" +} +``` + +**Ações**: +- Verifica se instância existe no banco +- Inicia goroutine com whatsmeow client +- Estabelece WebSocket com servidores WhatsApp + +#### 2. Solicitação de QR Code + +O Evolution GO solicita ao WhatsApp um código QR único, que contém: +- **Ref**: Referência única que identifica esta tentativa de conexão +- **Public Key**: Chave pública para iniciar o pareamento criptografado + +#### 3. Geração da Imagem QR + +**Formato do texto no QR Code**: +``` +versão@ref,chave_pública,segredo,dados_adicionais +``` + +**Exemplo**: +``` +2@ABC123DEF456,GHI789JKL012MNO345,PQR678STU901VWX234,YZA567 +``` + +**Armazenamento**: +O QR Code é convertido em uma imagem PNG, codificada em base64 e salva no banco de dados junto com o texto original. + +#### 4. Exibição do QR Code + +**Via navegador**: +``` +GET /instance/qr?instanceName=vendas +``` + +**Resposta HTML**: +```html + +``` + +**Via API JSON**: +```bash +GET /instance/qr?instanceName=vendas +``` + +```json +{ + "qrcode": "iVBORw0KGgoAAAANSUhEUgAA...", + "code": "2@ABC123,DEF456,GHI789,JKL012" +} +``` + +#### 5. Usuário Escaneia + +**No smartphone**: +1. Abre WhatsApp +2. Menu → Aparelhos conectados +3. Conectar um aparelho +4. Escaneia QR Code + +**WhatsApp envia**: +- Chaves públicas do device +- JID (WhatsApp ID) do número +- Device info (modelo, OS) + +#### 6. Pareamento Concluído + +Após o usuário escanear o QR Code: + +1. **Evolution GO recebe confirmação** do WhatsApp +2. **Sessão é salva** no banco de dados com: + - Chaves de identidade + - Chaves pré-geradas + - JID (identificador do WhatsApp) + - Informações do dispositivo +3. **Instância marcada como conectada** +4. **Evento CONNECTED** é publicado + +--- + +## Geração do QR Code + +### Evento de QR Code + +Quando um QR Code é gerado: + +1. **Texto do QR Code** é recebido do WhatsApp +2. **Imagem PNG** é criada a partir do texto +3. **Salvo no banco de dados** em formato base64 +4. **Evento QR_CODE** é publicado para webhooks/websockets configurados + +### Formato do QR + +**Estrutura**: +``` +version@ref,pub_key,secret,adv +``` + +**Componentes**: +- `version`: Versão do protocolo (geralmente `2`) +- `ref`: Referência única (identifica esta tentativa de pareamento) +- `pub_key`: Chave pública do servidor +- `secret`: Segredo compartilhado +- `adv`: Dados de advertising (device info) + +**Exemplo real**: +``` +2@12345abcdef,67890ghijk,lmnop12345,qrstu67890 +``` + +### Expiração + +**Tempo de vida**: ~40 segundos + +**Após expiração**: +- Whatsmeow emite novo evento QR +- Novo QR Code é gerado +- Repete até `max_attempts` (padrão: 5 tentativas) + +**Evento de timeout**: +```go +case *events.QRTimeout: + logger.Warn("QR Code expired, generating new one...") +``` + +--- + +## Leitura do QR Code + +### Endpoint HTTP + +**Obter QR Code via API**: +```bash +GET /instance/qr?instanceName=vendas +``` + +**Response (JSON)**: +```json +{ + "qrcode": "iVBORw0KGgoAAAANSUhEUgAABAA...", + "code": "2@12345abcdef,67890ghijk,lmnop12345,qrstu67890" +} +``` + +**Response (HTML)** - Se aceitar `text/html`: +```html + + +QR Code - vendas + +

QR Code - Instância: vendas

+ +

Escaneie com WhatsApp

+ + +``` + +### Via WebSocket + +**Conectar**: +```javascript +const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas'); + +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + + if (data.queue === 'qrcode') { + const payload = JSON.parse(data.payload); + const qrBase64 = payload.qrcode; + + // Exibir QR Code + document.getElementById('qr-img').src = + `data:image/png;base64,${qrBase64}`; + } +}; +``` + +### Via Webhook + +**Configurar webhook**: +```bash +POST /instance/connect +{ + "instanceName": "vendas", + "webhookUrl": "https://meu-servidor.com/webhook", + "subscribe": ["QRCODE"] +} +``` + +**Evento recebido**: +```json +{ + "event": "QRCODE", + "instance": "vendas", + "data": { + "qrcode": "iVBORw0KGgoAAAANSUhEUgA...", + "code": "2@12345abcdef,67890ghijk,lmnop12345,qrstu67890" + } +} +``` + +--- + +## Pareamento por Código + +### Alternativa ao QR Code + +Além de QR Code, é possível parear via **código de 8 dígitos**. + +**Endpoint**: +```bash +POST /instance/pair +{ + "instanceName": "vendas", + "phone": "5511999999999" +} +``` + +**Response**: +```json +{ + "pairingCode": "ABCD-1234" +} +``` + +### Como Usar + +**No smartphone**: +1. Abre WhatsApp +2. Menu → Aparelhos conectados +3. Conectar um aparelho +4. Link com código de aparelho +5. Digita `ABCD-1234` + +**Vantagens**: +- ✅ Não precisa de camera/QR scanner +- ✅ Mais fácil para compartilhar remotamente + +**Desvantagens**: +- ❌ Requer digitação manual +- ❌ Menos visual que QR Code + +### Como Funciona + +O Evolution GO gera um código de 8 dígitos único e o retorna na API. Esse código é válido por tempo limitado e pode ser usado uma única vez. + +--- + +## Estados da Conexão + +### Máquina de Estados + +``` +┌─────────────┐ +│ CREATED │ Instância criada, nunca conectada +└──────┬──────┘ + │ POST /instance/connect + ▼ +┌─────────────┐ +│ CONNECTING │ WebSocket iniciando +└──────┬──────┘ + │ + ▼ +┌─────────────┐ +│ WAITING_QR │ Aguardando usuário escanear +└──────┬──────┘ + │ Usuário escaneia QR + ▼ +┌─────────────┐ +│ PAIRING │ Trocando chaves criptográficas +└──────┬──────┘ + │ + ▼ +┌─────────────┐ +│ OPEN │ Conectado e autenticado +└──────┬──────┘ + │ + │ Erro de conexão ou logout + ▼ +┌─────────────┐ +│ DISCONNECTED│ +└─────────────┘ +``` + +### Eventos Associados + +#### QRCODE +```json +{ + "event": "QRCODE", + "data": { + "qrcode": "base64...", + "code": "2@..." + } +} +``` + +#### QR_TIMEOUT +```json +{ + "event": "QR_TIMEOUT", + "data": { + "attempts": 1, + "maxAttempts": 5 + } +} +``` + +#### QR_SUCCESS +```json +{ + "event": "QR_SUCCESS", + "data": { + "jid": "5511999999999@s.whatsapp.net" + } +} +``` + +#### CONNECTED +```json +{ + "event": "CONNECTED", + "data": { + "jid": "5511999999999@s.whatsapp.net", + "name": "João Silva", + "timestamp": "2025-11-11T10:30:00Z" + } +} +``` + +--- + +## Reconexão Automática + +### Após Primeiro Pareamento + +Depois do primeiro pareamento bem-sucedido via QR Code: + +1. **Sessão é salva** no banco de dados PostgreSQL +2. **Próxima inicialização**: Sessão é carregada automaticamente +3. **Conecta diretamente** sem necessidade de novo QR Code + +O Evolution GO mantém várias tabelas para armazenar as informações de sessão e chaves criptográficas necessárias para reconexão. + +### Tentativas de Reconexão + +Se uma conexão cair, o Evolution GO tenta reconectar automaticamente usando estratégia de intervalo crescente: + +- Tentativa 1: 2 segundos +- Tentativa 2: 4 segundos +- Tentativa 3: 8 segundos +- Tentativa 4: 16 segundos +- Tentativa 5: 32 segundos + +### Quando é Necessário Novo QR Code + +Em alguns cenários, é necessário gerar um novo QR Code: + +- ❌ Após logout explícito via API +- ❌ Dispositivo removido manualmente no app WhatsApp +- ❌ Sessão expirada (mais de 14 dias offline) +- ❌ Conta temporariamente ou permanentemente bloqueada + +--- + +## Troubleshooting + +### QR Code não aparece + +**Diagnóstico**: +```bash +GET /instance/logs/:instanceId?level=ERROR +``` + +**Causas comuns**: +1. Cliente não conectado ao WebSocket +2. Firewall bloqueando conexão com WhatsApp servers +3. Instância já conectada (não precisa de QR) + +**Solução**: +```bash +# Forçar reconexão +POST /instance/reconnect +{ + "instanceName": "vendas" +} +``` + +### QR Code expira muito rápido + +**Causa**: Delay entre geração e exibição. + +**Solução**: Use WebSocket para receber QR em tempo real. + +```javascript +const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas'); + +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + if (data.queue === 'qrcode') { + // Exibir imediatamente + showQRCode(data.payload.qrcode); + } +}; +``` + +### Escaneou QR mas não conectou + +**Diagnóstico**: +```bash +GET /instance/status?instanceName=vendas +``` + +**Resposta esperada após scan**: +```json +{ + "connected": true, + "loggedIn": true, + "jid": "5511999999999@s.whatsapp.net" +} +``` + +**Se continuar `connected: false`**: +1. Verificar logs de erro +2. Tentar logout e novo QR +3. Verificar se WhatsApp está atualizado + +### Erro: "too many attempts" + +**Causa**: QR Code expirou 5 vezes. + +**Solução**: +```bash +# Desconectar +POST /instance/disconnect + +# Aguardar 30 segundos + +# Reconectar +POST /instance/connect +``` + +--- + +## Boas Práticas + +### 1. Exibir QR em Tempo Real + +Use WebSocket em vez de polling: + +**❌ Ruim** (polling): +```javascript +setInterval(() => { + fetch('/instance/qr?instanceName=vendas') + .then(res => res.json()) + .then(data => showQR(data.qrcode)); +}, 5000); // A cada 5 segundos +``` + +**✅ Bom** (WebSocket): +```javascript +const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas'); +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + if (data.queue === 'qrcode') showQR(data.payload.qrcode); +}; +``` + +### 2. Feedback Visual + +Mostre estado da conexão para o usuário: + +```javascript +ws.onmessage = (event) => { + const { queue } = JSON.parse(event.data); + + switch(queue) { + case 'qrcode': + showStatus('Escaneie o QR Code'); + break; + case 'qr_success': + showStatus('QR Code escaneado! Conectando...'); + break; + case 'connected': + showStatus('Conectado com sucesso!'); + break; + } +}; +``` + +### 3. Timeout de Inatividade + +Desconecte se QR não for escaneado em tempo razoável: + +```javascript +let qrTimeout; + +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + + if (data.queue === 'qrcode') { + // Cancela timeout anterior + clearTimeout(qrTimeout); + + // Timeout de 2 minutos + qrTimeout = setTimeout(() => { + alert('QR Code expirou. Por favor, tente novamente.'); + ws.close(); + }, 120000); + } + + if (data.queue === 'connected') { + clearTimeout(qrTimeout); + } +}; +``` + +### 4. Validar Sessão Antes de Solicitar QR + +```bash +# Verificar status primeiro +GET /instance/status?instanceName=vendas + +# Se já conectado, não precisa de QR +# Se desconectado mas tem sessão, tentar reconnect +# Só gerar QR se não tem sessão +``` + +--- + +## Próximos Passos + +- [Multi-Dispositivo](./multi-device.md) - Entender protocolo Multi-Device +- [Instâncias WhatsApp](../conceitos-core/instances.md) - Ciclo de vida completo +- [Sistema de Eventos](./events-system.md) - Receber eventos de conexão +- [API de Instâncias](../guias-api/api-instances.md) - Todos os endpoints + +--- + +**Documentação gerada para Evolution GO v1.0** diff --git a/docs/wiki/referencia/api-reference.md b/docs/wiki/referencia/api-reference.md new file mode 100644 index 0000000..f4f7e81 --- /dev/null +++ b/docs/wiki/referencia/api-reference.md @@ -0,0 +1,184 @@ +# Referência da API + +Referência rápida de endpoints disponíveis na API Evolution GO. + +## Autenticação + +Todos os endpoints requerem header de autenticação: + +``` +apikey: SUA-CHAVE-API +``` + +## Base URL + +``` +http://localhost:4000 +``` + +--- + +## Endpoints por Categoria + +### Instâncias (16 endpoints) + +**Gerenciamento (requer GLOBAL_API_KEY):** +- `POST /instance/create` - Criar nova instância +- `GET /instance/all` - Listar todas as instâncias +- `GET /instance/info/:instanceId` - Detalhes da instância +- `DELETE /instance/delete/:instanceId` - Remover instância + +**Operações (requer token da instância):** +- `POST /instance/connect` - Iniciar conexão +- `GET /instance/status` - Status de conexão +- `GET /instance/qr` - Obter QR Code +- `POST /instance/pair` - Parear com código +- `POST /instance/disconnect` - Desconectar +- `POST /instance/reconnect` - Reconectar +- `DELETE /instance/logout` - Fazer logout + +**Documentação completa:** [API de Instâncias](../guias-api/api-instances.md) + +--- + +### Mensagens (16 endpoints) + +**Envio:** +- `POST /send/text` - Mensagem de texto +- `POST /send/media` - Mídia (imagem/vídeo/áudio/documento) +- `POST /send/link` - Link com preview +- `POST /send/location` - Localização +- `POST /send/contact` - Contato +- `POST /send/poll` - Enquete +- `POST /send/sticker` - Sticker +- `POST /send/button` - Botões interativos +- `POST /send/list` - Lista de opções + +**Operações:** +- `POST /message/react` - Reagir à mensagem +- `POST /message/markread` - Marcar como lida +- `POST /message/edit` - Editar mensagem +- `POST /message/delete` - Deletar mensagem +- `POST /message/presence` - Status de presença (digitando/gravando) +- `POST /message/downloadmedia` - Download de mídia +- `POST /message/status` - Status de entrega/leitura + +**Documentação completa:** [API de Mensagens](../guias-api/api-messages.md) + +--- + +### Usuários (13 endpoints) + +- `POST /user/info` - Informações do usuário +- `POST /user/check` - Verificar número no WhatsApp +- `POST /user/avatar` - Obter avatar +- `GET /user/contacts` - Listar contatos +- `GET /user/privacy` - Configurações de privacidade +- `POST /user/privacy` - Atualizar privacidade +- `POST /user/block` - Bloquear contato +- `POST /user/unblock` - Desbloquear contato +- `GET /user/blocklist` - Lista de bloqueados +- `POST /user/profilePicture` - Atualizar foto de perfil +- `POST /user/profileName` - Atualizar nome +- `POST /user/profileStatus` - Atualizar status/recado + +**Documentação completa:** [API de Usuários](../guias-api/api-user.md) + +--- + +### Grupos (11 endpoints) + +- `GET /group/list` - Listar grupos +- `POST /group/create` - Criar grupo +- `POST /group/info` - Informações do grupo +- `POST /group/participant` - Gerenciar participantes +- `POST /group/photo` - Atualizar foto +- `POST /group/name` - Atualizar nome +- `POST /group/description` - Atualizar descrição +- `POST /group/invitelink` - Gerar link de convite +- `POST /group/join` - Entrar via link +- `POST /group/leave` - Sair do grupo +- `GET /group/myall` - Grupos do usuário + +**Documentação completa:** [API de Grupos](../guias-api/api-groups.md) + +--- + +### Chats (7 endpoints) + +- `POST /chat/pin` - Fixar conversa +- `POST /chat/unpin` - Desfixar conversa +- `POST /chat/archive` - Arquivar +- `POST /chat/unarchive` - Desarquivar +- `POST /chat/mute` - Silenciar +- `POST /chat/unmute` - Reativar notificações +- `POST /chat/history-sync` - Sincronizar histórico + +**Documentação completa:** [API de Chats](../guias-api/api-chats.md) + +--- + +### Labels (6 endpoints) + +- `POST /label/chat` - Adicionar label ao chat +- `POST /label/message` - Adicionar label à mensagem +- `POST /label/edit` - Editar label +- `GET /label/list` - Listar labels +- `POST /unlabel/chat` - Remover label do chat +- `POST /unlabel/message` - Remover label da mensagem + +**Documentação completa:** [API de Labels](../guias-api/api-labels.md) + +--- + +### Comunidades (3 endpoints) + +- `POST /community/create` - Criar comunidade +- `POST /community/add` - Adicionar grupo +- `POST /community/remove` - Remover grupo + +**Documentação completa:** [API de Comunidades](../guias-api/api-community.md) + +--- + +### Newsletters (6 endpoints) + +- `POST /newsletter/create` - Criar newsletter/canal +- `GET /newsletter/list` - Listar newsletters +- `POST /newsletter/info` - Informações da newsletter +- `POST /newsletter/link` - Gerar link de convite +- `POST /newsletter/subscribe` - Inscrever-se +- `POST /newsletter/messages` - Listar mensagens + +**Documentação completa:** [API de Newsletters](../guias-api/api-newsletter.md) + +--- + +### Chamadas (1 endpoint) + +- `POST /call/reject` - Rejeitar chamada recebida + +**Documentação completa:** [API de Chamadas](../guias-api/api-call.md) + +--- + +## Recursos Adicionais + +### Documentação Interativa + +- **Swagger UI**: http://localhost:4000/swagger/index.html (quando servidor estiver rodando) +- Teste endpoints diretamente no navegador +- Visualize payloads de request/response +- Documentação completa com exemplos + +### Guias de API + +- [Visão Geral da API](../guias-api/api-overview.md) +- [Autenticação](../conceitos-core/authentication.md) +- [Sistema de Eventos](../recursos-avancados/events-system.md) + +--- + +**Total de endpoints disponíveis: 79** + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/referencia/environment-variables.md b/docs/wiki/referencia/environment-variables.md new file mode 100644 index 0000000..a1abf27 --- /dev/null +++ b/docs/wiki/referencia/environment-variables.md @@ -0,0 +1,230 @@ +# Variáveis de Ambiente + +Referência rápida de variáveis de ambiente do Evolution GO. + +Para documentação detalhada, consulte: [Configuração](../fundamentos/configuration.md) + +--- + +## Obrigatórias + +| Variável | Descrição | Exemplo | +|----------|-----------|---------| +| `GLOBAL_API_KEY` | Chave de autenticação da API | `df16caad-d0d2-41b2-bec5-75b90048a0db` | +| `DATABASE_SAVE_MESSAGES` | Salvar mensagens no banco | `false` | + +--- + +## Servidor + +| Variável | Padrão | Descrição | +|----------|--------|-----------| +| `SERVER_PORT` | `4000` | Porta HTTP | +| `CLIENT_NAME` | `evolution` | Nome identificador | +| `OS_NAME` | `Linux` | Sistema operacional | + +--- + +## Banco de Dados + +| Variável | Descrição | +|----------|-----------| +| `POSTGRES_AUTH_DB` | Connection string banco de autenticação | +| `POSTGRES_USERS_DB` | Connection string banco de usuários | + +**Formato:** +```env +POSTGRES_AUTH_DB=postgresql://user:pass@host:5432/evogo_auth?sslmode=disable +POSTGRES_USERS_DB=postgresql://user:pass@host:5432/evogo_users?sslmode=disable +``` + +--- + +## Logs + +| Variável | Padrão | Valores | Descrição | +|----------|--------|---------|-----------| +| `WADEBUG` | `INFO` | `DEBUG`, `INFO`, `WARN`, `ERROR` | Nível de log | +| `LOGTYPE` | `console` | `console`, `file` | Destino de saída | +| `LOG_DIRECTORY` | `/app/logs` | - | Diretório de arquivos de log | +| `LOG_MAX_SIZE` | `100` | - | Tamanho máximo por arquivo (MB) | +| `LOG_MAX_BACKUPS` | `5` | - | Arquivos de backup a manter | +| `LOG_MAX_AGE` | `30` | - | Retenção em dias | +| `LOG_COMPRESS` | `true` | `true`/`false` | Compressão de logs antigos | + +--- + +## Conexão e Comportamento + +| Variável | Padrão | Descrição | +|----------|--------|-----------| +| `CONNECT_ON_STARTUP` | `false` | Conectar instâncias ao iniciar servidor | +| `WEBHOOKFILES` | `true` | Enviar URLs de mídia em webhooks | +| `QRCODE_MAX_COUNT` | `5` | Tentativas máximas de QR Code | +| `CHECK_USER_EXISTS` | `true` | Validar destinatário antes de enviar | + +--- + +## Eventos + +| Variável | Padrão | Descrição | +|----------|--------|-----------| +| `EVENT_IGNORE_GROUP` | `false` | Ignorar eventos de grupos | +| `EVENT_IGNORE_STATUS` | `true` | Ignorar eventos de status/stories | +| `WEBHOOK_URL` | - | URL para callbacks HTTP | + +--- + +## RabbitMQ (AMQP) + +| Variável | Descrição | +|----------|-----------| +| `AMQP_URL` | URL de conexão RabbitMQ | +| `AMQP_GLOBAL_ENABLED` | Habilitar filas globais | +| `AMQP_GLOBAL_EVENTS` | Eventos a publicar (separados por vírgula) | +| `AMQP_SPECIFIC_EVENTS` | Eventos específicos por instância | + +**Exemplo:** +```env +AMQP_URL=amqp://user:pass@rabbitmq:5672/vhost +AMQP_GLOBAL_ENABLED=true +AMQP_GLOBAL_EVENTS=messages.upsert,messages.update,connection.update +``` + +--- + +## NATS + +| Variável | Descrição | +|----------|-----------| +| `NATS_URL` | URL de conexão NATS | +| `NATS_GLOBAL_ENABLED` | Habilitar publicação global | +| `NATS_GLOBAL_EVENTS` | Eventos a publicar | + +**Exemplo:** +```env +NATS_URL=nats://nats:4222 +NATS_GLOBAL_ENABLED=true +NATS_GLOBAL_EVENTS=messages.upsert,connection.update +``` + +--- + +## MinIO/S3 + +| Variável | Descrição | +|----------|-----------| +| `MINIO_ENABLED` | Habilitar armazenamento S3-compatible | +| `MINIO_ENDPOINT` | Endpoint do servidor | +| `MINIO_ACCESS_KEY` | Access Key para autenticação | +| `MINIO_SECRET_KEY` | Secret Key para autenticação | +| `MINIO_BUCKET` | Nome do bucket | +| `MINIO_USE_SSL` | Utilizar HTTPS | +| `MINIO_REGION` | Região do bucket (AWS) | + +**Exemplo:** +```env +MINIO_ENABLED=true +MINIO_ENDPOINT=localhost:9000 +MINIO_ACCESS_KEY=minioadmin +MINIO_SECRET_KEY=minioadmin +MINIO_BUCKET=evolution-media +MINIO_USE_SSL=false +MINIO_REGION=us-east-1 +``` + +--- + +## Proxy HTTP + +| Variável | Descrição | +|----------|-----------| +| `PROXY_HOST` | Hostname do proxy | +| `PROXY_PORT` | Porta do proxy | +| `PROXY_USERNAME` | Usuário (opcional) | +| `PROXY_PASSWORD` | Senha (opcional) | + +**Exemplo:** +```env +PROXY_HOST=proxy.empresa.com +PROXY_PORT=8080 +PROXY_USERNAME=usuario +PROXY_PASSWORD=senha +``` + +--- + +## Recursos Adicionais + +| Variável | Descrição | +|----------|-----------| +| `API_AUDIO_CONVERTER` | URL de serviço de conversão de áudio | +| `API_AUDIO_CONVERTER_KEY` | Chave de autenticação do conversor | + +--- + +## Versão WhatsApp (Avançado) + +| Variável | Descrição | +|----------|-----------| +| `WHATSAPP_VERSION_MAJOR` | Versão major do WhatsApp Web | +| `WHATSAPP_VERSION_MINOR` | Versão minor do WhatsApp Web | +| `WHATSAPP_VERSION_PATCH` | Versão patch do WhatsApp Web | + +**⚠️ Atenção**: Modificar versão do WhatsApp pode resultar em bloqueio. Deixar vazio para usar versão automática. + +--- + +## Exemplo Completo + +```env +# Obrigatórias +GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db +DATABASE_SAVE_MESSAGES=false + +# Servidor +SERVER_PORT=4000 +CLIENT_NAME=evolution +OS_NAME=Linux + +# Banco de Dados +POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable +POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable + +# Logs +WADEBUG=INFO +LOGTYPE=console + +# Comportamento +CONNECT_ON_STARTUP=false +WEBHOOKFILES=true +CHECK_USER_EXISTS=true +EVENT_IGNORE_STATUS=true + +# Webhook +WEBHOOK_URL=https://seu-servidor.com/webhook + +# RabbitMQ (opcional) +AMQP_URL=amqp://admin:admin@rabbitmq:5672/default +AMQP_GLOBAL_ENABLED=true +AMQP_GLOBAL_EVENTS=messages.upsert,connection.update + +# MinIO (opcional) +MINIO_ENABLED=true +MINIO_ENDPOINT=minio:9000 +MINIO_ACCESS_KEY=minioadmin +MINIO_SECRET_KEY=minioadmin +MINIO_BUCKET=evolution-media +MINIO_USE_SSL=false +``` + +--- + +## Recursos + +- **[Configuração Detalhada](../fundamentos/configuration.md)** - Documentação completa de cada variável +- **[.env.example](https://git.evoai.app/Evolution/evolution-go/blob/main/docker/examples/.env.example)** - Arquivo de exemplo com todas as variáveis + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/referencia/error-codes.md b/docs/wiki/referencia/error-codes.md new file mode 100644 index 0000000..cb2dccd --- /dev/null +++ b/docs/wiki/referencia/error-codes.md @@ -0,0 +1,274 @@ +# Códigos de Erro + +Referência de códigos de erro HTTP e mensagens da aplicação. + +## Códigos HTTP + +| Código | Status | Descrição | +|--------|--------|-----------| +| `200` | OK | Requisição processada com sucesso | +| `201` | Created | Recurso criado com sucesso | +| `400` | Bad Request | Requisição inválida ou malformada | +| `401` | Unauthorized | Autenticação ausente ou inválida | +| `403` | Forbidden | Acesso negado ao recurso | +| `404` | Not Found | Recurso não encontrado | +| `409` | Conflict | Conflito com estado atual do recurso | +| `500` | Internal Server Error | Erro interno não tratado | + +--- + +## Erros de Autenticação + +### 401 Unauthorized + +```json +{ + "error": "Unauthorized" +} +``` + +**Causa**: Header `apikey` ausente ou valor inválido. + +**Resolução**: +```bash +curl -H "apikey: SUA-CHAVE-API" http://localhost:4000/endpoint +``` + +--- + +## Erros de Instância + +### 404 Instance Not Found + +```json +{ + "error": "Instance not found" +} +``` + +**Causa**: Instância com nome especificado não existe. + +**Resolução**: Verificar nome da instância ou criar nova via `POST /instance/create`. + +### 409 Instance Already Exists + +```json +{ + "error": "Instance already exists" +} +``` + +**Causa**: Tentativa de criar instância com nome duplicado. + +**Resolução**: Utilizar nome único ou deletar instância existente. + +### Instance Not Connected + +```json +{ + "error": "Instance is not connected" +} +``` + +**Causa**: Operação requer instância conectada ao WhatsApp. + +**Resolução**: Conectar instância via QR Code (`POST /instance/connect`) ou pairing code. + +--- + +## Erros de Validação + +### 400 Invalid Phone Number + +```json +{ + "error": "Invalid phone number format" +} +``` + +**Causa**: Formato de número incorreto. + +**Resolução**: Utilizar formato internacional sem símbolos. +- Correto: `5511999999999` (DDI + DDD + número) +- Incorreto: `+55 (11) 99999-9999`, `11999999999` + +### 400 Required Field Missing + +```json +{ + "error": "Field 'instanceName' is required" +} +``` + +**Causa**: Campo obrigatório ausente no body da requisição. + +**Resolução**: Incluir campo obrigatório no payload JSON. + +### 400 Invalid JSON + +```json +{ + "error": "Invalid JSON" +} +``` + +**Causa**: Sintaxe JSON inválida ou header Content-Type incorreto. + +**Resolução**: +- Validar sintaxe JSON +- Incluir header: `Content-Type: application/json` + +--- + +## Erros de Infraestrutura + +### 500 Database Connection Error + +```json +{ + "error": "Database connection failed" +} +``` + +**Causa**: Falha ao conectar com PostgreSQL. + +**Diagnóstico**: +```bash +# Verificar status do PostgreSQL +docker-compose ps postgres + +# Verificar logs +docker-compose logs postgres + +# Testar conectividade +docker-compose exec evolution-go nc -zv postgres 5432 +``` + +**Resolução**: +- Verificar variáveis `POSTGRES_AUTH_DB` e `POSTGRES_USERS_DB` +- Confirmar que PostgreSQL está rodando +- Validar credenciais de acesso + +### 500 Queue Connection Error + +```json +{ + "error": "Failed to connect to message queue" +} +``` + +**Causa**: Falha ao conectar com RabbitMQ/NATS. + +**Resolução**: +- Verificar variável `AMQP_URL` ou `NATS_URL` +- Confirmar que serviço de fila está rodando +- Validar credenciais e permissões + +--- + +## Erros de Negócio + +### User Not Found on WhatsApp + +```json +{ + "error": "User not found on WhatsApp" +} +``` + +**Causa**: Número destinatário não está registrado no WhatsApp. + +**Resolução**: Verificar número ou desabilitar validação (`CHECK_USER_EXISTS=false`). + +### Message Send Failed + +```json +{ + "error": "Failed to send message", + "details": "..." +} +``` + +**Causas comuns**: +- Número bloqueou sua instância +- Mensagem violou políticas do WhatsApp +- Instância foi bloqueada/banida +- Problema de conectividade + +**Diagnóstico**: +```bash +# Verificar logs detalhados +docker-compose logs -f evolution-go + +# Verificar status da instância +curl -H "apikey: SUA-CHAVE" \ + "http://localhost:4000/instance/status?instanceName=NOME" +``` + +--- + +## Debugging + +### Habilitar Logs Detalhados + +```env +WADEBUG=DEBUG +``` + +### Verificar Logs + +```bash +# Docker Compose +docker-compose logs -f evolution-go + +# Docker (container específico) +docker logs -f evolution-go --tail=100 + +# Arquivo (se LOGTYPE=file) +tail -f logs/evolution-go.log +``` + +### Logs Estruturados + +Logs incluem: +- **Timestamp**: Data/hora do evento +- **Level**: DEBUG, INFO, WARN, ERROR +- **Module**: Componente que gerou o log +- **Message**: Descrição do evento +- **Context**: Dados adicionais (instanceName, userId, etc) + +--- + +## Códigos de Erro por Categoria + +### Autenticação (401, 403) +- API key inválida +- Token expirado +- Permissões insuficientes + +### Validação (400) +- JSON malformado +- Campos obrigatórios ausentes +- Formato inválido + +### Recurso (404, 409) +- Instância não encontrada +- Recurso duplicado +- Estado inconsistente + +### Servidor (500, 503) +- Erro de banco de dados +- Timeout de operação +- Serviço indisponível + +--- + +## Recursos Adicionais + +- **[Debugging](../desenvolvimento/debugging.md)** - Guia completo de debugging +- **[FAQ](./faq.md)** - Problemas comuns e soluções +- **[Logs](../fundamentos/configuration.md#logs-e-debug)** - Configuração de logs + +--- + +**Documentação Evolution GO v1.0** diff --git a/docs/wiki/referencia/faq.md b/docs/wiki/referencia/faq.md new file mode 100644 index 0000000..8bb0f7b --- /dev/null +++ b/docs/wiki/referencia/faq.md @@ -0,0 +1,274 @@ +# FAQ - Perguntas Frequentes + +Respostas para questões comuns sobre o Evolution GO. + +## Visão Geral + +### O que é Evolution GO? + +Gateway de API WhatsApp construído em Go que fornece interface RESTful para comunicação com o protocolo WhatsApp Web. Permite automação de mensagens, gerenciamento multi-instância e integração via APIs padronizadas. + +### Diferença entre Evolution GO e Evolution API (Node.js)? + +- **Evolution GO**: Implementação em Go, foco em performance e baixo consumo de recursos +- **Evolution API V2**: Implementação em Node.js/TypeScript, maior maturidade e conjunto de features + +Ambos utilizam a biblioteca whatsmeow para conexão com WhatsApp. + +### Suporte a múltiplas instâncias? + +Sim. É possível gerenciar quantas instâncias forem necessárias, cada uma representando uma conta WhatsApp independente com sessão isolada. + +--- + +## Instalação + +### SQLite vs PostgreSQL + +**PostgreSQL** é fortemente recomendado para produção devido a: +- Performance superior em ambientes multiusuário +- Suporte a conexões concorrentes +- Recursos empresariais (replicação, backup incremental) + +SQLite é adequado apenas para desenvolvimento/testes. + +### Geração de API Key + +```bash +# UUID v4 (recomendado) +uuidgen + +# OpenSSL +openssl rand -hex 32 + +# Python +python3 -c "import uuid; print(uuid.uuid4())" +``` + +--- + +## Operações + +### Processo de Conexão + +1. Criar instância: `POST /instance/create` +2. Iniciar conexão: `POST /instance/connect` +3. Obter QR Code: `GET /instance/qr?instanceName=NOME` +4. Escanear QR Code no WhatsApp (Aparelhos Conectados) +5. Aguardar estabelecimento da conexão + +### Validade do QR Code + +Aproximadamente 40 segundos. Após expiração, novo QR Code é gerado automaticamente até atingir `QRCODE_MAX_COUNT` (padrão: 5 tentativas). + +### Envio para Múltiplos Destinatários + +Realizar requisições individuais para cada destinatário. Para volume alto: +- Implementar fila de envio +- Adicionar delay entre requisições (2-5 segundos recomendado) +- Utilizar worker pool para paralelização controlada + +### Limites de Envio + +O WhatsApp não divulga limites oficiais, mas observa-se: +- Aproximadamente 1000 mensagens/dia para números não salvos +- Risco de bloqueio com padrões identificados como spam +- Recomendações: + - Começar com volume baixo (~100/dia) + - Escalar gradualmente + - Personalizar mensagens + - Evitar conteúdo idêntico em massa + - Respeitar opt-out de usuários + +### Recepção de Mensagens + +Configure webhook ao criar instância ou via atualização: + +```json +{ + "instanceName": "nome-instancia", + "webhook": "https://seu-servidor.com/webhook" +} +``` + +Eventos serão enviados via POST HTTP para o endpoint configurado. + +--- + +## Troubleshooting + +### QR Code Não Exibido + +**Diagnóstico**: +```bash +docker-compose logs -f evolution-go +``` + +**Soluções**: +- Verificar conectividade com banco de dados +- Deletar e recriar instância +- Verificar logs para erros específicos + +### Falha no Envio de Mensagens + +**Verificações**: +1. Status da conexão: `GET /instance/status?instanceName=NOME` +2. Formato do número: DDI + DDD + número (ex: `5511999999999`) +3. Validação do destinatário: `CHECK_USER_EXISTS=true` + +### Desconexão Espontânea + +**Causas comuns**: +- WhatsApp Web ativo em outro dispositivo +- Bloqueio preventivo do WhatsApp +- Instabilidade de rede +- Versão do protocolo desatualizada + +**Resolução**: Reconectar via `POST /instance/reconnect` + +### Webhook Não Recebe Eventos + +**Verificações**: +- URL acessível publicamente (não localhost) +- Endpoint retorna status 200 +- Firewall/proxy não bloqueando +- Logs: `docker-compose logs -f evolution-go | grep webhook` + +--- + +## Performance + +### Capacidade por Servidor + +Estimativas baseadas em uso típico: + +| RAM | CPU | Instâncias Estimadas | +|-----|-----|---------------------| +| 1GB | 1 core | 5-10 | +| 2GB | 2 cores | 20-30 | +| 4GB | 4 cores | 50-100 | +| 8GB | 8 cores | 200+ | + +**Fatores de impacto**: +- Volume de mensagens +- Uso de webhook vs filas +- `DATABASE_SAVE_MESSAGES` habilitado +- Processamento de mídia + +### Otimização + +**Configuração**: +```env +# Desabilitar salvamento de mensagens +DATABASE_SAVE_MESSAGES=false + +# Ignorar eventos desnecessários +EVENT_IGNORE_STATUS=true +EVENT_IGNORE_GROUP=false # conforme necessidade + +# Usar PostgreSQL +POSTGRES_AUTH_DB=postgresql://... +POSTGRES_USERS_DB=postgresql://... +``` + +**Infraestrutura**: +- Connection pooling adequado +- Índices de banco otimizados +- Escalabilidade horizontal (múltiplos servidores) +- Load balancer para distribuição + +--- + +## Segurança + +### Proteção de API Key + +- Não versionar no controle de código +- Utilizar variáveis de ambiente +- Rotação periódica (recomendado: 90 dias) +- HTTPS obrigatório em produção +- Rate limiting por chave + +### Armazenamento de Mensagens + +Configurar `DATABASE_SAVE_MESSAGES=false` se histórico não for necessário: +- Reduz uso de storage +- Melhora privacidade +- Aumenta performance + +### Backup Seguro + +```bash +# Backup com criptografia +docker exec postgres pg_dumpall -U postgres | \ + gzip | \ + gpg --encrypt --recipient seu@email.com \ + > backup-$(date +%Y%m%d).sql.gz.gpg + +# Restauração +gpg --decrypt backup-20250111.sql.gz.gpg | \ + gunzip | \ + docker exec -i postgres psql -U postgres +``` + +--- + +## Limitações do WhatsApp + +### Envio para Números Não Salvos + +WhatsApp limita envios para números não salvos na agenda. Boas práticas: +- Priorizar números salvos +- Aguardar resposta antes de enviar mais mensagens +- Evitar volume alto para números desconhecidos + +### Prevenção de Banimento + +**Práticas recomendadas**: +- Não enviar spam +- Respeitar opt-out de usuários +- Usar contas WhatsApp Business verificadas +- Adicionar delay entre mensagens +- Personalizar conteúdo + +**Em caso de bloqueio**: +- Utilizar número diferente +- Considerar WhatsApp Business API oficial +- Revisar práticas de envio + +--- + +## Desenvolvimento + +### Contribuição + +Consulte [Guia de Contribuição](../desenvolvimento/contributing.md) para processo de contribuição ao projeto. + +### Reporte de Bugs + +Utilize [Issues no GitLab](https://git.evoai.app/Evolution/evolution-go/issues) incluindo: +- Versão do Evolution GO +- Ambiente (Docker/local, SO) +- Steps to reproduce +- Logs relevantes +- Comportamento esperado vs observado + +--- + +## Recursos + +### Documentação +- [Guia de Instalação](../fundamentos/installation.md) +- [Configuração](../fundamentos/configuration.md) +- [Referência de API](./api-reference.md) +- [Swagger UI](http://localhost:4000/swagger/index.html) + +### Suporte +- [Issues GitLab](https://git.evoai.app/Evolution/evolution-go/issues) +- [Documentação Completa](https://git.evoai.app/Evolution/evolution-go/-/wikis) + +--- + +**Não encontrou resposta?** Abra uma [issue](https://git.evoai.app/Evolution/evolution-go/issues) com sua questão. + +**Documentação Evolution GO v1.0** diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e877705 --- /dev/null +++ b/go.mod @@ -0,0 +1,103 @@ +module github.com/EvolutionAPI/evolution-go + +go 1.25.0 + +require ( + github.com/EvolutionAPI/evo-gate v0.1.2 + github.com/chai2010/webp v1.1.1 + github.com/gabriel-vasile/mimetype v1.4.5 + github.com/gin-gonic/gin v1.10.0 + github.com/gomessguii/logger v0.0.3 + github.com/google/uuid v1.6.0 + github.com/gorilla/websocket v1.5.3 + github.com/joho/godotenv v1.5.1 + github.com/lib/pq v1.10.9 + github.com/minio/minio-go/v7 v7.0.80 + github.com/nats-io/nats.go v1.39.0 + github.com/patrickmn/go-cache v2.1.0+incompatible + github.com/rabbitmq/amqp091-go v1.10.0 + github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e + github.com/swaggo/files v1.0.1 + github.com/swaggo/gin-swagger v1.6.0 + github.com/swaggo/swag v1.16.3 + github.com/vincent-petithory/dataurl v1.0.0 + go.mau.fi/whatsmeow v0.0.0-00010101000000-000000000000 + golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a + golang.org/x/image v0.0.0-20211028202545-6944b10bf410 + golang.org/x/net v0.50.0 + google.golang.org/protobuf v1.36.11 + gopkg.in/natefinch/lumberjack.v2 v2.2.1 + gorm.io/driver/postgres v1.5.9 + gorm.io/gorm v1.25.10 + modernc.org/sqlite v1.33.1 +) + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/beeper/argo-go v1.1.2 // indirect + github.com/bytedance/sonic v1.12.2 // indirect + github.com/bytedance/sonic/loader v0.2.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/coder/websocket v1.8.14 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-ini/ini v1.67.0 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.21.0 // indirect + github.com/go-openapi/spec v0.21.0 // indirect + github.com/go-openapi/swag v0.23.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.22.0 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/pgx/v5 v5.5.5 // indirect + github.com/jackc/puddle/v2 v2.2.1 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/compress v1.17.11 // indirect + github.com/klauspost/cpuid/v2 v2.2.8 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/minio/md5-simd v1.1.2 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/nats-io/nkeys v0.4.9 // indirect + github.com/nats-io/nuid v1.0.1 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rogpeppe/go-internal v1.12.0 // indirect + github.com/rs/xid v1.6.0 // indirect + github.com/rs/zerolog v1.34.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + github.com/vektah/gqlparser/v2 v2.5.27 // indirect + go.mau.fi/libsignal v0.2.1 // indirect + go.mau.fi/util v0.9.6 // indirect + golang.org/x/arch v0.10.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/text v0.34.0 // indirect + golang.org/x/tools v0.42.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect + modernc.org/libc v1.55.3 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect + modernc.org/strutil v1.2.0 // indirect + modernc.org/token v1.1.0 // indirect +) + +replace go.mau.fi/whatsmeow => ./whatsmeow-lib diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b2d291d --- /dev/null +++ b/go.sum @@ -0,0 +1,283 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= +github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= +github.com/EvolutionAPI/evo-gate v0.1.2 h1:ZPQ9SZ7OlajNU1pbtYqbMg1U/ZiUSKmlrYk0GHWOXkc= +github.com/EvolutionAPI/evo-gate v0.1.2/go.mod h1:48tcAgZ0yVojqLdmLpOSyWDGqPODBYXYRSEs2yIUI/w= +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= +github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM= +github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= +github.com/beeper/argo-go v1.1.2 h1:UQI2G8F+NLfGTOmTUI0254pGKx/HUU/etbUGTJv91Fs= +github.com/beeper/argo-go v1.1.2/go.mod h1:M+LJAnyowKVQ6Rdj6XYGEn+qcVFkb3R/MUpqkGR0hM4= +github.com/bytedance/sonic v1.12.2 h1:oaMFuRTpMHYLpCntGca65YWt5ny+wAceDERTkT2L9lg= +github.com/bytedance/sonic v1.12.2/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM= +github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/chai2010/webp v1.1.1 h1:jTRmEccAJ4MGrhFOrPMpNGIJ/eybIgwKpcACsrTEapk= +github.com/chai2010/webp v1.1.1/go.mod h1:0XVwvZWdjjdxpUEIf7b9g9VkHFnInUSYujwqTLEuldU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= +github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg= +github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo= +github.com/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4= +github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4= +github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4= +github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= +github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= +github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= +github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= +github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= +github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= +github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= +github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= +github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.22.0 h1:k6HsTZ0sTnROkhS//R0O+55JgM8C4Bx7ia+JlgcnOao= +github.com/go-playground/validator/v10 v10.22.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gomessguii/logger v0.0.3 h1:985MqDkp2Fi6IQ3eQ3NG7VXZo8flbWd+6QUj9hASWJA= +github.com/gomessguii/logger v0.0.3/go.mod h1:JBfDf2h4qUFaIjpE/0T4/jeLpIHopc73k+G9+iu9+ms= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw= +github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A= +github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= +github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= +github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM= +github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk= +github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.0.80 h1:2mdUHXEykRdY/BigLt3Iuu1otL0JTogT0Nmltg0wujk= +github.com/minio/minio-go/v7 v7.0.80/go.mod h1:84gmIilaX4zcvAWWzJ5Z1WI5axN+hAbM5w25xf8xvC0= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/nats-io/nats.go v1.39.0 h1:2/yg2JQjiYYKLwDuBzV0FbB2sIV+eFNkEevlRi4n9lI= +github.com/nats-io/nats.go v1.39.0/go.mod h1:MgRb8oOdigA6cYpEPhXJuRVH6UE/V4jblJ2jQ27IXYM= +github.com/nats-io/nkeys v0.4.9 h1:qe9Faq2Gxwi6RZnZMXfmGMZkg3afLLOtrU+gDZJ35b0= +github.com/nats-io/nkeys v0.4.9/go.mod h1:jcMqs+FLG+W5YO36OX6wFIFcmpdAns+w1Wm6D3I/evE= +github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 h1:KPpdlQLZcHfTMQRi6bFQ7ogNO0ltFT4PmtwTLW4W+14= +github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw= +github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY= +github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ= +github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= +github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= +github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= +github.com/swaggo/gin-swagger v1.6.0 h1:y8sxvQ3E20/RCyrXeFfg60r6H0Z+SwpTjMYsMm+zy8M= +github.com/swaggo/gin-swagger v1.6.0/go.mod h1:BG00cCEy294xtVpyIAHG6+e2Qzj/xKlRdOqDkvq0uzo= +github.com/swaggo/swag v1.16.3 h1:PnCYjPCah8FK4I26l2F/KQ4yz3sILcVUN3cTlBFA9Pg= +github.com/swaggo/swag v1.16.3/go.mod h1:DImHIuOFXKpMFAQjcC7FG4m3Dg4+QuUgUzJmKjI/gRk= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s= +github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo= +github.com/vincent-petithory/dataurl v1.0.0 h1:cXw+kPto8NLuJtlMsI152irrVw9fRDX8AbShPRpg2CI= +github.com/vincent-petithory/dataurl v1.0.0/go.mod h1:FHafX5vmDzyP+1CQATJn7WFKc9CvnvxyvZy6I1MrG/U= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mau.fi/libsignal v0.2.1 h1:vRZG4EzTn70XY6Oh/pVKrQGuMHBkAWlGRC22/85m9L0= +go.mau.fi/libsignal v0.2.1/go.mod h1:iVvjrHyfQqWajOUaMEsIfo3IqgVMrhWcPiiEzk7NgoU= +go.mau.fi/util v0.9.6 h1:2nsvxm49KhI3wrFltr0+wSUBlnQ4CMtykuELjpIU+ts= +go.mau.fi/util v0.9.6/go.mod h1:sIJpRH7Iy5Ad1SBuxQoatxtIeErgzxCtjd/2hCMkYMI= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= +golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a h1:ovFr6Z0MNmU7nH8VaX5xqw+05ST2uO1exVfZPVqRC5o= +golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA= +golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ= +golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= +golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60= +golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= +golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= +gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8= +gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI= +gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s= +gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= +modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= +modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= +modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= +modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= +modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= +modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= +modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM= +modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= diff --git a/manager/dist/assets/index-BsMXpWP7.css b/manager/dist/assets/index-BsMXpWP7.css new file mode 100644 index 0000000..e97c33b --- /dev/null +++ b/manager/dist/assets/index-BsMXpWP7.css @@ -0,0 +1 @@ +@layer properties;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-100: oklch(93.6% .032 17.717);--color-red-500: oklch(63.7% .237 25.331);--color-red-600: oklch(57.7% .245 27.325);--color-red-700: oklch(50.5% .213 27.518);--color-red-800: oklch(44.4% .177 26.899);--color-orange-100: oklch(95.4% .038 75.164);--color-orange-500: oklch(70.5% .213 47.604);--color-orange-600: oklch(64.6% .222 41.116);--color-orange-700: oklch(55.3% .195 38.402);--color-yellow-100: oklch(97.3% .071 103.193);--color-yellow-400: oklch(85.2% .199 91.936);--color-yellow-500: oklch(79.5% .184 86.047);--color-yellow-600: oklch(68.1% .162 75.834);--color-yellow-700: oklch(55.4% .135 66.442);--color-green-50: oklch(98.2% .018 155.826);--color-green-100: oklch(96.2% .044 156.743);--color-green-200: oklch(92.5% .084 155.995);--color-green-400: oklch(79.2% .209 151.711);--color-green-500: oklch(72.3% .219 149.579);--color-green-600: oklch(62.7% .194 149.214);--color-green-700: oklch(52.7% .154 150.069);--color-green-800: oklch(44.8% .119 151.328);--color-blue-50: oklch(97% .014 254.604);--color-blue-100: oklch(93.2% .032 255.585);--color-blue-200: oklch(88.2% .059 254.128);--color-blue-400: oklch(70.7% .165 254.624);--color-blue-500: oklch(62.3% .214 259.815);--color-blue-600: oklch(54.6% .245 262.881);--color-blue-700: oklch(48.8% .243 264.376);--color-blue-800: oklch(42.4% .199 265.638);--color-blue-900: oklch(37.9% .146 265.522);--color-purple-50: oklch(97.7% .014 308.299);--color-purple-100: oklch(94.6% .033 307.174);--color-purple-200: oklch(90.2% .063 306.703);--color-purple-500: oklch(62.7% .265 303.9);--color-purple-600: oklch(55.8% .288 302.321);--color-purple-700: oklch(49.6% .265 301.924);--color-purple-900: oklch(38.1% .176 304.987);--color-pink-50: oklch(97.1% .014 343.198);--color-pink-500: oklch(65.6% .241 354.308);--color-pink-600: oklch(59.2% .249 .584);--color-slate-50: oklch(98.4% .003 247.858);--color-slate-800: oklch(27.9% .041 260.031);--color-slate-900: oklch(20.8% .042 265.755);--color-gray-400: oklch(70.7% .022 261.325);--color-gray-600: oklch(44.6% .03 256.802);--color-gray-700: oklch(37.3% .034 259.733);--color-gray-900: oklch(21% .034 264.665);--color-black: #000;--color-white: #fff;--spacing: .25rem;--container-xs: 20rem;--container-sm: 24rem;--container-md: 28rem;--container-lg: 32rem;--container-2xl: 42rem;--container-4xl: 56rem;--container-6xl: 72rem;--text-xs: .75rem;--text-xs--line-height: calc(1 / .75);--text-sm: .875rem;--text-sm--line-height: calc(1.25 / .875);--text-base: 1rem;--text-base--line-height: 1.5 ;--text-lg: 1.125rem;--text-lg--line-height: calc(1.75 / 1.125);--text-xl: 1.25rem;--text-xl--line-height: calc(1.75 / 1.25);--text-2xl: 1.5rem;--text-2xl--line-height: calc(2 / 1.5);--text-3xl: 1.875rem;--text-3xl--line-height: 1.2 ;--text-4xl: 2.25rem;--text-4xl--line-height: calc(2.5 / 2.25);--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--font-weight-bold: 700;--tracking-tight: -.025em;--tracking-widest: .1em;--leading-tight: 1.25;--leading-snug: 1.375;--leading-relaxed: 1.625;--radius-xs: .125rem;--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--animate-pulse: pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--aspect-video: 16 / 9;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-background: var(--background);--color-foreground: var(--foreground);--color-primary: var(--primary);--color-primary-foreground: var(--primary-foreground);--color-secondary: var(--secondary);--color-secondary-foreground: var(--secondary-foreground);--color-muted: var(--muted);--color-muted-foreground: var(--muted-foreground);--color-accent: var(--accent);--color-accent-foreground: var(--accent-foreground);--color-destructive: var(--destructive);--color-destructive-foreground: var(--destructive-foreground);--color-border: var(--border);--color-input: var(--input);--color-ring: var(--ring)}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings, normal);font-variation-settings:var(--default-mono-font-variation-settings, normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:currentcolor}@supports (color: color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.\@container\/card-header{container-type:inline-size;container-name:card-header}.pointer-events-none{pointer-events:none}.invisible{visibility:hidden}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing) * 0)}.inset-x-0{inset-inline:calc(var(--spacing) * 0)}.inset-y-0{inset-block:calc(var(--spacing) * 0)}.-top-2{top:calc(var(--spacing) * -2)}.-top-12{top:calc(var(--spacing) * -12)}.top-0{top:calc(var(--spacing) * 0)}.top-1\.5{top:calc(var(--spacing) * 1.5)}.top-1\/2{top:50%}.top-2{top:calc(var(--spacing) * 2)}.top-3\.5{top:calc(var(--spacing) * 3.5)}.top-4{top:calc(var(--spacing) * 4)}.top-\[1px\]{top:1px}.top-\[50\%\]{top:50%}.top-\[60\%\]{top:60%}.top-full{top:100%}.-right-0{right:calc(var(--spacing) * -0)}.-right-2{right:calc(var(--spacing) * -2)}.-right-12{right:calc(var(--spacing) * -12)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.right-2{right:calc(var(--spacing) * 2)}.right-3{right:calc(var(--spacing) * 3)}.right-4{right:calc(var(--spacing) * 4)}.-bottom-0{bottom:calc(var(--spacing) * -0)}.-bottom-12{bottom:calc(var(--spacing) * -12)}.bottom-0{bottom:calc(var(--spacing) * 0)}.-left-12{left:calc(var(--spacing) * -12)}.left-0{left:calc(var(--spacing) * 0)}.left-1\/2{left:50%}.left-2{left:calc(var(--spacing) * 2)}.left-3{left:calc(var(--spacing) * 3)}.left-4{left:calc(var(--spacing) * 4)}.left-\[50\%\]{left:50%}.isolate{isolation:isolate}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[1\]{z-index:1}.col-span-2{grid-column:span 2 / span 2}.col-span-3{grid-column:span 3 / span 3}.col-start-2{grid-column-start:2}.row-span-2{grid-row:span 2 / span 2}.row-span-3{grid-row:span 3 / span 3}.row-start-1{grid-row-start:1}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-2{margin-inline:calc(var(--spacing) * 2)}.mx-3\.5{margin-inline:calc(var(--spacing) * 3.5)}.mx-auto{margin-inline:auto}.my-0\.5{margin-block:calc(var(--spacing) * .5)}.my-1{margin-block:calc(var(--spacing) * 1)}.my-4{margin-block:calc(var(--spacing) * 4)}.-mt-1{margin-top:calc(var(--spacing) * -1)}.-mt-4{margin-top:calc(var(--spacing) * -4)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing) * 1)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.-ml-1{margin-left:calc(var(--spacing) * -1)}.-ml-4{margin-left:calc(var(--spacing) * -4)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-4{margin-left:calc(var(--spacing) * 4)}.ml-8{margin-left:calc(var(--spacing) * 8)}.ml-12{margin-left:calc(var(--spacing) * 12)}.ml-auto{margin-left:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.table-caption{display:table-caption}.table-cell{display:table-cell}.table-row{display:table-row}.field-sizing-content{field-sizing:content}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:var(--aspect-video)}.size-\(--cell-size\){width:var(--cell-size);height:var(--cell-size)}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.size-2\.5{width:calc(var(--spacing) * 2.5);height:calc(var(--spacing) * 2.5)}.size-3{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-7{width:calc(var(--spacing) * 7);height:calc(var(--spacing) * 7)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-auto{width:auto;height:auto}.size-full{width:100%;height:100%}.h-\(--cell-size\){height:var(--cell-size)}.h-1{height:calc(var(--spacing) * 1)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-2\.5{height:calc(var(--spacing) * 2.5)}.h-3{height:calc(var(--spacing) * 3)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-20{height:calc(var(--spacing) * 20)}.h-24{height:calc(var(--spacing) * 24)}.h-32{height:calc(var(--spacing) * 32)}.h-48{height:calc(var(--spacing) * 48)}.h-\[1\.15rem\]{height:1.15rem}.h-\[100px\]{height:100px}.h-\[150px\]{height:150px}.h-\[200px\]{height:200px}.h-\[300px\]{height:300px}.h-\[400px\]{height:400px}.h-\[500px\]{height:500px}.h-\[calc\(100\%-1px\)\]{height:calc(100% - 1px)}.h-\[var\(--radix-navigation-menu-viewport-height\)\]{height:var(--radix-navigation-menu-viewport-height)}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-auto{height:auto}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.h-svh{height:100svh}.max-h-\(--radix-context-menu-content-available-height\){max-height:var(--radix-context-menu-content-available-height)}.max-h-\(--radix-dropdown-menu-content-available-height\){max-height:var(--radix-dropdown-menu-content-available-height)}.max-h-\(--radix-select-content-available-height\){max-height:var(--radix-select-content-available-height)}.max-h-\[80vh\]{max-height:80vh}.max-h-\[300px\]{max-height:300px}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-4{min-height:calc(var(--spacing) * 4)}.min-h-16{min-height:calc(var(--spacing) * 16)}.min-h-\[80px\]{min-height:80px}.min-h-\[100px\]{min-height:100px}.min-h-\[100vh\]{min-height:100vh}.min-h-svh{min-height:100svh}.w-\(--cell-size\){width:var(--cell-size)}.w-0{width:calc(var(--spacing) * 0)}.w-1{width:calc(var(--spacing) * 1)}.w-1\/2{width:50%}.w-2{width:calc(var(--spacing) * 2)}.w-2\.5{width:calc(var(--spacing) * 2.5)}.w-2\/3{width:calc(2/3 * 100%)}.w-3{width:calc(var(--spacing) * 3)}.w-3\/4{width:75%}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-9{width:calc(var(--spacing) * 9)}.w-10{width:calc(var(--spacing) * 10)}.w-12{width:calc(var(--spacing) * 12)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-18{width:calc(var(--spacing) * 18)}.w-20{width:calc(var(--spacing) * 20)}.w-24{width:calc(var(--spacing) * 24)}.w-32{width:calc(var(--spacing) * 32)}.w-48{width:calc(var(--spacing) * 48)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-72{width:calc(var(--spacing) * 72)}.w-80{width:calc(var(--spacing) * 80)}.w-96{width:calc(var(--spacing) * 96)}.w-\[--radix-dropdown-menu-trigger-width\]{width:--radix-dropdown-menu-trigger-width}.w-\[50px\]{width:50px}.w-\[100px\]{width:100px}.w-\[180px\]{width:180px}.w-\[200px\]{width:200px}.w-\[250px\]{width:250px}.w-\[280px\]{width:280px}.w-\[300px\]{width:300px}.w-\[350px\]{width:350px}.w-\[400px\]{width:400px}.w-\[500px\]{width:500px}.w-\[600px\]{width:600px}.w-\[var\(--sidebar-width\)\]{width:var(--sidebar-width)}.w-auto{width:auto}.w-fit{width:fit-content}.w-full{width:100%}.w-max{width:max-content}.w-px{width:1px}.max-w-\(--skeleton-width\){max-width:var(--skeleton-width)}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-6xl{max-width:var(--container-6xl)}.max-w-\[calc\(100\%-2rem\)\]{max-width:calc(100% - 2rem)}.max-w-lg{max-width:var(--container-lg)}.max-w-max{max-width:max-content}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.max-w-xs{max-width:var(--container-xs)}.min-w-\(--cell-size\){min-width:var(--cell-size)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-5{min-width:calc(var(--spacing) * 5)}.min-w-8{min-width:calc(var(--spacing) * 8)}.min-w-9{min-width:calc(var(--spacing) * 9)}.min-w-10{min-width:calc(var(--spacing) * 10)}.min-w-56{min-width:calc(var(--spacing) * 56)}.min-w-\[8rem\]{min-width:8rem}.min-w-\[12rem\]{min-width:12rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.flex-1{flex:1}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.grow-0{flex-grow:0}.basis-full{flex-basis:100%}.caption-bottom{caption-side:bottom}.border-collapse{border-collapse:collapse}.origin-\(--radix-context-menu-content-transform-origin\){transform-origin:var(--radix-context-menu-content-transform-origin)}.origin-\(--radix-dropdown-menu-content-transform-origin\){transform-origin:var(--radix-dropdown-menu-content-transform-origin)}.origin-\(--radix-hover-card-content-transform-origin\){transform-origin:var(--radix-hover-card-content-transform-origin)}.origin-\(--radix-menubar-content-transform-origin\){transform-origin:var(--radix-menubar-content-transform-origin)}.origin-\(--radix-select-content-transform-origin\){transform-origin:var(--radix-select-content-transform-origin)}.origin-\(--radix-tooltip-content-transform-origin\){transform-origin:var(--radix-tooltip-content-transform-origin)}.-translate-x-1\/2{--tw-translate-x: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-x-px{--tw-translate-x: -1px;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-\[-50\%\]{--tw-translate-x: -50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-px{--tw-translate-x: 1px;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-0\.5{--tw-translate-y: calc(var(--spacing) * .5);translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[-50\%\]{--tw-translate-y: -50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[calc\(-50\%_-_2px\)\]{--tw-translate-y: calc(-50% - 2px) ;translate:var(--tw-translate-x) var(--tw-translate-y)}.rotate-45{rotate:45deg}.rotate-90{rotate:90deg}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.animate-caret-blink{animation:caret-blink 1.25s ease-out infinite}.animate-in{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize-none{resize:none}.scroll-my-1{scroll-margin-block:calc(var(--spacing) * 1)}.scroll-py-1{scroll-padding-block:calc(var(--spacing) * 1)}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.list-none{list-style-type:none}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.auto-rows-min{grid-auto-rows:min-content}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-\[0_1fr\]{grid-template-columns:0 1fr}.grid-rows-\[auto_auto\]{grid-template-rows:auto auto}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.justify-items-start{justify-items:start}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}:where(.space-y-0>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 0) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 0) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-8>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 8) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 8) * calc(1 - var(--tw-space-y-reverse)))}:where(.-space-x-2>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * -2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * -2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-2>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-3>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-4>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 4) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-6>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 6) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-x-reverse)))}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.self-start{align-self:flex-start}.justify-self-end{justify-self:flex-end}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-x-hidden{overflow-x:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[4px\]{border-radius:4px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:calc(infinity * 1px)}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-none{border-radius:0}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:calc(var(--radius) + 4px)}.rounded-xs{border-radius:var(--radius-xs)}.rounded-l-md{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.rounded-tl-sm{border-top-left-radius:calc(var(--radius) - 4px)}.rounded-r-md{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-\[1\.5px\]{border-style:var(--tw-border-style);border-width:1.5px}.border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style: dashed;border-style:dashed}.border-\(--color-border\){border-color:var(--color-border)}.border-background{border-color:var(--background)}.border-blue-200{border-color:var(--color-blue-200)}.border-border\/50{border-color:var(--border)}@supports (color: color-mix(in lab,red,red)){.border-border\/50{border-color:color-mix(in oklab,var(--border) 50%,transparent)}}.border-current{border-color:currentcolor}.border-destructive{border-color:var(--destructive)}.border-destructive\/20{border-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.border-destructive\/20{border-color:color-mix(in oklab,var(--destructive) 20%,transparent)}}.border-gray-700{border-color:var(--color-gray-700)}.border-green-200{border-color:var(--color-green-200)}.border-green-500{border-color:var(--color-green-500)}.border-input{border-color:var(--input)}.border-muted{border-color:var(--muted)}.border-primary{border-color:var(--primary)}.border-purple-100{border-color:var(--color-purple-100)}.border-purple-200{border-color:var(--color-purple-200)}.border-sidebar-border{border-color:var(--sidebar-border)}.border-transparent{border-color:transparent}.border-white{border-color:var(--color-white)}.border-yellow-500{border-color:var(--color-yellow-500)}.border-t-transparent{border-top-color:transparent}.border-l-transparent{border-left-color:transparent}.bg-\(--color-bg\){background-color:var(--color-bg)}.bg-accent{background-color:var(--accent)}.bg-background{background-color:var(--background)}.bg-black{background-color:var(--color-black)}.bg-black\/50{background-color:color-mix(in srgb,#000 50%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-blue-50{background-color:var(--color-blue-50)}.bg-blue-100{background-color:var(--color-blue-100)}.bg-blue-500{background-color:var(--color-blue-500)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-border{background-color:var(--border)}.bg-card{background-color:var(--card)}.bg-destructive{background-color:var(--destructive)}.bg-destructive\/10{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.bg-destructive\/10{background-color:color-mix(in oklab,var(--destructive) 10%,transparent)}}.bg-foreground{background-color:var(--foreground)}.bg-gray-400{background-color:var(--color-gray-400)}.bg-gray-600{background-color:var(--color-gray-600)}.bg-gray-900{background-color:var(--color-gray-900)}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-500{background-color:var(--color-green-500)}.bg-green-600{background-color:var(--color-green-600)}.bg-muted{background-color:var(--muted)}.bg-muted\/50{background-color:var(--muted)}@supports (color: color-mix(in lab,red,red)){.bg-muted\/50{background-color:color-mix(in oklab,var(--muted) 50%,transparent)}}.bg-orange-100{background-color:var(--color-orange-100)}.bg-orange-500{background-color:var(--color-orange-500)}.bg-orange-600{background-color:var(--color-orange-600)}.bg-popover{background-color:var(--popover)}.bg-primary{background-color:var(--primary)}.bg-primary\/10{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--primary) 10%,transparent)}}.bg-primary\/20{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.bg-primary\/20{background-color:color-mix(in oklab,var(--primary) 20%,transparent)}}.bg-purple-100{background-color:var(--color-purple-100)}.bg-purple-500{background-color:var(--color-purple-500)}.bg-purple-600{background-color:var(--color-purple-600)}.bg-red-100{background-color:var(--color-red-100)}.bg-red-500{background-color:var(--color-red-500)}.bg-red-600{background-color:var(--color-red-600)}.bg-secondary{background-color:var(--secondary)}.bg-sidebar{background-color:var(--sidebar)}.bg-sidebar-border{background-color:var(--sidebar-border)}.bg-sidebar-primary{background-color:var(--sidebar-primary)}.bg-slate-50{background-color:var(--color-slate-50)}.bg-transparent{background-color:transparent}.bg-white{background-color:var(--color-white)}.bg-white\/60{background-color:color-mix(in srgb,#fff 60%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-white\/60{background-color:color-mix(in oklab,var(--color-white) 60%,transparent)}}.bg-white\/80{background-color:color-mix(in srgb,#fff 80%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-white\/80{background-color:color-mix(in oklab,var(--color-white) 80%,transparent)}}.bg-yellow-100{background-color:var(--color-yellow-100)}.bg-yellow-500{background-color:var(--color-yellow-500)}.bg-yellow-600{background-color:var(--color-yellow-600)}.bg-gradient-to-b{--tw-gradient-position: to bottom in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-br{--tw-gradient-position: to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-r{--tw-gradient-position: to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-blue-400{--tw-gradient-from: var(--color-blue-400);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-500{--tw-gradient-from: var(--color-blue-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-500\/20{--tw-gradient-from: color-mix(in srgb, oklch(62.3% .214 259.815) 20%, transparent);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.from-blue-500\/20{--tw-gradient-from: color-mix(in oklab, var(--color-blue-500) 20%, transparent)}}.from-muted\/50{--tw-gradient-from: var(--muted);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.from-muted\/50{--tw-gradient-from: color-mix(in oklab, var(--muted) 50%, transparent)}}.from-purple-50{--tw-gradient-from: var(--color-purple-50);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-purple-500{--tw-gradient-from: var(--color-purple-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-white{--tw-gradient-from: var(--color-white);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-blue-600\/20{--tw-gradient-to: color-mix(in srgb, oklch(54.6% .245 262.881) 20%, transparent);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.to-blue-600\/20{--tw-gradient-to: color-mix(in oklab, var(--color-blue-600) 20%, transparent)}}.to-gray-900{--tw-gradient-to: var(--color-gray-900);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-muted{--tw-gradient-to: var(--muted);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-pink-50{--tw-gradient-to: var(--color-pink-50);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-pink-500{--tw-gradient-to: var(--color-pink-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-purple-600{--tw-gradient-to: var(--color-purple-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.fill-blue-400{fill:var(--color-blue-400)}.fill-current{fill:currentcolor}.fill-primary{fill:var(--primary)}.fill-yellow-400{fill:var(--color-yellow-400)}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing) * 0)}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-\[3px\]{padding:3px}.p-px{padding:1px}.px-\(--cell-size\){padding-inline:var(--cell-size)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-0{padding-top:calc(var(--spacing) * 0)}.pt-1{padding-top:calc(var(--spacing) * 1)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-1{padding-right:calc(var(--spacing) * 1)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-2\.5{padding-right:calc(var(--spacing) * 2.5)}.pr-8{padding-right:calc(var(--spacing) * 8)}.pr-10{padding-right:calc(var(--spacing) * 10)}.pb-0{padding-bottom:calc(var(--spacing) * 0)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-8{padding-left:calc(var(--spacing) * 8)}.pl-10{padding-left:calc(var(--spacing) * 10)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading, var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading, var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading, var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading, var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading, var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading, var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.text-\[0\.8rem\]{font-size:.8rem}.text-\[10px\]{font-size:10px}.leading-none{--tw-leading: 1;line-height:1}.leading-relaxed{--tw-leading: var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading: var(--leading-snug);line-height:var(--leading-snug)}.leading-tight{--tw-leading: var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight: var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking: var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-widest{--tw-tracking: var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-balance{text-wrap:balance}.break-words{overflow-wrap:break-word}.whitespace-nowrap{white-space:nowrap}.text-accent-foreground{color:var(--accent-foreground)}.text-blue-400{color:var(--color-blue-400)}.text-blue-500{color:var(--color-blue-500)}.text-blue-600{color:var(--color-blue-600)}.text-blue-700{color:var(--color-blue-700)}.text-blue-800{color:var(--color-blue-800)}.text-blue-900{color:var(--color-blue-900)}.text-card-foreground{color:var(--card-foreground)}.text-current{color:currentcolor}.text-destructive{color:var(--destructive)}.text-destructive-foreground{color:var(--destructive-foreground)}.text-foreground{color:var(--foreground)}.text-green-400{color:var(--color-green-400)}.text-green-500{color:var(--color-green-500)}.text-green-600{color:var(--color-green-600)}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted-foreground{color:var(--muted-foreground)}.text-orange-600{color:var(--color-orange-600)}.text-orange-700{color:var(--color-orange-700)}.text-pink-600{color:var(--color-pink-600)}.text-popover-foreground{color:var(--popover-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-purple-500{color:var(--color-purple-500)}.text-purple-600{color:var(--color-purple-600)}.text-purple-700{color:var(--color-purple-700)}.text-purple-900{color:var(--color-purple-900)}.text-red-500{color:var(--color-red-500)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-red-800{color:var(--color-red-800)}.text-secondary-foreground{color:var(--secondary-foreground)}.text-sidebar-foreground{color:var(--sidebar-foreground)}.text-sidebar-foreground\/70{color:var(--sidebar-foreground)}@supports (color: color-mix(in lab,red,red)){.text-sidebar-foreground\/70{color:color-mix(in oklab,var(--sidebar-foreground) 70%,transparent)}}.text-sidebar-primary-foreground{color:var(--sidebar-primary-foreground)}.text-white{color:var(--color-white)}.text-yellow-400{color:var(--color-yellow-400)}.text-yellow-600{color:var(--color-yellow-600)}.text-yellow-700{color:var(--color-yellow-700)}.capitalize{text-transform:capitalize}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.line-through{text-decoration-line:line-through}.no-underline{text-decoration-line:none}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0%}.opacity-50{opacity:50%}.opacity-70{opacity:70%}.opacity-75{opacity:75%}.opacity-90{opacity:90%}.opacity-100{opacity:100%}.shadow{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\[0_0_0_1px_hsl\(var\(--sidebar-border\)\)\]{--tw-shadow: 0 0 0 1px var(--tw-shadow-color, hsl(var(--sidebar-border)));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 8px 10px -6px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / .05));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-0{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-2{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-primary{--tw-ring-color: var(--primary)}.ring-ring\/50{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.ring-ring\/50{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.ring-sidebar-ring{--tw-ring-color: var(--sidebar-ring)}.ring-offset-background{--tw-ring-offset-color: var(--background)}.outline-hidden{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.outline-hidden{outline:2px solid transparent;outline-offset:2px}}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[color\,box-shadow\]{transition-property:color,box-shadow;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[left\,right\,width\]{transition-property:left,right,width;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[margin\,opacity\]{transition-property:margin,opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\,height\,padding\]{transition-property:width,height,padding;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\,height\]{transition-property:width,height;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\]{transition-property:width;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-shadow{transition-property:box-shadow;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-none{transition-property:none}.duration-200{--tw-duration: .2s;transition-duration:.2s}.duration-300{--tw-duration: .3s;transition-duration:.3s}.duration-1000{--tw-duration: 1s;transition-duration:1s}.ease-in-out{--tw-ease: var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-linear{--tw-ease: linear;transition-timing-function:linear}.fade-in-0{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.outline-none{--tw-outline-style: none;outline-style:none}.select-all{-webkit-user-select:all;user-select:all}.select-none{-webkit-user-select:none;user-select:none}.zoom-in-95{--tw-enter-scale: 95% ;--tw-enter-scale: .95}.\[--cell-size\:--spacing\(8\)\]{--cell-size: calc(var(--spacing) * 8)}.group-focus-within\/menu-item\:opacity-100:is(:where(.group\/menu-item):focus-within *){opacity:100%}@media(hover:hover){.group-hover\/menu-item\:opacity-100:is(:where(.group\/menu-item):hover *){opacity:100%}}.group-has-data-\[sidebar\=menu-action\]\/menu-item\:pr-8:is(:where(.group\/menu-item):has(*[data-sidebar=menu-action]) *){padding-right:calc(var(--spacing) * 8)}.group-has-\[\[data-collapsible\=icon\]\]\/sidebar-wrapper\:h-12:is(:where(.group\/sidebar-wrapper):has(*:is([data-collapsible=icon])) *){height:calc(var(--spacing) * 12)}.group-data-\[collapsible\=icon\]\:-mt-8:is(:where(.group)[data-collapsible=icon] *){margin-top:calc(var(--spacing) * -8)}.group-data-\[collapsible\=icon\]\:hidden:is(:where(.group)[data-collapsible=icon] *){display:none}.group-data-\[collapsible\=icon\]\:size-8\!:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--spacing) * 8)!important;height:calc(var(--spacing) * 8)!important}.group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)\+1rem\)\]:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--sidebar-width-icon) + 1rem)}.group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)\+1rem\+2px\)\]:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--sidebar-width-icon) + 1rem + 2px)}.group-data-\[collapsible\=icon\]\:w-\[var\(--sidebar-width-icon\)\]:is(:where(.group)[data-collapsible=icon] *){width:var(--sidebar-width-icon)}.group-data-\[collapsible\=icon\]\:overflow-hidden:is(:where(.group)[data-collapsible=icon] *){overflow:hidden}.group-data-\[collapsible\=icon\]\:p-0\!:is(:where(.group)[data-collapsible=icon] *){padding:calc(var(--spacing) * 0)!important}.group-data-\[collapsible\=icon\]\:p-2\!:is(:where(.group)[data-collapsible=icon] *){padding:calc(var(--spacing) * 2)!important}.group-data-\[collapsible\=icon\]\:opacity-0:is(:where(.group)[data-collapsible=icon] *){opacity:0%}.group-data-\[collapsible\=offcanvas\]\:right-\[calc\(var\(--sidebar-width\)\*-1\)\]:is(:where(.group)[data-collapsible=offcanvas] *){right:calc(var(--sidebar-width) * -1)}.group-data-\[collapsible\=offcanvas\]\:left-\[calc\(var\(--sidebar-width\)\*-1\)\]:is(:where(.group)[data-collapsible=offcanvas] *){left:calc(var(--sidebar-width) * -1)}.group-data-\[collapsible\=offcanvas\]\:w-0:is(:where(.group)[data-collapsible=offcanvas] *){width:calc(var(--spacing) * 0)}.group-data-\[collapsible\=offcanvas\]\:translate-x-0:is(:where(.group)[data-collapsible=offcanvas] *){--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.group-data-\[disabled\=true\]\:pointer-events-none:is(:where(.group)[data-disabled=true] *){pointer-events:none}.group-data-\[disabled\=true\]\:opacity-50:is(:where(.group)[data-disabled=true] *){opacity:50%}.group-data-\[focused\=true\]\/day\:relative:is(:where(.group\/day)[data-focused=true] *){position:relative}.group-data-\[focused\=true\]\/day\:z-10:is(:where(.group\/day)[data-focused=true] *){z-index:10}.group-data-\[focused\=true\]\/day\:border-ring:is(:where(.group\/day)[data-focused=true] *){border-color:var(--ring)}.group-data-\[focused\=true\]\/day\:ring-\[3px\]:is(:where(.group\/day)[data-focused=true] *){--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[focused\=true\]\/day\:ring-ring\/50:is(:where(.group\/day)[data-focused=true] *){--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.group-data-\[focused\=true\]\/day\:ring-ring\/50:is(:where(.group\/day)[data-focused=true] *){--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.group-data-\[side\=left\]\:-right-4:is(:where(.group)[data-side=left] *){right:calc(var(--spacing) * -4)}.group-data-\[side\=left\]\:border-r:is(:where(.group)[data-side=left] *){border-right-style:var(--tw-border-style);border-right-width:1px}.group-data-\[side\=right\]\:left-0:is(:where(.group)[data-side=right] *){left:calc(var(--spacing) * 0)}.group-data-\[side\=right\]\:rotate-180:is(:where(.group)[data-side=right] *){rotate:180deg}.group-data-\[side\=right\]\:border-l:is(:where(.group)[data-side=right] *){border-left-style:var(--tw-border-style);border-left-width:1px}.group-data-\[state\=open\]\:rotate-180:is(:where(.group)[data-state=open] *){rotate:180deg}.group-data-\[state\=open\]\/collapsible\:rotate-180:is(:where(.group\/collapsible)[data-state=open] *){rotate:180deg}.group-data-\[variant\=floating\]\:rounded-lg:is(:where(.group)[data-variant=floating] *){border-radius:var(--radius)}.group-data-\[variant\=floating\]\:border:is(:where(.group)[data-variant=floating] *){border-style:var(--tw-border-style);border-width:1px}.group-data-\[variant\=floating\]\:border-sidebar-border:is(:where(.group)[data-variant=floating] *){border-color:var(--sidebar-border)}.group-data-\[variant\=floating\]\:shadow-sm:is(:where(.group)[data-variant=floating] *){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[vaul-drawer-direction\=bottom\]\/drawer-content\:block:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=bottom] *){display:block}.group-data-\[vaul-drawer-direction\=bottom\]\/drawer-content\:text-center:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=bottom] *){text-align:center}.group-data-\[vaul-drawer-direction\=top\]\/drawer-content\:text-center:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=top] *){text-align:center}.group-data-\[viewport\=false\]\/navigation-menu\:top-full:is(:where(.group\/navigation-menu)[data-viewport=false] *){top:100%}.group-data-\[viewport\=false\]\/navigation-menu\:mt-1\.5:is(:where(.group\/navigation-menu)[data-viewport=false] *){margin-top:calc(var(--spacing) * 1.5)}.group-data-\[viewport\=false\]\/navigation-menu\:overflow-hidden:is(:where(.group\/navigation-menu)[data-viewport=false] *){overflow:hidden}.group-data-\[viewport\=false\]\/navigation-menu\:rounded-md:is(:where(.group\/navigation-menu)[data-viewport=false] *){border-radius:calc(var(--radius) - 2px)}.group-data-\[viewport\=false\]\/navigation-menu\:border:is(:where(.group\/navigation-menu)[data-viewport=false] *){border-style:var(--tw-border-style);border-width:1px}.group-data-\[viewport\=false\]\/navigation-menu\:bg-popover:is(:where(.group\/navigation-menu)[data-viewport=false] *){background-color:var(--popover)}.group-data-\[viewport\=false\]\/navigation-menu\:text-popover-foreground:is(:where(.group\/navigation-menu)[data-viewport=false] *){color:var(--popover-foreground)}.group-data-\[viewport\=false\]\/navigation-menu\:shadow:is(:where(.group\/navigation-menu)[data-viewport=false] *){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[viewport\=false\]\/navigation-menu\:duration-200:is(:where(.group\/navigation-menu)[data-viewport=false] *){--tw-duration: .2s;transition-duration:.2s}@media(hover:hover){.peer-hover\/menu-button\:text-sidebar-accent-foreground:is(:where(.peer\/menu-button):hover~*){color:var(--sidebar-accent-foreground)}}.peer-disabled\:cursor-not-allowed:is(:where(.peer):disabled~*){cursor:not-allowed}.peer-disabled\:opacity-50:is(:where(.peer):disabled~*){opacity:50%}.peer-data-\[active\=true\]\/menu-button\:text-sidebar-accent-foreground:is(:where(.peer\/menu-button)[data-active=true]~*){color:var(--sidebar-accent-foreground)}.peer-data-\[size\=default\]\/menu-button\:top-1\.5:is(:where(.peer\/menu-button)[data-size=default]~*){top:calc(var(--spacing) * 1.5)}.peer-data-\[size\=lg\]\/menu-button\:top-2\.5:is(:where(.peer\/menu-button)[data-size=lg]~*){top:calc(var(--spacing) * 2.5)}.peer-data-\[size\=sm\]\/menu-button\:top-1:is(:where(.peer\/menu-button)[data-size=sm]~*){top:calc(var(--spacing) * 1)}.selection\:bg-primary *::selection{background-color:var(--primary)}.selection\:bg-primary::selection{background-color:var(--primary)}.selection\:text-primary-foreground *::selection{color:var(--primary-foreground)}.selection\:text-primary-foreground::selection{color:var(--primary-foreground)}.file\:inline-flex::file-selector-button{display:inline-flex}.file\:h-7::file-selector-button{height:calc(var(--spacing) * 7)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-foreground::file-selector-button{color:var(--foreground)}.placeholder\:text-muted-foreground::placeholder{color:var(--muted-foreground)}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:-inset-2:after{content:var(--tw-content);inset:calc(var(--spacing) * -2)}.after\:inset-y-0:after{content:var(--tw-content);inset-block:calc(var(--spacing) * 0)}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:calc(var(--spacing) * 1)}.after\:w-\[2px\]:after{content:var(--tw-content);width:2px}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.group-data-\[collapsible\=offcanvas\]\:after\:left-full:is(:where(.group)[data-collapsible=offcanvas] *):after{content:var(--tw-content);left:100%}.first\:rounded-l-md:first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.first\:border-l:first-child{border-left-style:var(--tw-border-style);border-left-width:1px}.last\:rounded-r-md:last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.last\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0px}@media(hover:hover){.hover\:border-muted-foreground\/50:hover{border-color:var(--muted-foreground)}@supports (color: color-mix(in lab,red,red)){.hover\:border-muted-foreground\/50:hover{border-color:color-mix(in oklab,var(--muted-foreground) 50%,transparent)}}}@media(hover:hover){.hover\:bg-accent:hover{background-color:var(--accent)}}@media(hover:hover){.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}}@media(hover:hover){.hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--destructive) 90%,transparent)}}}@media(hover:hover){.hover\:bg-gray-700:hover{background-color:var(--color-gray-700)}}@media(hover:hover){.hover\:bg-green-700:hover{background-color:var(--color-green-700)}}@media(hover:hover){.hover\:bg-muted:hover{background-color:var(--muted)}}@media(hover:hover){.hover\:bg-muted\/50:hover{background-color:var(--muted)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-muted\/50:hover{background-color:color-mix(in oklab,var(--muted) 50%,transparent)}}}@media(hover:hover){.hover\:bg-orange-700:hover{background-color:var(--color-orange-700)}}@media(hover:hover){.hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary) 90%,transparent)}}}@media(hover:hover){.hover\:bg-purple-700:hover{background-color:var(--color-purple-700)}}@media(hover:hover){.hover\:bg-red-700:hover{background-color:var(--color-red-700)}}@media(hover:hover){.hover\:bg-secondary\/80:hover{background-color:var(--secondary)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab,var(--secondary) 80%,transparent)}}}@media(hover:hover){.hover\:bg-sidebar-accent:hover{background-color:var(--sidebar-accent)}}@media(hover:hover){.hover\:bg-white:hover{background-color:var(--color-white)}}@media(hover:hover){.hover\:bg-yellow-700:hover{background-color:var(--color-yellow-700)}}@media(hover:hover){.hover\:from-purple-600:hover{--tw-gradient-from: var(--color-purple-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}}@media(hover:hover){.hover\:to-pink-600:hover{--tw-gradient-to: var(--color-pink-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}}@media(hover:hover){.hover\:text-accent-foreground:hover{color:var(--accent-foreground)}}@media(hover:hover){.hover\:text-destructive:hover{color:var(--destructive)}}@media(hover:hover){.hover\:text-foreground:hover{color:var(--foreground)}}@media(hover:hover){.hover\:text-muted-foreground:hover{color:var(--muted-foreground)}}@media(hover:hover){.hover\:text-primary:hover{color:var(--primary)}}@media(hover:hover){.hover\:text-sidebar-accent-foreground:hover{color:var(--sidebar-accent-foreground)}}@media(hover:hover){.hover\:underline:hover{text-decoration-line:underline}}@media(hover:hover){.hover\:opacity-90:hover{opacity:90%}}@media(hover:hover){.hover\:opacity-100:hover{opacity:100%}}@media(hover:hover){.hover\:shadow-\[0_0_0_1px_hsl\(var\(--sidebar-accent\)\)\]:hover{--tw-shadow: 0 0 0 1px var(--tw-shadow-color, hsl(var(--sidebar-accent)));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:ring-4:hover{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:group-data-\[collapsible\=offcanvas\]\:bg-sidebar:hover:is(:where(.group)[data-collapsible=offcanvas] *){background-color:var(--sidebar)}}@media(hover:hover){.hover\:after\:bg-sidebar-border:hover:after{content:var(--tw-content);background-color:var(--sidebar-border)}}.focus\:z-10:focus{z-index:10}.focus\:bg-accent:focus{background-color:var(--accent)}.focus\:text-accent-foreground:focus{color:var(--accent-foreground)}.focus\:shadow-md:focus{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-2:focus{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-ring:focus{--tw-ring-color: var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-hidden:focus{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline:2px solid transparent;outline-offset:2px}}.focus-visible\:z-10:focus-visible{z-index:10}.focus-visible\:border-ring:focus-visible{border-color:var(--ring)}.focus-visible\:ring-1:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-4:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.focus-visible\:ring-green-500\/20:focus-visible{--tw-ring-color: color-mix(in srgb, oklch(72.3% .219 149.579) 20%, transparent)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-green-500\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--color-green-500) 20%, transparent)}}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: var(--ring)}.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.focus-visible\:ring-yellow-500\/20:focus-visible{--tw-ring-color: color-mix(in srgb, oklch(79.5% .184 86.047) 20%, transparent)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-yellow-500\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--color-yellow-500) 20%, transparent)}}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:outline-hidden:focus-visible{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.focus-visible\:outline-hidden:focus-visible{outline:2px solid transparent;outline-offset:2px}}.focus-visible\:outline-1:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-ring:focus-visible{outline-color:var(--ring)}.focus-visible\:outline-none:focus-visible{--tw-outline-style: none;outline-style:none}.active\:bg-sidebar-accent:active{background-color:var(--sidebar-accent)}.active\:text-sidebar-accent-foreground:active{color:var(--sidebar-accent-foreground)}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:50%}:where(*[data-side=left]) .in-data-\[side\=left\]\:cursor-w-resize{cursor:w-resize}:where(*[data-side=right]) .in-data-\[side\=right\]\:cursor-e-resize{cursor:e-resize}.has-focus\:border-ring:has(*:focus){border-color:var(--ring)}.has-focus\:ring-\[3px\]:has(*:focus){--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.has-focus\:ring-ring\/50:has(*:focus){--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.has-focus\:ring-ring\/50:has(*:focus){--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.has-disabled\:opacity-50:has(*:disabled){opacity:50%}.has-data-\[slot\=card-action\]\:grid-cols-\[1fr_auto\]:has(*[data-slot=card-action]){grid-template-columns:1fr auto}.has-data-\[variant\=inset\]\:bg-sidebar:has(*[data-variant=inset]){background-color:var(--sidebar)}.has-\[\>svg\]\:grid-cols-\[calc\(var\(--spacing\)\*4\)_1fr\]:has(>svg){grid-template-columns:calc(var(--spacing) * 4) 1fr}.has-\[\>svg\]\:gap-x-3:has(>svg){column-gap:calc(var(--spacing) * 3)}.has-\[\>svg\]\:px-2\.5:has(>svg){padding-inline:calc(var(--spacing) * 2.5)}.has-\[\>svg\]\:px-3:has(>svg){padding-inline:calc(var(--spacing) * 3)}.has-\[\>svg\]\:px-4:has(>svg){padding-inline:calc(var(--spacing) * 4)}.aria-disabled\:pointer-events-none[aria-disabled=true]{pointer-events:none}.aria-disabled\:opacity-50[aria-disabled=true]{opacity:50%}.aria-invalid\:border-destructive[aria-invalid=true]{border-color:var(--destructive)}.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.aria-selected\:text-muted-foreground[aria-selected=true]{color:var(--muted-foreground)}.data-\[active\=true\]\:z-10[data-active=true]{z-index:10}.data-\[active\=true\]\:border-ring[data-active=true]{border-color:var(--ring)}.data-\[active\=true\]\:bg-accent\/50[data-active=true]{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:bg-accent\/50[data-active=true]{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}.data-\[active\=true\]\:bg-sidebar-accent[data-active=true]{background-color:var(--sidebar-accent)}.data-\[active\=true\]\:font-medium[data-active=true]{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.data-\[active\=true\]\:text-accent-foreground[data-active=true]{color:var(--accent-foreground)}.data-\[active\=true\]\:text-sidebar-accent-foreground[data-active=true]{color:var(--sidebar-accent-foreground)}.data-\[active\=true\]\:ring-\[3px\][data-active=true]{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[active\=true\]\:ring-ring\/50[data-active=true]{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:ring-ring\/50[data-active=true]{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}@media(hover:hover){.data-\[active\=true\]\:hover\:bg-accent[data-active=true]:hover{background-color:var(--accent)}}.data-\[active\=true\]\:focus\:bg-accent[data-active=true]:focus{background-color:var(--accent)}.data-\[active\=true\]\:aria-invalid\:border-destructive[data-active=true][aria-invalid=true]{border-color:var(--destructive)}.data-\[active\=true\]\:aria-invalid\:ring-destructive\/20[data-active=true][aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:aria-invalid\:ring-destructive\/20[data-active=true][aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:50%}.data-\[disabled\=true\]\:pointer-events-none[data-disabled=true]{pointer-events:none}.data-\[disabled\=true\]\:opacity-50[data-disabled=true]{opacity:50%}.data-\[empty\=true\]\:text-muted-foreground[data-empty=true]{color:var(--muted-foreground)}.data-\[error\=true\]\:text-destructive[data-error=true]{color:var(--destructive)}.data-\[inset\]\:pl-8[data-inset]{padding-left:calc(var(--spacing) * 8)}.data-\[motion\=from-end\]\:slide-in-from-right-52[data-motion=from-end]{--tw-enter-translate-x: calc(52*var(--spacing))}.data-\[motion\=from-start\]\:slide-in-from-left-52[data-motion=from-start]{--tw-enter-translate-x: calc(52*var(--spacing)*-1)}.data-\[motion\=to-end\]\:slide-out-to-right-52[data-motion=to-end]{--tw-exit-translate-x: calc(52*var(--spacing))}.data-\[motion\=to-start\]\:slide-out-to-left-52[data-motion=to-start]{--tw-exit-translate-x: calc(52*var(--spacing)*-1)}.data-\[motion\^\=from-\]\:animate-in[data-motion^=from-]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[motion\^\=from-\]\:fade-in[data-motion^=from-]{--tw-enter-opacity: 0}.data-\[motion\^\=to-\]\:animate-out[data-motion^=to-]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[motion\^\=to-\]\:fade-out[data-motion^=to-]{--tw-exit-opacity: 0}.data-\[orientation\=horizontal\]\:h-1\.5[data-orientation=horizontal]{height:calc(var(--spacing) * 1.5)}.data-\[orientation\=horizontal\]\:h-full[data-orientation=horizontal]{height:100%}.data-\[orientation\=horizontal\]\:h-px[data-orientation=horizontal]{height:1px}.data-\[orientation\=horizontal\]\:w-full[data-orientation=horizontal]{width:100%}.data-\[orientation\=vertical\]\:h-full[data-orientation=vertical]{height:100%}.data-\[orientation\=vertical\]\:min-h-44[data-orientation=vertical]{min-height:calc(var(--spacing) * 44)}.data-\[orientation\=vertical\]\:w-1\.5[data-orientation=vertical]{width:calc(var(--spacing) * 1.5)}.data-\[orientation\=vertical\]\:w-auto[data-orientation=vertical]{width:auto}.data-\[orientation\=vertical\]\:w-full[data-orientation=vertical]{width:100%}.data-\[orientation\=vertical\]\:w-px[data-orientation=vertical]{width:1px}.data-\[orientation\=vertical\]\:flex-col[data-orientation=vertical]{flex-direction:column}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:calc(var(--spacing) * 0)}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:calc(var(--spacing) * 1)}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[placeholder\]\:text-muted-foreground[data-placeholder]{color:var(--muted-foreground)}.data-\[range-end\=true\]\:rounded-md[data-range-end=true]{border-radius:calc(var(--radius) - 2px)}.data-\[range-end\=true\]\:rounded-r-md[data-range-end=true]{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.data-\[range-end\=true\]\:bg-primary[data-range-end=true]{background-color:var(--primary)}.data-\[range-end\=true\]\:text-primary-foreground[data-range-end=true]{color:var(--primary-foreground)}.data-\[range-middle\=true\]\:rounded-none[data-range-middle=true]{border-radius:0}.data-\[range-middle\=true\]\:bg-accent[data-range-middle=true]{background-color:var(--accent)}.data-\[range-middle\=true\]\:text-accent-foreground[data-range-middle=true]{color:var(--accent-foreground)}.data-\[range-start\=true\]\:rounded-md[data-range-start=true]{border-radius:calc(var(--radius) - 2px)}.data-\[range-start\=true\]\:rounded-l-md[data-range-start=true]{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.data-\[range-start\=true\]\:bg-primary[data-range-start=true]{background-color:var(--primary)}.data-\[range-start\=true\]\:text-primary-foreground[data-range-start=true]{color:var(--primary-foreground)}.data-\[selected-single\=true\]\:bg-primary[data-selected-single=true]{background-color:var(--primary)}.data-\[selected-single\=true\]\:text-primary-foreground[data-selected-single=true]{color:var(--primary-foreground)}.data-\[selected\=true\]\:rounded-none[data-selected=true]{border-radius:0}.data-\[selected\=true\]\:bg-accent[data-selected=true]{background-color:var(--accent)}.data-\[selected\=true\]\:text-accent-foreground[data-selected=true]{color:var(--accent-foreground)}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: calc(var(--spacing) * 1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: calc(2*var(--spacing)*-1)}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: calc(2*var(--spacing))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: calc(var(--spacing) * 1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: calc(2*var(--spacing)*-1)}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: calc(2*var(--spacing))}.data-\[size\=default\]\:h-9[data-size=default]{height:calc(var(--spacing) * 9)}.data-\[size\=sm\]\:h-8[data-size=sm]{height:calc(var(--spacing) * 8)}:is(.\*\:data-\[slot\=alert-description\]\:text-destructive\/90>*)[data-slot=alert-description]{color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){:is(.\*\:data-\[slot\=alert-description\]\:text-destructive\/90>*)[data-slot=alert-description]{color:color-mix(in oklab,var(--destructive) 90%,transparent)}}:is(.\*\*\:data-\[slot\=command-input-wrapper\]\:h-12 *)[data-slot=command-input-wrapper]{height:calc(var(--spacing) * 12)}:is(.\*\*\:data-\[slot\=navigation-menu-link\]\:focus\:ring-0 *)[data-slot=navigation-menu-link]:focus{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}:is(.\*\*\:data-\[slot\=navigation-menu-link\]\:focus\:outline-none *)[data-slot=navigation-menu-link]:focus{--tw-outline-style: none;outline-style:none}:is(.\*\:data-\[slot\=select-value\]\:line-clamp-1>*)[data-slot=select-value]{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}:is(.\*\:data-\[slot\=select-value\]\:flex>*)[data-slot=select-value]{display:flex}:is(.\*\:data-\[slot\=select-value\]\:items-center>*)[data-slot=select-value]{align-items:center}:is(.\*\:data-\[slot\=select-value\]\:gap-2>*)[data-slot=select-value]{gap:calc(var(--spacing) * 2)}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:var(--background)}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[state\=checked\]\:translate-x-\[calc\(100\%-2px\)\][data-state=checked]{--tw-translate-x: calc(100% - 2px) ;translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[state\=checked\]\:border-primary[data-state=checked]{border-color:var(--primary)}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:var(--primary)}.data-\[state\=checked\]\:text-primary-foreground[data-state=checked]{color:var(--primary-foreground)}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up var(--tw-animation-duration,var(--tw-duration,.2s))ease-out}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:duration-300[data-state=closed]{--tw-duration: .3s;transition-duration:.3s}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0 ;--tw-exit-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: 95% ;--tw-exit-scale: .95}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:animate-out:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:fade-out-0:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{--tw-exit-opacity: 0 ;--tw-exit-opacity: 0}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:zoom-out-95:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{--tw-exit-scale: 95% ;--tw-exit-scale: .95}.data-\[state\=hidden\]\:animate-out[data-state=hidden]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=hidden\]\:fade-out[data-state=hidden]{--tw-exit-opacity: 0}.data-\[state\=on\]\:bg-accent[data-state=on]{background-color:var(--accent)}.data-\[state\=on\]\:text-accent-foreground[data-state=on]{color:var(--accent-foreground)}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down var(--tw-animation-duration,var(--tw-duration,.2s))ease-out}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:var(--accent)}.data-\[state\=open\]\:bg-accent\/50[data-state=open]{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.data-\[state\=open\]\:bg-accent\/50[data-state=open]{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}.data-\[state\=open\]\:bg-secondary[data-state=open]{background-color:var(--secondary)}.data-\[state\=open\]\:bg-sidebar-accent[data-state=open]{background-color:var(--sidebar-accent)}.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:var(--accent-foreground)}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:var(--muted-foreground)}.data-\[state\=open\]\:text-sidebar-accent-foreground[data-state=open]{color:var(--sidebar-accent-foreground)}.data-\[state\=open\]\:opacity-100[data-state=open]{opacity:100%}.data-\[state\=open\]\:duration-500[data-state=open]{--tw-duration: .5s;transition-duration:.5s}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.data-\[state\=open\]\:zoom-in-90[data-state=open]{--tw-enter-scale: 90% ;--tw-enter-scale: .9}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: 95% ;--tw-enter-scale: .95}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:animate-in:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:fade-in-0:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:zoom-in-95:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{--tw-enter-scale: 95% ;--tw-enter-scale: .95}@media(hover:hover){.data-\[state\=open\]\:hover\:bg-accent[data-state=open]:hover{background-color:var(--accent)}}@media(hover:hover){.data-\[state\=open\]\:hover\:bg-sidebar-accent[data-state=open]:hover{background-color:var(--sidebar-accent)}}@media(hover:hover){.data-\[state\=open\]\:hover\:text-sidebar-accent-foreground[data-state=open]:hover{color:var(--sidebar-accent-foreground)}}.data-\[state\=open\]\:focus\:bg-accent[data-state=open]:focus{background-color:var(--accent)}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:var(--muted)}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:var(--input)}.data-\[state\=visible\]\:animate-in[data-state=visible]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=visible\]\:fade-in[data-state=visible]{--tw-enter-opacity: 0}.data-\[variant\=destructive\]\:text-destructive[data-variant=destructive]{color:var(--destructive)}.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--destructive) 10%,transparent)}}.data-\[variant\=destructive\]\:focus\:text-destructive[data-variant=destructive]:focus{color:var(--destructive)}.data-\[variant\=outline\]\:border-l-0[data-variant=outline]{border-left-style:var(--tw-border-style);border-left-width:0px}.data-\[variant\=outline\]\:shadow-xs[data-variant=outline]{--tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / .05));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[variant\=outline\]\:first\:border-l[data-variant=outline]:first-child{border-left-style:var(--tw-border-style);border-left-width:1px}.data-\[vaul-drawer-direction\=bottom\]\:inset-x-0[data-vaul-drawer-direction=bottom]{inset-inline:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=bottom\]\:bottom-0[data-vaul-drawer-direction=bottom]{bottom:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=bottom\]\:mt-24[data-vaul-drawer-direction=bottom]{margin-top:calc(var(--spacing) * 24)}.data-\[vaul-drawer-direction\=bottom\]\:max-h-\[80vh\][data-vaul-drawer-direction=bottom]{max-height:80vh}.data-\[vaul-drawer-direction\=bottom\]\:rounded-t-lg[data-vaul-drawer-direction=bottom]{border-top-left-radius:var(--radius);border-top-right-radius:var(--radius)}.data-\[vaul-drawer-direction\=bottom\]\:border-t[data-vaul-drawer-direction=bottom]{border-top-style:var(--tw-border-style);border-top-width:1px}.data-\[vaul-drawer-direction\=left\]\:inset-y-0[data-vaul-drawer-direction=left]{inset-block:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=left\]\:left-0[data-vaul-drawer-direction=left]{left:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=left\]\:w-3\/4[data-vaul-drawer-direction=left]{width:75%}.data-\[vaul-drawer-direction\=left\]\:border-r[data-vaul-drawer-direction=left]{border-right-style:var(--tw-border-style);border-right-width:1px}.data-\[vaul-drawer-direction\=right\]\:inset-y-0[data-vaul-drawer-direction=right]{inset-block:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=right\]\:right-0[data-vaul-drawer-direction=right]{right:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=right\]\:w-3\/4[data-vaul-drawer-direction=right]{width:75%}.data-\[vaul-drawer-direction\=right\]\:border-l[data-vaul-drawer-direction=right]{border-left-style:var(--tw-border-style);border-left-width:1px}.data-\[vaul-drawer-direction\=top\]\:inset-x-0[data-vaul-drawer-direction=top]{inset-inline:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=top\]\:top-0[data-vaul-drawer-direction=top]{top:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=top\]\:mb-24[data-vaul-drawer-direction=top]{margin-bottom:calc(var(--spacing) * 24)}.data-\[vaul-drawer-direction\=top\]\:max-h-\[80vh\][data-vaul-drawer-direction=top]{max-height:80vh}.data-\[vaul-drawer-direction\=top\]\:rounded-b-lg[data-vaul-drawer-direction=top]{border-bottom-right-radius:var(--radius);border-bottom-left-radius:var(--radius)}.data-\[vaul-drawer-direction\=top\]\:border-b[data-vaul-drawer-direction=top]{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}@media(min-width:40rem){.sm\:block{display:block}}@media(min-width:40rem){.sm\:flex{display:flex}}@media(min-width:40rem){.sm\:w-auto{width:auto}}@media(min-width:40rem){.sm\:max-w-\[425px\]{max-width:425px}}@media(min-width:40rem){.sm\:max-w-lg{max-width:var(--container-lg)}}@media(min-width:40rem){.sm\:max-w-md{max-width:var(--container-md)}}@media(min-width:40rem){.sm\:max-w-sm{max-width:var(--container-sm)}}@media(min-width:40rem){.sm\:flex-row{flex-direction:row}}@media(min-width:40rem){.sm\:justify-end{justify-content:flex-end}}@media(min-width:40rem){.sm\:gap-2\.5{gap:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:pr-2\.5{padding-right:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:pl-2\.5{padding-left:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:text-left{text-align:left}}@media(min-width:40rem){.data-\[vaul-drawer-direction\=left\]\:sm\:max-w-sm[data-vaul-drawer-direction=left]{max-width:var(--container-sm)}}@media(min-width:40rem){.data-\[vaul-drawer-direction\=right\]\:sm\:max-w-sm[data-vaul-drawer-direction=right]{max-width:var(--container-sm)}}@media(min-width:48rem){.md\:absolute{position:absolute}}@media(min-width:48rem){.md\:block{display:block}}@media(min-width:48rem){.md\:flex{display:flex}}@media(min-width:48rem){.md\:min-h-min{min-height:min-content}}@media(min-width:48rem){.md\:w-\[400px\]{width:400px}}@media(min-width:48rem){.md\:w-\[500px\]{width:500px}}@media(min-width:48rem){.md\:w-\[var\(--radix-navigation-menu-viewport-width\)\]{width:var(--radix-navigation-menu-viewport-width)}}@media(min-width:48rem){.md\:w-auto{width:auto}}@media(min-width:48rem){.md\:basis-1\/2{flex-basis:50%}}@media(min-width:48rem){.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:48rem){.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:48rem){.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(min-width:48rem){.md\:flex-row{flex-direction:row}}@media(min-width:48rem){.md\:gap-1\.5{gap:calc(var(--spacing) * 1.5)}}@media(min-width:48rem){.md\:text-left{text-align:left}}@media(min-width:48rem){.md\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}}@media(min-width:48rem){.md\:opacity-0{opacity:0%}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:m-2:is(:where(.peer)[data-variant=inset]~*){margin:calc(var(--spacing) * 2)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:ml-0:is(:where(.peer)[data-variant=inset]~*){margin-left:calc(var(--spacing) * 0)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:rounded-xl:is(:where(.peer)[data-variant=inset]~*){border-radius:calc(var(--radius) + 4px)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:shadow-sm:is(:where(.peer)[data-variant=inset]~*){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:peer-data-\[state\=collapsed\]\:ml-2:is(:where(.peer)[data-variant=inset]~*):is(:where(.peer)[data-state=collapsed]~*){margin-left:calc(var(--spacing) * 2)}}@media(min-width:48rem){.md\:after\:hidden:after{content:var(--tw-content);display:none}}@media(min-width:64rem){.lg\:w-\[500px\]{width:500px}}@media(min-width:64rem){.lg\:w-\[600px\]{width:600px}}@media(min-width:64rem){.lg\:basis-1\/3{flex-basis:calc(1/3 * 100%)}}@media(min-width:64rem){.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-\[\.75fr_1fr\]{grid-template-columns:.75fr 1fr}}.dark\:border-input:is(.dark *){border-color:var(--input)}.dark\:bg-destructive\/60:is(.dark *){background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:bg-destructive\/60:is(.dark *){background-color:color-mix(in oklab,var(--destructive) 60%,transparent)}}.dark\:bg-input\/30:is(.dark *){background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:bg-input\/30:is(.dark *){background-color:color-mix(in oklab,var(--input) 30%,transparent)}}.dark\:bg-slate-800:is(.dark *){background-color:var(--color-slate-800)}.dark\:bg-slate-900:is(.dark *){background-color:var(--color-slate-900)}.dark\:text-muted-foreground:is(.dark *){color:var(--muted-foreground)}@media(hover:hover){.dark\:hover\:bg-accent\/50:is(.dark *):hover{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.dark\:hover\:bg-accent\/50:is(.dark *):hover{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}}@media(hover:hover){.dark\:hover\:bg-input\/50:is(.dark *):hover{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:hover\:bg-input\/50:is(.dark *):hover{background-color:color-mix(in oklab,var(--input) 50%,transparent)}}}@media(hover:hover){.dark\:hover\:text-accent-foreground:is(.dark *):hover{color:var(--accent-foreground)}}.dark\:focus-visible\:ring-destructive\/40:is(.dark *):focus-visible{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:focus-visible\:ring-destructive\/40:is(.dark *):focus-visible{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:aria-invalid\:ring-destructive\/40:is(.dark *)[aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:aria-invalid\:ring-destructive\/40:is(.dark *)[aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:data-\[active\=true\]\:aria-invalid\:ring-destructive\/40:is(.dark *)[data-active=true][aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[active\=true\]\:aria-invalid\:ring-destructive\/40:is(.dark *)[data-active=true][aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:data-\[state\=active\]\:border-input:is(.dark *)[data-state=active]{border-color:var(--input)}.dark\:data-\[state\=active\]\:bg-input\/30:is(.dark *)[data-state=active]{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[state\=active\]\:bg-input\/30:is(.dark *)[data-state=active]{background-color:color-mix(in oklab,var(--input) 30%,transparent)}}.dark\:data-\[state\=active\]\:text-foreground:is(.dark *)[data-state=active]{color:var(--foreground)}.dark\:data-\[state\=checked\]\:bg-primary:is(.dark *)[data-state=checked]{background-color:var(--primary)}.dark\:data-\[state\=checked\]\:bg-primary-foreground:is(.dark *)[data-state=checked]{background-color:var(--primary-foreground)}.dark\:data-\[state\=unchecked\]\:bg-foreground:is(.dark *)[data-state=unchecked]{background-color:var(--foreground)}.dark\:data-\[state\=unchecked\]\:bg-input\/80:is(.dark *)[data-state=unchecked]{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[state\=unchecked\]\:bg-input\/80:is(.dark *)[data-state=unchecked]{background-color:color-mix(in oklab,var(--input) 80%,transparent)}}.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:is(.dark *)[data-variant=destructive]:focus{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:is(.dark *)[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--destructive) 20%,transparent)}}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:var(--muted-foreground)}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:var(--border)}@supports (color: color-mix(in lab,red,red)){.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:color-mix(in oklab,var(--border) 50%,transparent)}}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:var(--border)}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-hidden .recharts-layer{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-layer\]\:outline-hidden .recharts-layer{outline:2px solid transparent;outline-offset:2px}}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:var(--border)}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector{fill:var(--muted)}.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:var(--muted)}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:var(--border)}.\[\&_\.recharts-sector\]\:outline-hidden .recharts-sector{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-sector\]\:outline-hidden .recharts-sector{outline:2px solid transparent;outline-offset:2px}}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-surface\]\:outline-hidden .recharts-surface{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-surface\]\:outline-hidden .recharts-surface{outline:2px solid transparent;outline-offset:2px}}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-block:calc(var(--spacing) * 1.5)}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:var(--muted-foreground)}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:calc(var(--spacing) * 0)}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:calc(var(--spacing) * 12)}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-block:calc(var(--spacing) * 3)}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:calc(var(--spacing) * 5)}.\[\&_p\]\:leading-relaxed p{--tw-leading: var(--leading-relaxed);line-height:var(--leading-relaxed)}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\:not\(\[class\*\=\'text-\'\]\)\]\:text-muted-foreground svg:not([class*=text-]){color:var(--muted-foreground)}.\[\&_tr\]\:border-b tr{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-style:var(--tw-border-style);border-width:0px}.\[\&\:\:-webkit-calendar-picker-indicator\]\:hidden::-webkit-calendar-picker-indicator{display:none}.\[\&\:\:-webkit-calendar-picker-indicator\]\:appearance-none::-webkit-calendar-picker-indicator{-webkit-appearance:none;-moz-appearance:none;appearance:none}.\[\&\:first-child\[data-selected\=true\]_button\]\:rounded-l-md:first-child[data-selected=true] button{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:calc(var(--spacing) * 0)}.\[\.border-b\]\:pb-6:is(.border-b){padding-bottom:calc(var(--spacing) * 6)}.\[\.border-t\]\:pt-6:is(.border-t){padding-top:calc(var(--spacing) * 6)}:is(.rtl\:\*\*\:\[\.rdp-button\\_next\>svg\]\:rotate-180:where(:dir(rtl),[dir=rtl],[dir=rtl] *) *):is(.rdp-button_next>svg){rotate:180deg}:is(.rtl\:\*\*\:\[\.rdp-button\\_previous\>svg\]\:rotate-180:where(:dir(rtl),[dir=rtl],[dir=rtl] *) *):is(.rdp-button_previous>svg){rotate:180deg}:is(.\*\:\[span\]\:last\:flex>*):is(span):last-child{display:flex}:is(.\*\:\[span\]\:last\:items-center>*):is(span):last-child{align-items:center}:is(.\*\:\[span\]\:last\:gap-2>*):is(span):last-child{gap:calc(var(--spacing) * 2)}:is(.data-\[variant\=destructive\]\:\*\:\[svg\]\:\!text-destructive[data-variant=destructive]>*):is(svg){color:var(--destructive)!important}.\[\&\:last-child\[data-selected\=true\]_button\]\:rounded-r-md:last-child[data-selected=true] button{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\[\&\>\[role\=checkbox\]\]\:translate-y-\[2px\]>[role=checkbox]{--tw-translate-y: 2px;translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>button\]\:hidden>button{display:none}.\[\&\>div\]\:bg-blue-500>div{background-color:var(--color-blue-500)}.\[\&\>div\]\:bg-green-500>div{background-color:var(--color-green-500)}.\[\&\>div\]\:bg-orange-500>div{background-color:var(--color-orange-500)}.\[\&\>div\]\:bg-red-500>div{background-color:var(--color-red-500)}.\[\&\>div\]\:bg-yellow-500>div{background-color:var(--color-yellow-500)}.\[\&\>div\]\:bg-gradient-to-r>div{--tw-gradient-position: to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.\[\&\>div\]\:from-purple-500>div{--tw-gradient-from: var(--color-purple-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.\[\&\>div\]\:to-pink-500>div{--tw-gradient-to: var(--color-pink-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.\[\&\>span\]\:text-xs>span{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.\[\&\>span\]\:opacity-70>span{opacity:70%}.\[\&\>span\:last-child\]\:truncate>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\[\&\>svg\]\:pointer-events-none>svg{pointer-events:none}.\[\&\>svg\]\:size-3>svg{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.\[\&\>svg\]\:size-3\.5>svg{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.\[\&\>svg\]\:size-4>svg{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&\>svg\]\:h-2\.5>svg{height:calc(var(--spacing) * 2.5)}.\[\&\>svg\]\:h-3>svg{height:calc(var(--spacing) * 3)}.\[\&\>svg\]\:w-2\.5>svg{width:calc(var(--spacing) * 2.5)}.\[\&\>svg\]\:w-3>svg{width:calc(var(--spacing) * 3)}.\[\&\>svg\]\:shrink-0>svg{flex-shrink:0}.\[\&\>svg\]\:translate-y-0\.5>svg{--tw-translate-y: calc(var(--spacing) * .5);translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>svg\]\:text-current>svg{color:currentcolor}.\[\&\>svg\]\:text-muted-foreground>svg{color:var(--muted-foreground)}.\[\&\>svg\]\:text-sidebar-accent-foreground>svg{color:var(--sidebar-accent-foreground)}.\[\&\>tr\]\:last\:border-b-0>tr:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{rotate:90deg}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{rotate:180deg}[data-side=left][data-collapsible=offcanvas] .\[\[data-side\=left\]\[data-collapsible\=offcanvas\]_\&\]\:-right-2{right:calc(var(--spacing) * -2)}[data-side=left][data-state=collapsed] .\[\[data-side\=left\]\[data-state\=collapsed\]_\&\]\:cursor-e-resize{cursor:e-resize}[data-side=right][data-collapsible=offcanvas] .\[\[data-side\=right\]\[data-collapsible\=offcanvas\]_\&\]\:-left-2{left:calc(var(--spacing) * -2)}[data-side=right][data-state=collapsed] .\[\[data-side\=right\]\[data-state\=collapsed\]_\&\]\:cursor-w-resize{cursor:w-resize}[data-slot=card-content] .\[\[data-slot\=card-content\]_\&\]\:bg-transparent{background-color:transparent}[data-slot=popover-content] .\[\[data-slot\=popover-content\]_\&\]\:bg-transparent{background-color:transparent}@media(hover:hover){a.\[a\&\]\:hover\:bg-accent:hover{background-color:var(--accent)}}@media(hover:hover){a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--destructive) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:var(--secondary)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:color-mix(in oklab,var(--secondary) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:text-accent-foreground:hover{color:var(--accent-foreground)}}}@property --tw-animation-delay{syntax: "*"; inherits: false; initial-value: 0s;}@property --tw-animation-direction{syntax: "*"; inherits: false; initial-value: normal;}@property --tw-animation-duration{syntax: "*"; inherits: false;}@property --tw-animation-fill-mode{syntax: "*"; inherits: false; initial-value: none;}@property --tw-animation-iteration-count{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-opacity{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-rotate{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-enter-scale{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-enter-translate-y{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-opacity{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-exit-rotate{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-scale{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-exit-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-translate-y{syntax: "*"; inherits: false; initial-value: 0;}:root{--background: oklch(1 0 0);--foreground: oklch(.145 0 0);--card: oklch(1 0 0);--card-foreground: oklch(.145 0 0);--popover: oklch(1 0 0);--popover-foreground: oklch(.145 0 0);--primary: oklch(67.35% .153 159.64);--primary-foreground: oklch(.985 0 0);--secondary: oklch(.97 0 0);--secondary-foreground: oklch(.205 0 0);--muted: oklch(.97 0 0);--muted-foreground: oklch(.556 0 0);--accent: oklch(.97 0 0);--accent-foreground: oklch(.205 0 0);--destructive: oklch(.577 .245 27.325);--destructive-foreground: oklch(.577 .245 27.325);--border: oklch(.922 0 0);--input: oklch(.922 0 0);--ring: oklch(.708 0 0);--chart-1: oklch(.646 .222 41.116);--chart-2: oklch(.6 .118 184.704);--chart-3: oklch(.398 .07 227.392);--chart-4: oklch(.828 .189 84.429);--chart-5: oklch(.769 .188 70.08);--radius: .625rem;--sidebar: oklch(.985 0 0);--sidebar-foreground: oklch(.145 0 0);--sidebar-primary: oklch(.205 0 0);--sidebar-primary-foreground: oklch(.985 0 0);--sidebar-accent: oklch(.97 0 0);--sidebar-accent-foreground: oklch(.205 0 0);--sidebar-border: oklch(.922 0 0);--sidebar-ring: oklch(.708 0 0)}.dark{--background: oklch(.145 0 0);--foreground: oklch(.985 0 0);--card: oklch(.145 0 0);--card-foreground: oklch(.985 0 0);--popover: oklch(.145 0 0);--popover-foreground: oklch(.985 0 0);--primary: oklch(88.18% .202 159.34);--primary-foreground: oklch(.205 0 0);--secondary: oklch(.269 0 0);--secondary-foreground: oklch(.985 0 0);--muted: oklch(.269 0 0);--muted-foreground: oklch(.708 0 0);--accent: oklch(.269 0 0);--accent-foreground: oklch(.985 0 0);--destructive: oklch(.396 .141 25.723);--destructive-foreground: oklch(.637 .237 25.331);--border: oklch(.269 0 0);--input: oklch(.269 0 0);--ring: oklch(.439 0 0);--chart-1: oklch(.488 .243 264.376);--chart-2: oklch(.696 .17 162.48);--chart-3: oklch(.769 .188 70.08);--chart-4: oklch(.627 .265 303.9);--chart-5: oklch(.645 .246 16.439);--sidebar: oklch(.205 0 0);--sidebar-foreground: oklch(.985 0 0);--sidebar-primary: oklch(.488 .243 264.376);--sidebar-primary-foreground: oklch(.985 0 0);--sidebar-accent: oklch(.269 0 0);--sidebar-accent-foreground: oklch(.985 0 0);--sidebar-border: oklch(.269 0 0);--sidebar-ring: oklch(.439 0 0)}@layer base{*{border-color:var(--border);outline-color:var(--ring)}@supports (color: color-mix(in lab,red,red)){*{outline-color:color-mix(in oklab,var(--ring) 50%,transparent)}}body{background-color:var(--background);color:var(--foreground)}}@property --tw-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-translate-y{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-translate-z{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-rotate-x{syntax: "*"; inherits: false;}@property --tw-rotate-y{syntax: "*"; inherits: false;}@property --tw-rotate-z{syntax: "*"; inherits: false;}@property --tw-skew-x{syntax: "*"; inherits: false;}@property --tw-skew-y{syntax: "*"; inherits: false;}@property --tw-space-y-reverse{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-space-x-reverse{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-border-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-gradient-position{syntax: "*"; inherits: false;}@property --tw-gradient-from{syntax: ""; inherits: false; initial-value: #0000;}@property --tw-gradient-via{syntax: ""; inherits: false; initial-value: #0000;}@property --tw-gradient-to{syntax: ""; inherits: false; initial-value: #0000;}@property --tw-gradient-stops{syntax: "*"; inherits: false;}@property --tw-gradient-via-stops{syntax: "*"; inherits: false;}@property --tw-gradient-from-position{syntax: ""; inherits: false; initial-value: 0%;}@property --tw-gradient-via-position{syntax: ""; inherits: false; initial-value: 50%;}@property --tw-gradient-to-position{syntax: ""; inherits: false; initial-value: 100%;}@property --tw-leading{syntax: "*"; inherits: false;}@property --tw-font-weight{syntax: "*"; inherits: false;}@property --tw-tracking{syntax: "*"; inherits: false;}@property --tw-ordinal{syntax: "*"; inherits: false;}@property --tw-slashed-zero{syntax: "*"; inherits: false;}@property --tw-numeric-figure{syntax: "*"; inherits: false;}@property --tw-numeric-spacing{syntax: "*"; inherits: false;}@property --tw-numeric-fraction{syntax: "*"; inherits: false;}@property --tw-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-shadow-color{syntax: "*"; inherits: false;}@property --tw-shadow-alpha{syntax: ""; inherits: false; initial-value: 100%;}@property --tw-inset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-shadow-color{syntax: "*"; inherits: false;}@property --tw-inset-shadow-alpha{syntax: ""; inherits: false; initial-value: 100%;}@property --tw-ring-color{syntax: "*"; inherits: false;}@property --tw-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-ring-color{syntax: "*"; inherits: false;}@property --tw-inset-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-ring-inset{syntax: "*"; inherits: false;}@property --tw-ring-offset-width{syntax: ""; inherits: false; initial-value: 0px;}@property --tw-ring-offset-color{syntax: "*"; inherits: false; initial-value: #fff;}@property --tw-ring-offset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-outline-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-duration{syntax: "*"; inherits: false;}@property --tw-ease{syntax: "*"; inherits: false;}@property --tw-content{syntax: "*"; initial-value: ""; inherits: false;}@keyframes pulse{50%{opacity:.5}}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0)scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1))rotate(var(--tw-enter-rotate,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0)scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1))rotate(var(--tw-exit-rotate,0))}}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height,var(--bits-accordion-content-height,var(--reka-accordion-content-height,var(--kb-accordion-content-height,auto))))}}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height,var(--bits-accordion-content-height,var(--reka-accordion-content-height,var(--kb-accordion-content-height,auto))))}to{height:0}}@keyframes caret-blink{0%,70%,to{opacity:1}20%,50%{opacity:0}}@layer properties{@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x: 0;--tw-translate-y: 0;--tw-translate-z: 0;--tw-rotate-x: initial;--tw-rotate-y: initial;--tw-rotate-z: initial;--tw-skew-x: initial;--tw-skew-y: initial;--tw-space-y-reverse: 0;--tw-space-x-reverse: 0;--tw-border-style: solid;--tw-gradient-position: initial;--tw-gradient-from: #0000;--tw-gradient-via: #0000;--tw-gradient-to: #0000;--tw-gradient-stops: initial;--tw-gradient-via-stops: initial;--tw-gradient-from-position: 0%;--tw-gradient-via-position: 50%;--tw-gradient-to-position: 100%;--tw-leading: initial;--tw-font-weight: initial;--tw-tracking: initial;--tw-ordinal: initial;--tw-slashed-zero: initial;--tw-numeric-figure: initial;--tw-numeric-spacing: initial;--tw-numeric-fraction: initial;--tw-shadow: 0 0 #0000;--tw-shadow-color: initial;--tw-shadow-alpha: 100%;--tw-inset-shadow: 0 0 #0000;--tw-inset-shadow-color: initial;--tw-inset-shadow-alpha: 100%;--tw-ring-color: initial;--tw-ring-shadow: 0 0 #0000;--tw-inset-ring-color: initial;--tw-inset-ring-shadow: 0 0 #0000;--tw-ring-inset: initial;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-offset-shadow: 0 0 #0000;--tw-outline-style: solid;--tw-duration: initial;--tw-ease: initial;--tw-content: "";--tw-animation-delay: 0s;--tw-animation-direction: normal;--tw-animation-duration: initial;--tw-animation-fill-mode: none;--tw-animation-iteration-count: 1;--tw-enter-opacity: 1;--tw-enter-rotate: 0;--tw-enter-scale: 1;--tw-enter-translate-x: 0;--tw-enter-translate-y: 0;--tw-exit-opacity: 1;--tw-exit-rotate: 0;--tw-exit-scale: 1;--tw-exit-translate-x: 0;--tw-exit-translate-y: 0}}}/*! tailwindcss v4.1.10 | MIT License | https://tailwindcss.com *//*! tailwindcss v4.1.17 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-yellow-400:oklch(85.2% .199 91.936);--color-yellow-500:oklch(79.5% .184 86.047);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-gray-50:oklch(98.5% .002 247.839);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-900:oklch(21% .034 264.665);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-md:28rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--text-6xl:3.75rem;--text-6xl--line-height:1;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--animate-spin:spin 1s linear infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--border);outline-color:var(--ring)}@supports (color:color-mix(in lab,red,red)){*{outline-color:color-mix(in oklab,var(--ring)50%,transparent)}}html,body{height:100%;margin:0;padding:0}body{background-color:var(--background);color:var(--foreground);font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif}#root{height:100%}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0;border-radius:4px}::-webkit-scrollbar-thumb{background-color:#ffffff26;background-clip:content-box;border:2px solid #0000;border-radius:4px;transition:background-color .2s}::-webkit-scrollbar-thumb:hover{background-color:#ffffff40}::-webkit-scrollbar-thumb:active{background-color:#ffffff59}*{scrollbar-width:thin;scrollbar-color:#ffffff26 transparent}@media(max-width:768px){*{scrollbar-width:none}::-webkit-scrollbar{display:none}}}@layer components;@layer utilities{.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.top-1\/2{top:50%}.left-3{left:calc(var(--spacing)*3)}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing)*.5)}.mt-1{margin-top:calc(var(--spacing)*1)}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-12{margin-top:calc(var(--spacing)*12)}.mt-16{margin-top:calc(var(--spacing)*16)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing)*1)}.mr-1\.5{margin-right:calc(var(--spacing)*1.5)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-1{margin-bottom:calc(var(--spacing)*1)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-3{margin-bottom:calc(var(--spacing)*3)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.mb-6{margin-bottom:calc(var(--spacing)*6)}.ml-1{margin-left:calc(var(--spacing)*1)}.ml-2{margin-left:calc(var(--spacing)*2)}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-7{height:calc(var(--spacing)*7)}.h-8{height:calc(var(--spacing)*8)}.h-12{height:calc(var(--spacing)*12)}.h-14{height:calc(var(--spacing)*14)}.h-16{height:calc(var(--spacing)*16)}.h-48{height:calc(var(--spacing)*48)}.h-64{height:calc(var(--spacing)*64)}.h-full{height:100%}.h-screen{height:100vh}.max-h-40{max-height:calc(var(--spacing)*40)}.max-h-48{max-height:calc(var(--spacing)*48)}.max-h-60{max-height:calc(var(--spacing)*60)}.max-h-\[90vh\]{max-height:90vh}.min-h-screen{min-height:100vh}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-6{width:calc(var(--spacing)*6)}.w-8{width:calc(var(--spacing)*8)}.w-12{width:calc(var(--spacing)*12)}.w-14{width:calc(var(--spacing)*14)}.w-56{width:calc(var(--spacing)*56)}.w-64{width:calc(var(--spacing)*64)}.w-full{width:100%}.w-px{width:1px}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-\[150px\]{max-width:150px}.max-w-md{max-width:var(--container-md)}.min-w-0{min-width:calc(var(--spacing)*0)}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y: -50% ;translate:var(--tw-translate-x)var(--tw-translate-y)}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.gap-6{gap:calc(var(--spacing)*6)}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*1)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*1)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*1.5)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*1.5)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*4)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*6)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*6)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-8>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*8)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*8)*calc(1 - var(--tw-space-y-reverse)))}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-none{border-radius:0}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-destructive\/50{border-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.border-destructive\/50{border-color:color-mix(in oklab,var(--destructive)50%,transparent)}}.border-gray-300{border-color:var(--color-gray-300)}.border-input{border-color:var(--input)}.border-primary\/20{border-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.border-primary\/20{border-color:color-mix(in oklab,var(--primary)20%,transparent)}}.border-sidebar-border{border-color:var(--sidebar-border)}.bg-background,.bg-background\/80{background-color:var(--background)}@supports (color:color-mix(in lab,red,red)){.bg-background\/80{background-color:color-mix(in oklab,var(--background)80%,transparent)}}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black)50%,transparent)}}.bg-blue-600{background-color:var(--color-blue-600)}.bg-card{background-color:var(--card)}.bg-destructive\/10{background-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.bg-destructive\/10{background-color:color-mix(in oklab,var(--destructive)10%,transparent)}}.bg-gray-50{background-color:var(--color-gray-50)}.bg-gray-900{background-color:var(--color-gray-900)}.bg-green-500\/10{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.bg-green-500\/10{background-color:color-mix(in oklab,var(--color-green-500)10%,transparent)}}.bg-muted{background-color:var(--muted)}.bg-primary,.bg-primary\/10{background-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--primary)10%,transparent)}}.bg-red-50{background-color:var(--color-red-50)}.bg-red-100{background-color:var(--color-red-100)}.bg-red-500\/10{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.bg-red-500\/10{background-color:color-mix(in oklab,var(--color-red-500)10%,transparent)}}.bg-red-600{background-color:var(--color-red-600)}.bg-sidebar{background-color:var(--sidebar)}.bg-sidebar-accent,.bg-sidebar-accent\/50{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.bg-sidebar-accent\/50{background-color:color-mix(in oklab,var(--sidebar-accent)50%,transparent)}}.bg-sidebar-border{background-color:var(--sidebar-border)}.bg-white{background-color:var(--color-white)}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-t{--tw-gradient-position:to top in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-primary\/10{--tw-gradient-from:var(--primary)}@supports (color:color-mix(in lab,red,red)){.from-primary\/10{--tw-gradient-from:color-mix(in oklab,var(--primary)10%,transparent)}}.from-primary\/10{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-primary\/20{--tw-gradient-from:var(--primary)}@supports (color:color-mix(in lab,red,red)){.from-primary\/20{--tw-gradient-from:color-mix(in oklab,var(--primary)20%,transparent)}}.from-primary\/20{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.via-background{--tw-gradient-via:var(--background);--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-background\/95{--tw-gradient-via:var(--background)}@supports (color:color-mix(in lab,red,red)){.via-background\/95{--tw-gradient-via:color-mix(in oklab,var(--background)95%,transparent)}}.via-background\/95{--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-background{--tw-gradient-to:var(--background);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing)*0)}.p-1{padding:calc(var(--spacing)*1)}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.p-6{padding:calc(var(--spacing)*6)}.p-8{padding:calc(var(--spacing)*8)}.px-0{padding-inline:calc(var(--spacing)*0)}.px-1\.5{padding-inline:calc(var(--spacing)*1.5)}.px-2{padding-inline:calc(var(--spacing)*2)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-8{padding-inline:calc(var(--spacing)*8)}.px-\[0\.3rem\]{padding-inline:.3rem}.py-1{padding-block:calc(var(--spacing)*1)}.py-2{padding-block:calc(var(--spacing)*2)}.py-2\.5{padding-block:calc(var(--spacing)*2.5)}.py-3{padding-block:calc(var(--spacing)*3)}.py-4{padding-block:calc(var(--spacing)*4)}.py-6{padding-block:calc(var(--spacing)*6)}.py-12{padding-block:calc(var(--spacing)*12)}.py-16{padding-block:calc(var(--spacing)*16)}.py-\[0\.2rem\]{padding-block:.2rem}.pt-2{padding-top:calc(var(--spacing)*2)}.pt-3{padding-top:calc(var(--spacing)*3)}.pt-4{padding-top:calc(var(--spacing)*4)}.pt-8{padding-top:calc(var(--spacing)*8)}.pr-1{padding-right:calc(var(--spacing)*1)}.pl-2{padding-left:calc(var(--spacing)*2)}.pl-9{padding-left:calc(var(--spacing)*9)}.text-center{text-align:center}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-6xl{font-size:var(--text-6xl);line-height:var(--tw-leading,var(--text-6xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.whitespace-nowrap{white-space:nowrap}.text-blue-500{color:var(--color-blue-500)}.text-blue-600{color:var(--color-blue-600)}.text-destructive{color:var(--destructive)}.text-foreground{color:var(--foreground)}.text-gray-500{color:var(--color-gray-500)}.text-gray-600{color:var(--color-gray-600)}.text-gray-700{color:var(--color-gray-700)}.text-gray-900{color:var(--color-gray-900)}.text-green-500{color:var(--color-green-500)}.text-muted-foreground{color:var(--muted-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-red-400{color:var(--color-red-400)}.text-red-500{color:var(--color-red-500)}.text-red-600{color:var(--color-red-600)}.text-red-800{color:var(--color-red-800)}.text-sidebar-foreground,.text-sidebar-foreground\/40{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/40{color:color-mix(in oklab,var(--sidebar-foreground)40%,transparent)}}.text-sidebar-foreground\/60{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/60{color:color-mix(in oklab,var(--sidebar-foreground)60%,transparent)}}.text-sidebar-foreground\/70{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/70{color:color-mix(in oklab,var(--sidebar-foreground)70%,transparent)}}.text-white{color:var(--color-white)}.text-yellow-500{color:var(--color-yellow-500)}.lowercase{text-transform:lowercase}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(1px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}@media(hover:hover){.group-hover\:translate-x-1:is(:where(.group):hover *){--tw-translate-x:calc(var(--spacing)*1);translate:var(--tw-translate-x)var(--tw-translate-y)}.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.placeholder\:text-muted-foreground::placeholder{color:var(--muted-foreground)}.placeholder\:text-sidebar-foreground\/50::placeholder{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.placeholder\:text-sidebar-foreground\/50::placeholder{color:color-mix(in oklab,var(--sidebar-foreground)50%,transparent)}}@media(hover:hover){.hover\:border-primary:hover{border-color:var(--primary)}.hover\:bg-accent:hover{background-color:var(--accent)}.hover\:bg-blue-500\/10:hover{background-color:#3080ff1a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-blue-500\/10:hover{background-color:color-mix(in oklab,var(--color-blue-500)10%,transparent)}}.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}.hover\:bg-gray-50:hover{background-color:var(--color-gray-50)}.hover\:bg-gray-500\/10:hover{background-color:#6a72821a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-500\/10:hover{background-color:color-mix(in oklab,var(--color-gray-500)10%,transparent)}}.hover\:bg-green-500\/10:hover{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-500\/10:hover{background-color:color-mix(in oklab,var(--color-green-500)10%,transparent)}}.hover\:bg-green-500\/20:hover{background-color:#00c75833}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-500\/20:hover{background-color:color-mix(in oklab,var(--color-green-500)20%,transparent)}}.hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary)90%,transparent)}}.hover\:bg-red-500\/10:hover{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-red-500\/10:hover{background-color:color-mix(in oklab,var(--color-red-500)10%,transparent)}}.hover\:bg-red-500\/20:hover{background-color:#fb2c3633}@supports (color:color-mix(in lab,red,red)){.hover\:bg-red-500\/20:hover{background-color:color-mix(in oklab,var(--color-red-500)20%,transparent)}}.hover\:bg-red-700:hover{background-color:var(--color-red-700)}.hover\:bg-sidebar:hover{background-color:var(--sidebar)}.hover\:bg-sidebar-accent:hover,.hover\:bg-sidebar-accent\/30:hover{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-sidebar-accent\/30:hover{background-color:color-mix(in oklab,var(--sidebar-accent)30%,transparent)}}.hover\:bg-transparent:hover{background-color:#0000}.hover\:bg-yellow-500\/10:hover{background-color:#edb2001a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-yellow-500\/10:hover{background-color:color-mix(in oklab,var(--color-yellow-500)10%,transparent)}}.hover\:text-blue-400:hover{color:var(--color-blue-400)}.hover\:text-foreground:hover{color:var(--foreground)}.hover\:text-gray-300:hover{color:var(--color-gray-300)}.hover\:text-green-400:hover{color:var(--color-green-400)}.hover\:text-primary:hover{color:var(--primary)}.hover\:text-red-400:hover{color:var(--color-red-400)}.hover\:text-sidebar-foreground:hover{color:var(--sidebar-foreground)}.hover\:text-yellow-400:hover{color:var(--color-yellow-400)}.hover\:shadow-lg:hover{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\:shadow-black\/10:hover{--tw-shadow-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.hover\:shadow-black\/10:hover{--tw-shadow-color:color-mix(in oklab,color-mix(in oklab,var(--color-black)10%,transparent)var(--tw-shadow-alpha),transparent)}}}.focus\:border-sidebar-border:focus{border-color:var(--sidebar-border)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-blue-500:focus{--tw-ring-color:var(--color-blue-500)}.focus\:ring-ring:focus{--tw-ring-color:var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,)0 0 0 var(--tw-ring-offset-width)var(--tw-ring-offset-color)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:opacity-50:disabled{opacity:.5}@media(min-width:40rem){.sm\:w-auto{width:auto}.sm\:max-w-md{max-width:var(--container-md)}.sm\:gap-0{gap:calc(var(--spacing)*0)}}@media(min-width:48rem){.md\:flex{display:flex}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:items-center{align-items:center}.md\:items-start{align-items:flex-start}.md\:justify-between{justify-content:space-between}}@media(min-width:64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:80rem){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(prefers-color-scheme:dark){.dark\:bg-red-600{background-color:var(--color-red-600)}.dark\:bg-sidebar-accent\/50{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.dark\:bg-sidebar-accent\/50{background-color:color-mix(in oklab,var(--sidebar-accent)50%,transparent)}}.dark\:text-gray-200{color:var(--color-gray-200)}.dark\:text-gray-400{color:var(--color-gray-400)}.dark\:text-red-500{color:var(--color-red-500)}.dark\:placeholder\:text-gray-400::placeholder{color:var(--color-gray-400)}@media(hover:hover){.dark\:hover\:bg-red-700:hover{background-color:var(--color-red-700)}.dark\:hover\:bg-sidebar:hover{background-color:var(--sidebar)}.dark\:hover\:bg-sidebar-accent:hover{background-color:var(--sidebar-accent)}.dark\:hover\:text-gray-400:hover{color:var(--color-gray-400)}}}.scrollbar-hidden{scrollbar-width:none!important;-ms-overflow-style:none!important}.scrollbar-hidden::-webkit-scrollbar{display:none!important}.scrollbar-thin::-webkit-scrollbar{width:6px!important;height:6px!important}.scrollbar-thin::-webkit-scrollbar-thumb{background-color:#9ca3af4d!important;border-radius:3px!important}.scrollbar-thin::-webkit-scrollbar-thumb:hover{background-color:#9ca3af80!important}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}} diff --git a/manager/dist/assets/index-CRnVAbpY.js b/manager/dist/assets/index-CRnVAbpY.js new file mode 100644 index 0000000..d466c7c --- /dev/null +++ b/manager/dist/assets/index-CRnVAbpY.js @@ -0,0 +1,340 @@ +var iC=Object.defineProperty;var lC=(t,n,r)=>n in t?iC(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r;var tb=(t,n,r)=>lC(t,typeof n!="symbol"?n+"":n,r);function cC(t,n){for(var r=0;rs[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const c of i)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&s(u)}).observe(document,{childList:!0,subtree:!0});function r(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(i){if(i.ep)return;i.ep=!0;const c=r(i);fetch(i.href,c)}})();function ix(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var om={exports:{}},Pi={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var nb;function uC(){if(nb)return Pi;nb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(s,i,c){var u=null;if(c!==void 0&&(u=""+c),i.key!==void 0&&(u=""+i.key),"key"in i){c={};for(var f in i)f!=="key"&&(c[f]=i[f])}else c=i;return i=c.ref,{$$typeof:t,type:s,key:u,ref:i!==void 0?i:null,props:c}}return Pi.Fragment=n,Pi.jsx=r,Pi.jsxs=r,Pi}var ab;function dC(){return ab||(ab=1,om.exports=uC()),om.exports}var p=dC(),im={exports:{}},Pe={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var rb;function fC(){if(rb)return Pe;rb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),w=Symbol.iterator;function N(T){return T===null||typeof T!="object"?null:(T=w&&T[w]||T["@@iterator"],typeof T=="function"?T:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,C={};function A(T,Y,D){this.props=T,this.context=Y,this.refs=C,this.updater=D||E}A.prototype.isReactComponent={},A.prototype.setState=function(T,Y){if(typeof T!="object"&&typeof T!="function"&&T!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,T,Y,"setState")},A.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function O(){}O.prototype=A.prototype;function R(T,Y,D){this.props=T,this.context=Y,this.refs=C,this.updater=D||E}var L=R.prototype=new O;L.constructor=R,S(L,A.prototype),L.isPureReactComponent=!0;var I=Array.isArray;function ee(){}var U={H:null,A:null,T:null,S:null},Q=Object.prototype.hasOwnProperty;function le(T,Y,D){var V=D.ref;return{$$typeof:t,type:T,key:Y,ref:V!==void 0?V:null,props:D}}function ue(T,Y){return le(T.type,Y,T.props)}function me(T){return typeof T=="object"&&T!==null&&T.$$typeof===t}function re(T){var Y={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(D){return Y[D]})}var X=/\/+/g;function he(T,Y){return typeof T=="object"&&T!==null&&T.key!=null?re(""+T.key):Y.toString(36)}function be(T){switch(T.status){case"fulfilled":return T.value;case"rejected":throw T.reason;default:switch(typeof T.status=="string"?T.then(ee,ee):(T.status="pending",T.then(function(Y){T.status==="pending"&&(T.status="fulfilled",T.value=Y)},function(Y){T.status==="pending"&&(T.status="rejected",T.reason=Y)})),T.status){case"fulfilled":return T.value;case"rejected":throw T.reason}}throw T}function j(T,Y,D,V,te){var fe=typeof T;(fe==="undefined"||fe==="boolean")&&(T=null);var oe=!1;if(T===null)oe=!0;else switch(fe){case"bigint":case"string":case"number":oe=!0;break;case"object":switch(T.$$typeof){case t:case n:oe=!0;break;case v:return oe=T._init,j(oe(T._payload),Y,D,V,te)}}if(oe)return te=te(T),oe=V===""?"."+he(T,0):V,I(te)?(D="",oe!=null&&(D=oe.replace(X,"$&/")+"/"),j(te,Y,D,"",function(_e){return _e})):te!=null&&(me(te)&&(te=ue(te,D+(te.key==null||T&&T.key===te.key?"":(""+te.key).replace(X,"$&/")+"/")+oe)),Y.push(te)),1;oe=0;var K=V===""?".":V+":";if(I(T))for(var de=0;de>>1,we=j[se];if(0>>1;sei(D,P))Vi(te,D)?(j[se]=te,j[V]=P,se=V):(j[se]=D,j[Y]=P,se=Y);else if(Vi(te,P))j[se]=te,j[V]=P,se=V;else break e}}return Z}function i(j,Z){var P=j.sortIndex-Z.sortIndex;return P!==0?P:j.id-Z.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;t.unstable_now=function(){return c.now()}}else{var u=Date,f=u.now();t.unstable_now=function(){return u.now()-f}}var g=[],h=[],v=1,y=null,w=3,N=!1,E=!1,S=!1,C=!1,A=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function L(j){for(var Z=r(h);Z!==null;){if(Z.callback===null)s(h);else if(Z.startTime<=j)s(h),Z.sortIndex=Z.expirationTime,n(g,Z);else break;Z=r(h)}}function I(j){if(S=!1,L(j),!E)if(r(g)!==null)E=!0,ee||(ee=!0,re());else{var Z=r(h);Z!==null&&be(I,Z.startTime-j)}}var ee=!1,U=-1,Q=5,le=-1;function ue(){return C?!0:!(t.unstable_now()-lej&&ue());){var se=y.callback;if(typeof se=="function"){y.callback=null,w=y.priorityLevel;var we=se(y.expirationTime<=j);if(j=t.unstable_now(),typeof we=="function"){y.callback=we,L(j),Z=!0;break t}y===r(g)&&s(g),L(j)}else s(g);y=r(g)}if(y!==null)Z=!0;else{var T=r(h);T!==null&&be(I,T.startTime-j),Z=!1}}break e}finally{y=null,w=P,N=!1}Z=void 0}}finally{Z?re():ee=!1}}}var re;if(typeof R=="function")re=function(){R(me)};else if(typeof MessageChannel<"u"){var X=new MessageChannel,he=X.port2;X.port1.onmessage=me,re=function(){he.postMessage(null)}}else re=function(){A(me,0)};function be(j,Z){U=A(function(){j(t.unstable_now())},Z)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(j){j.callback=null},t.unstable_forceFrameRate=function(j){0>j||125se?(j.sortIndex=P,n(h,j),r(g)===null&&j===r(h)&&(S?(O(U),U=-1):S=!0,be(I,P-se))):(j.sortIndex=we,n(g,j),E||N||(E=!0,ee||(ee=!0,re()))),j},t.unstable_shouldYield=ue,t.unstable_wrapCallback=function(j){var Z=w;return function(){var P=w;w=Z;try{return j.apply(this,arguments)}finally{w=P}}}})(um)),um}var ib;function hC(){return ib||(ib=1,cm.exports=mC()),cm.exports}var dm={exports:{}},cn={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var lb;function pC(){if(lb)return cn;lb=1;var t=mh();function n(g){var h="https://react.dev/errors/"+g;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),dm.exports=pC(),dm.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ub;function gC(){if(ub)return Hi;ub=1;var t=hC(),n=mh(),r=lx();function s(e){var a="https://react.dev/errors/"+e;if(1we||(e.current=se[we],se[we]=null,we--)}function D(e,a){we++,se[we]=e.current,e.current=a}var V=T(null),te=T(null),fe=T(null),oe=T(null);function K(e,a){switch(D(fe,a),D(te,e),D(V,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?_v(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=_v(a),e=Cv(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Y(V),D(V,e)}function de(){Y(V),Y(te),Y(fe)}function _e(e){e.memoizedState!==null&&D(oe,e);var a=V.current,o=Cv(a,e.type);a!==o&&(D(te,e),D(V,o))}function rt(e){te.current===e&&(Y(V),Y(te)),oe.current===e&&(Y(oe),zi._currentValue=P)}var De,Le;function xe(e){if(De===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);De=a&&a[1]||"",Le=-1)":-1d||M[l]!==F[d]){var ne=` +`+M[l].replace(" at new "," at ");return e.displayName&&ne.includes("")&&(ne=ne.replace("",e.displayName)),ne}while(1<=l&&0<=d);break}}}finally{je=!1,Error.prepareStackTrace=o}return(o=e?e.displayName||e.name:"")?xe(o):""}function pt(e,a){switch(e.tag){case 26:case 27:case 5:return xe(e.type);case 16:return xe("Lazy");case 13:return e.child!==a&&a!==null?xe("Suspense Fallback"):xe("Suspense");case 19:return xe("SuspenseList");case 0:case 15:return at(e.type,!1);case 11:return at(e.type.render,!1);case 1:return at(e.type,!0);case 31:return xe("Activity");default:return""}}function Je(e){try{var a="",o=null;do a+=pt(e,o),o=e,e=e.return;while(e);return a}catch(l){return` +Error generating stack: `+l.message+` +`+l.stack}}var Ue=Object.prototype.hasOwnProperty,k=t.unstable_scheduleCallback,H=t.unstable_cancelCallback,$=t.unstable_shouldYield,ye=t.unstable_requestPaint,pe=t.unstable_now,ge=t.unstable_getCurrentPriorityLevel,Se=t.unstable_ImmediatePriority,qe=t.unstable_UserBlockingPriority,Xe=t.unstable_NormalPriority,Ot=t.unstable_LowPriority,on=t.unstable_IdlePriority,dn=t.log,Fn=t.unstable_setDisableYieldValue,Ft=null,Nt=null;function fn(e){if(typeof dn=="function"&&Fn(e),Nt&&typeof Nt.setStrictMode=="function")try{Nt.setStrictMode(Ft,e)}catch{}}var $t=Math.clz32?Math.clz32:ya,Xo=Math.log,cr=Math.LN2;function ya(e){return e>>>=0,e===0?32:31-(Xo(e)/cr|0)|0}var As=256,Rs=262144,Xr=4194304;function va(e){var a=e&42;if(a!==0)return a;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Be(e,a,o){var l=e.pendingLanes;if(l===0)return 0;var d=0,m=e.suspendedLanes,x=e.pingedLanes;e=e.warmLanes;var _=l&134217727;return _!==0?(l=_&~m,l!==0?d=va(l):(x&=_,x!==0?d=va(x):o||(o=_&~e,o!==0&&(d=va(o))))):(_=l&~m,_!==0?d=va(_):x!==0?d=va(x):o||(o=l&~e,o!==0&&(d=va(o)))),d===0?0:a!==0&&a!==d&&(a&m)===0&&(m=d&-d,o=a&-a,m>=o||m===32&&(o&4194048)!==0)?a:d}function Et(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function Kt(e,a){switch(e){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ln(){var e=Xr;return Xr<<=1,(Xr&62914560)===0&&(Xr=4194304),e}function ur(e){for(var a=[],o=0;31>o;o++)a.push(e);return a}function At(e,a){e.pendingLanes|=a,a!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function gn(e,a,o,l,d,m){var x=e.pendingLanes;e.pendingLanes=o,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=o,e.entangledLanes&=o,e.errorRecoveryDisabledLanes&=o,e.shellSuspendCounter=0;var _=e.entanglements,M=e.expirationTimes,F=e.hiddenUpdates;for(o=x&~o;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var tE=/[\n"\\]/g;function Gn(e){return e.replace(tE,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Ju(e,a,o,l,d,m,x,_){e.name="",x!=null&&typeof x!="function"&&typeof x!="symbol"&&typeof x!="boolean"?e.type=x:e.removeAttribute("type"),a!=null?x==="number"?(a===0&&e.value===""||e.value!=a)&&(e.value=""+$n(a)):e.value!==""+$n(a)&&(e.value=""+$n(a)):x!=="submit"&&x!=="reset"||e.removeAttribute("value"),a!=null?ed(e,x,$n(a)):o!=null?ed(e,x,$n(o)):l!=null&&e.removeAttribute("value"),d==null&&m!=null&&(e.defaultChecked=!!m),d!=null&&(e.checked=d&&typeof d!="function"&&typeof d!="symbol"),_!=null&&typeof _!="function"&&typeof _!="symbol"&&typeof _!="boolean"?e.name=""+$n(_):e.removeAttribute("name")}function vp(e,a,o,l,d,m,x,_){if(m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"&&(e.type=m),a!=null||o!=null){if(!(m!=="submit"&&m!=="reset"||a!=null)){Wu(e);return}o=o!=null?""+$n(o):"",a=a!=null?""+$n(a):o,_||a===e.value||(e.value=a),e.defaultValue=a}l=l??d,l=typeof l!="function"&&typeof l!="symbol"&&!!l,e.checked=_?e.checked:!!l,e.defaultChecked=!!l,x!=null&&typeof x!="function"&&typeof x!="symbol"&&typeof x!="boolean"&&(e.name=x),Wu(e)}function ed(e,a,o){a==="number"&&xl(e.ownerDocument)===e||e.defaultValue===""+o||(e.defaultValue=""+o)}function zs(e,a,o,l){if(e=e.options,a){a={};for(var d=0;d"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),sd=!1;if(Ua)try{var Jo={};Object.defineProperty(Jo,"passive",{get:function(){sd=!0}}),window.addEventListener("test",Jo,Jo),window.removeEventListener("test",Jo,Jo)}catch{sd=!1}var fr=null,od=null,Sl=null;function Cp(){if(Sl)return Sl;var e,a=od,o=a.length,l,d="value"in fr?fr.value:fr.textContent,m=d.length;for(e=0;e=ni),Op=" ",kp=!1;function Mp(e,a){switch(e){case"keyup":return TE.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Dp(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ps=!1;function OE(e,a){switch(e){case"compositionend":return Dp(a);case"keypress":return a.which!==32?null:(kp=!0,Op);case"textInput":return e=a.data,e===Op&&kp?null:e;default:return null}}function kE(e,a){if(Ps)return e==="compositionend"||!dd&&Mp(e,a)?(e=Cp(),Sl=od=fr=null,Ps=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:o,offset:a-e};e=l}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=Ip(o)}}function Fp(e,a){return e&&a?e===a?!0:e&&e.nodeType===3?!1:a&&a.nodeType===3?Fp(e,a.parentNode):"contains"in e?e.contains(a):e.compareDocumentPosition?!!(e.compareDocumentPosition(a)&16):!1:!1}function $p(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var a=xl(e.document);a instanceof e.HTMLIFrameElement;){try{var o=typeof a.contentWindow.location.href=="string"}catch{o=!1}if(o)e=a.contentWindow;else break;a=xl(e.document)}return a}function hd(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a&&(a==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||a==="textarea"||e.contentEditable==="true")}var HE=Ua&&"documentMode"in document&&11>=document.documentMode,Hs=null,pd=null,oi=null,gd=!1;function Gp(e,a,o){var l=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;gd||Hs==null||Hs!==xl(l)||(l=Hs,"selectionStart"in l&&hd(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),oi&&si(oi,l)||(oi=l,l=pc(pd,"onSelect"),0>=x,d-=x,ba=1<<32-$t(a)+d|o<Ge?(tt=Oe,Oe=null):tt=Oe.sibling;var ct=G(B,Oe,q[Ge],ie);if(ct===null){Oe===null&&(Oe=tt);break}e&&Oe&&ct.alternate===null&&a(B,Oe),z=m(ct,z,Ge),lt===null?Me=ct:lt.sibling=ct,lt=ct,Oe=tt}if(Ge===q.length)return o(B,Oe),nt&&Pa(B,Ge),Me;if(Oe===null){for(;GeGe?(tt=Oe,Oe=null):tt=Oe.sibling;var Dr=G(B,Oe,ct.value,ie);if(Dr===null){Oe===null&&(Oe=tt);break}e&&Oe&&Dr.alternate===null&&a(B,Oe),z=m(Dr,z,Ge),lt===null?Me=Dr:lt.sibling=Dr,lt=Dr,Oe=tt}if(ct.done)return o(B,Oe),nt&&Pa(B,Ge),Me;if(Oe===null){for(;!ct.done;Ge++,ct=q.next())ct=ce(B,ct.value,ie),ct!==null&&(z=m(ct,z,Ge),lt===null?Me=ct:lt.sibling=ct,lt=ct);return nt&&Pa(B,Ge),Me}for(Oe=l(Oe);!ct.done;Ge++,ct=q.next())ct=J(Oe,B,Ge,ct.value,ie),ct!==null&&(e&&ct.alternate!==null&&Oe.delete(ct.key===null?Ge:ct.key),z=m(ct,z,Ge),lt===null?Me=ct:lt.sibling=ct,lt=ct);return e&&Oe.forEach(function(oC){return a(B,oC)}),nt&&Pa(B,Ge),Me}function vt(B,z,q,ie){if(typeof q=="object"&&q!==null&&q.type===S&&q.key===null&&(q=q.props.children),typeof q=="object"&&q!==null){switch(q.$$typeof){case N:e:{for(var Me=q.key;z!==null;){if(z.key===Me){if(Me=q.type,Me===S){if(z.tag===7){o(B,z.sibling),ie=d(z,q.props.children),ie.return=B,B=ie;break e}}else if(z.elementType===Me||typeof Me=="object"&&Me!==null&&Me.$$typeof===Q&&is(Me)===z.type){o(B,z.sibling),ie=d(z,q.props),fi(ie,q),ie.return=B,B=ie;break e}o(B,z);break}else a(B,z);z=z.sibling}q.type===S?(ie=ns(q.props.children,B.mode,ie,q.key),ie.return=B,B=ie):(ie=kl(q.type,q.key,q.props,null,B.mode,ie),fi(ie,q),ie.return=B,B=ie)}return x(B);case E:e:{for(Me=q.key;z!==null;){if(z.key===Me)if(z.tag===4&&z.stateNode.containerInfo===q.containerInfo&&z.stateNode.implementation===q.implementation){o(B,z.sibling),ie=d(z,q.children||[]),ie.return=B,B=ie;break e}else{o(B,z);break}else a(B,z);z=z.sibling}ie=Ed(q,B.mode,ie),ie.return=B,B=ie}return x(B);case Q:return q=is(q),vt(B,z,q,ie)}if(be(q))return Ce(B,z,q,ie);if(re(q)){if(Me=re(q),typeof Me!="function")throw Error(s(150));return q=Me.call(q),ze(B,z,q,ie)}if(typeof q.then=="function")return vt(B,z,Pl(q),ie);if(q.$$typeof===R)return vt(B,z,zl(B,q),ie);Hl(B,q)}return typeof q=="string"&&q!==""||typeof q=="number"||typeof q=="bigint"?(q=""+q,z!==null&&z.tag===6?(o(B,z.sibling),ie=d(z,q),ie.return=B,B=ie):(o(B,z),ie=Sd(q,B.mode,ie),ie.return=B,B=ie),x(B)):o(B,z)}return function(B,z,q,ie){try{di=0;var Me=vt(B,z,q,ie);return Qs=null,Me}catch(Oe){if(Oe===Ks||Oe===Ul)throw Oe;var lt=On(29,Oe,null,B.mode);return lt.lanes=ie,lt.return=B,lt}finally{}}}var cs=pg(!0),gg=pg(!1),yr=!1;function zd(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ld(e,a){e=e.updateQueue,a.updateQueue===e&&(a.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function vr(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function br(e,a,o){var l=e.updateQueue;if(l===null)return null;if(l=l.shared,(dt&2)!==0){var d=l.pending;return d===null?a.next=a:(a.next=d.next,d.next=a),l.pending=a,a=Ol(e),Jp(e,null,o),a}return jl(e,l,a,o),Ol(e)}function mi(e,a,o){if(a=a.updateQueue,a!==null&&(a=a.shared,(o&4194048)!==0)){var l=a.lanes;l&=e.pendingLanes,o|=l,a.lanes=o,yn(e,o)}}function Ud(e,a){var o=e.updateQueue,l=e.alternate;if(l!==null&&(l=l.updateQueue,o===l)){var d=null,m=null;if(o=o.firstBaseUpdate,o!==null){do{var x={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};m===null?d=m=x:m=m.next=x,o=o.next}while(o!==null);m===null?d=m=a:m=m.next=a}else d=m=a;o={baseState:l.baseState,firstBaseUpdate:d,lastBaseUpdate:m,shared:l.shared,callbacks:l.callbacks},e.updateQueue=o;return}e=o.lastBaseUpdate,e===null?o.firstBaseUpdate=a:e.next=a,o.lastBaseUpdate=a}var Bd=!1;function hi(){if(Bd){var e=Xs;if(e!==null)throw e}}function pi(e,a,o,l){Bd=!1;var d=e.updateQueue;yr=!1;var m=d.firstBaseUpdate,x=d.lastBaseUpdate,_=d.shared.pending;if(_!==null){d.shared.pending=null;var M=_,F=M.next;M.next=null,x===null?m=F:x.next=F,x=M;var ne=e.alternate;ne!==null&&(ne=ne.updateQueue,_=ne.lastBaseUpdate,_!==x&&(_===null?ne.firstBaseUpdate=F:_.next=F,ne.lastBaseUpdate=M))}if(m!==null){var ce=d.baseState;x=0,ne=F=M=null,_=m;do{var G=_.lane&-536870913,J=G!==_.lane;if(J?(et&G)===G:(l&G)===G){G!==0&&G===Zs&&(Bd=!0),ne!==null&&(ne=ne.next={lane:0,tag:_.tag,payload:_.payload,callback:null,next:null});e:{var Ce=e,ze=_;G=a;var vt=o;switch(ze.tag){case 1:if(Ce=ze.payload,typeof Ce=="function"){ce=Ce.call(vt,ce,G);break e}ce=Ce;break e;case 3:Ce.flags=Ce.flags&-65537|128;case 0:if(Ce=ze.payload,G=typeof Ce=="function"?Ce.call(vt,ce,G):Ce,G==null)break e;ce=y({},ce,G);break e;case 2:yr=!0}}G=_.callback,G!==null&&(e.flags|=64,J&&(e.flags|=8192),J=d.callbacks,J===null?d.callbacks=[G]:J.push(G))}else J={lane:G,tag:_.tag,payload:_.payload,callback:_.callback,next:null},ne===null?(F=ne=J,M=ce):ne=ne.next=J,x|=G;if(_=_.next,_===null){if(_=d.shared.pending,_===null)break;J=_,_=J.next,J.next=null,d.lastBaseUpdate=J,d.shared.pending=null}}while(!0);ne===null&&(M=ce),d.baseState=M,d.firstBaseUpdate=F,d.lastBaseUpdate=ne,m===null&&(d.shared.lanes=0),_r|=x,e.lanes=x,e.memoizedState=ce}}function yg(e,a){if(typeof e!="function")throw Error(s(191,e));e.call(a)}function vg(e,a){var o=e.callbacks;if(o!==null)for(e.callbacks=null,e=0;em?m:8;var x=j.T,_={};j.T=_,af(e,!1,a,o);try{var M=d(),F=j.S;if(F!==null&&F(_,M),M!==null&&typeof M=="object"&&typeof M.then=="function"){var ne=XE(M,l);vi(e,a,ne,Ln(e))}else vi(e,a,l,Ln(e))}catch(ce){vi(e,a,{then:function(){},status:"rejected",reason:ce},Ln())}finally{Z.p=m,x!==null&&_.types!==null&&(x.types=_.types),j.T=x}}function t_(){}function tf(e,a,o,l){if(e.tag!==5)throw Error(s(476));var d=Kg(e).queue;Xg(e,d,a,P,o===null?t_:function(){return Qg(e),o(l)})}function Kg(e){var a=e.memoizedState;if(a!==null)return a;a={memoizedState:P,baseState:P,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qa,lastRenderedState:P},next:null};var o={};return a.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qa,lastRenderedState:o},next:null},e.memoizedState=a,e=e.alternate,e!==null&&(e.memoizedState=a),a}function Qg(e){var a=Kg(e);a.next===null&&(a=e.alternate.memoizedState),vi(e,a.next.queue,{},Ln())}function nf(){return nn(zi)}function Wg(){return Mt().memoizedState}function Jg(){return Mt().memoizedState}function n_(e){for(var a=e.return;a!==null;){switch(a.tag){case 24:case 3:var o=Ln();e=vr(o);var l=br(a,e,o);l!==null&&(Cn(l,a,o),mi(l,a,o)),a={cache:Od()},e.payload=a;return}a=a.return}}function a_(e,a,o){var l=Ln();o={lane:l,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Kl(e)?ty(a,o):(o=xd(e,a,o,l),o!==null&&(Cn(o,e,l),ny(o,a,l)))}function ey(e,a,o){var l=Ln();vi(e,a,o,l)}function vi(e,a,o,l){var d={lane:l,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Kl(e))ty(a,d);else{var m=e.alternate;if(e.lanes===0&&(m===null||m.lanes===0)&&(m=a.lastRenderedReducer,m!==null))try{var x=a.lastRenderedState,_=m(x,o);if(d.hasEagerState=!0,d.eagerState=_,jn(_,x))return jl(e,a,d,0),bt===null&&Tl(),!1}catch{}finally{}if(o=xd(e,a,d,l),o!==null)return Cn(o,e,l),ny(o,a,l),!0}return!1}function af(e,a,o,l){if(l={lane:2,revertLane:Lf(),gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Kl(e)){if(a)throw Error(s(479))}else a=xd(e,o,l,2),a!==null&&Cn(a,e,2)}function Kl(e){var a=e.alternate;return e===Fe||a!==null&&a===Fe}function ty(e,a){Js=ql=!0;var o=e.pending;o===null?a.next=a:(a.next=o.next,o.next=a),e.pending=a}function ny(e,a,o){if((o&4194048)!==0){var l=a.lanes;l&=e.pendingLanes,o|=l,a.lanes=o,yn(e,o)}}var bi={readContext:nn,use:Gl,useCallback:Rt,useContext:Rt,useEffect:Rt,useImperativeHandle:Rt,useLayoutEffect:Rt,useInsertionEffect:Rt,useMemo:Rt,useReducer:Rt,useRef:Rt,useState:Rt,useDebugValue:Rt,useDeferredValue:Rt,useTransition:Rt,useSyncExternalStore:Rt,useId:Rt,useHostTransitionStatus:Rt,useFormState:Rt,useActionState:Rt,useOptimistic:Rt,useMemoCache:Rt,useCacheRefresh:Rt};bi.useEffectEvent=Rt;var ay={readContext:nn,use:Gl,useCallback:function(e,a){return mn().memoizedState=[e,a===void 0?null:a],e},useContext:nn,useEffect:Hg,useImperativeHandle:function(e,a,o){o=o!=null?o.concat([e]):null,Zl(4194308,4,Fg.bind(null,a,e),o)},useLayoutEffect:function(e,a){return Zl(4194308,4,e,a)},useInsertionEffect:function(e,a){Zl(4,2,e,a)},useMemo:function(e,a){var o=mn();a=a===void 0?null:a;var l=e();if(us){fn(!0);try{e()}finally{fn(!1)}}return o.memoizedState=[l,a],l},useReducer:function(e,a,o){var l=mn();if(o!==void 0){var d=o(a);if(us){fn(!0);try{o(a)}finally{fn(!1)}}}else d=a;return l.memoizedState=l.baseState=d,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:d},l.queue=e,e=e.dispatch=a_.bind(null,Fe,e),[l.memoizedState,e]},useRef:function(e){var a=mn();return e={current:e},a.memoizedState=e},useState:function(e){e=Kd(e);var a=e.queue,o=ey.bind(null,Fe,a);return a.dispatch=o,[e.memoizedState,o]},useDebugValue:Jd,useDeferredValue:function(e,a){var o=mn();return ef(o,e,a)},useTransition:function(){var e=Kd(!1);return e=Xg.bind(null,Fe,e.queue,!0,!1),mn().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,a,o){var l=Fe,d=mn();if(nt){if(o===void 0)throw Error(s(407));o=o()}else{if(o=a(),bt===null)throw Error(s(349));(et&127)!==0||_g(l,a,o)}d.memoizedState=o;var m={value:o,getSnapshot:a};return d.queue=m,Hg(Ng.bind(null,l,m,e),[e]),l.flags|=2048,to(9,{destroy:void 0},Cg.bind(null,l,m,o,a),null),o},useId:function(){var e=mn(),a=bt.identifierPrefix;if(nt){var o=xa,l=ba;o=(l&~(1<<32-$t(l)-1)).toString(32)+o,a="_"+a+"R_"+o,o=Fl++,0<\/script>",m=m.removeChild(m.firstChild);break;case"select":m=typeof l.is=="string"?x.createElement("select",{is:l.is}):x.createElement("select"),l.multiple?m.multiple=!0:l.size&&(m.size=l.size);break;default:m=typeof l.is=="string"?x.createElement(d,{is:l.is}):x.createElement(d)}}m[en]=a,m[bn]=l;e:for(x=a.child;x!==null;){if(x.tag===5||x.tag===6)m.appendChild(x.stateNode);else if(x.tag!==4&&x.tag!==27&&x.child!==null){x.child.return=x,x=x.child;continue}if(x===a)break e;for(;x.sibling===null;){if(x.return===null||x.return===a)break e;x=x.return}x.sibling.return=x.return,x=x.sibling}a.stateNode=m;e:switch(rn(m,d,l),d){case"button":case"input":case"select":case"textarea":l=!!l.autoFocus;break e;case"img":l=!0;break e;default:l=!1}l&&$a(a)}}return St(a),vf(a,a.type,e===null?null:e.memoizedProps,a.pendingProps,o),null;case 6:if(e&&a.stateNode!=null)e.memoizedProps!==l&&$a(a);else{if(typeof l!="string"&&a.stateNode===null)throw Error(s(166));if(e=fe.current,Gs(a)){if(e=a.stateNode,o=a.memoizedProps,l=null,d=tn,d!==null)switch(d.tag){case 27:case 5:l=d.memoizedProps}e[en]=a,e=!!(e.nodeValue===o||l!==null&&l.suppressHydrationWarning===!0||Sv(e.nodeValue,o)),e||pr(a,!0)}else e=gc(e).createTextNode(l),e[en]=a,a.stateNode=e}return St(a),null;case 31:if(o=a.memoizedState,e===null||e.memoizedState!==null){if(l=Gs(a),o!==null){if(e===null){if(!l)throw Error(s(318));if(e=a.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(557));e[en]=a}else as(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;St(a),e=!1}else o=Ad(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=o),e=!0;if(!e)return a.flags&256?(Mn(a),a):(Mn(a),null);if((a.flags&128)!==0)throw Error(s(558))}return St(a),null;case 13:if(l=a.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(d=Gs(a),l!==null&&l.dehydrated!==null){if(e===null){if(!d)throw Error(s(318));if(d=a.memoizedState,d=d!==null?d.dehydrated:null,!d)throw Error(s(317));d[en]=a}else as(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;St(a),d=!1}else d=Ad(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=d),d=!0;if(!d)return a.flags&256?(Mn(a),a):(Mn(a),null)}return Mn(a),(a.flags&128)!==0?(a.lanes=o,a):(o=l!==null,e=e!==null&&e.memoizedState!==null,o&&(l=a.child,d=null,l.alternate!==null&&l.alternate.memoizedState!==null&&l.alternate.memoizedState.cachePool!==null&&(d=l.alternate.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==d&&(l.flags|=2048)),o!==e&&o&&(a.child.flags|=8192),tc(a,a.updateQueue),St(a),null);case 4:return de(),e===null&&Hf(a.stateNode.containerInfo),St(a),null;case 10:return Va(a.type),St(a),null;case 19:if(Y(kt),l=a.memoizedState,l===null)return St(a),null;if(d=(a.flags&128)!==0,m=l.rendering,m===null)if(d)wi(l,!1);else{if(Tt!==0||e!==null&&(e.flags&128)!==0)for(e=a.child;e!==null;){if(m=Il(e),m!==null){for(a.flags|=128,wi(l,!1),e=m.updateQueue,a.updateQueue=e,tc(a,e),a.subtreeFlags=0,e=o,o=a.child;o!==null;)eg(o,e),o=o.sibling;return D(kt,kt.current&1|2),nt&&Pa(a,l.treeForkCount),a.child}e=e.sibling}l.tail!==null&&pe()>oc&&(a.flags|=128,d=!0,wi(l,!1),a.lanes=4194304)}else{if(!d)if(e=Il(m),e!==null){if(a.flags|=128,d=!0,e=e.updateQueue,a.updateQueue=e,tc(a,e),wi(l,!0),l.tail===null&&l.tailMode==="hidden"&&!m.alternate&&!nt)return St(a),null}else 2*pe()-l.renderingStartTime>oc&&o!==536870912&&(a.flags|=128,d=!0,wi(l,!1),a.lanes=4194304);l.isBackwards?(m.sibling=a.child,a.child=m):(e=l.last,e!==null?e.sibling=m:a.child=m,l.last=m)}return l.tail!==null?(e=l.tail,l.rendering=e,l.tail=e.sibling,l.renderingStartTime=pe(),e.sibling=null,o=kt.current,D(kt,d?o&1|2:o&1),nt&&Pa(a,l.treeForkCount),e):(St(a),null);case 22:case 23:return Mn(a),Hd(),l=a.memoizedState!==null,e!==null?e.memoizedState!==null!==l&&(a.flags|=8192):l&&(a.flags|=8192),l?(o&536870912)!==0&&(a.flags&128)===0&&(St(a),a.subtreeFlags&6&&(a.flags|=8192)):St(a),o=a.updateQueue,o!==null&&tc(a,o.retryQueue),o=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(o=e.memoizedState.cachePool.pool),l=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(l=a.memoizedState.cachePool.pool),l!==o&&(a.flags|=2048),e!==null&&Y(os),null;case 24:return o=null,e!==null&&(o=e.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),Va(Lt),St(a),null;case 25:return null;case 30:return null}throw Error(s(156,a.tag))}function l_(e,a){switch(Cd(a),a.tag){case 1:return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 3:return Va(Lt),de(),e=a.flags,(e&65536)!==0&&(e&128)===0?(a.flags=e&-65537|128,a):null;case 26:case 27:case 5:return rt(a),null;case 31:if(a.memoizedState!==null){if(Mn(a),a.alternate===null)throw Error(s(340));as()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 13:if(Mn(a),e=a.memoizedState,e!==null&&e.dehydrated!==null){if(a.alternate===null)throw Error(s(340));as()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 19:return Y(kt),null;case 4:return de(),null;case 10:return Va(a.type),null;case 22:case 23:return Mn(a),Hd(),e!==null&&Y(os),e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 24:return Va(Lt),null;case 25:return null;default:return null}}function Ay(e,a){switch(Cd(a),a.tag){case 3:Va(Lt),de();break;case 26:case 27:case 5:rt(a);break;case 4:de();break;case 31:a.memoizedState!==null&&Mn(a);break;case 13:Mn(a);break;case 19:Y(kt);break;case 10:Va(a.type);break;case 22:case 23:Mn(a),Hd(),e!==null&&Y(os);break;case 24:Va(Lt)}}function Si(e,a){try{var o=a.updateQueue,l=o!==null?o.lastEffect:null;if(l!==null){var d=l.next;o=d;do{if((o.tag&e)===e){l=void 0;var m=o.create,x=o.inst;l=m(),x.destroy=l}o=o.next}while(o!==d)}}catch(_){ht(a,a.return,_)}}function Sr(e,a,o){try{var l=a.updateQueue,d=l!==null?l.lastEffect:null;if(d!==null){var m=d.next;l=m;do{if((l.tag&e)===e){var x=l.inst,_=x.destroy;if(_!==void 0){x.destroy=void 0,d=a;var M=o,F=_;try{F()}catch(ne){ht(d,M,ne)}}}l=l.next}while(l!==m)}}catch(ne){ht(a,a.return,ne)}}function Ry(e){var a=e.updateQueue;if(a!==null){var o=e.stateNode;try{vg(a,o)}catch(l){ht(e,e.return,l)}}}function Ty(e,a,o){o.props=ds(e.type,e.memoizedProps),o.state=e.memoizedState;try{o.componentWillUnmount()}catch(l){ht(e,a,l)}}function Ei(e,a){try{var o=e.ref;if(o!==null){switch(e.tag){case 26:case 27:case 5:var l=e.stateNode;break;case 30:l=e.stateNode;break;default:l=e.stateNode}typeof o=="function"?e.refCleanup=o(l):o.current=l}}catch(d){ht(e,a,d)}}function wa(e,a){var o=e.ref,l=e.refCleanup;if(o!==null)if(typeof l=="function")try{l()}catch(d){ht(e,a,d)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(d){ht(e,a,d)}else o.current=null}function jy(e){var a=e.type,o=e.memoizedProps,l=e.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":o.autoFocus&&l.focus();break e;case"img":o.src?l.src=o.src:o.srcSet&&(l.srcset=o.srcSet)}}catch(d){ht(e,e.return,d)}}function bf(e,a,o){try{var l=e.stateNode;j_(l,e.type,o,a),l[bn]=a}catch(d){ht(e,e.return,d)}}function Oy(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Tr(e.type)||e.tag===4}function xf(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Oy(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Tr(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function wf(e,a,o){var l=e.tag;if(l===5||l===6)e=e.stateNode,a?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(e,a):(a=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,a.appendChild(e),o=o._reactRootContainer,o!=null||a.onclick!==null||(a.onclick=La));else if(l!==4&&(l===27&&Tr(e.type)&&(o=e.stateNode,a=null),e=e.child,e!==null))for(wf(e,a,o),e=e.sibling;e!==null;)wf(e,a,o),e=e.sibling}function nc(e,a,o){var l=e.tag;if(l===5||l===6)e=e.stateNode,a?o.insertBefore(e,a):o.appendChild(e);else if(l!==4&&(l===27&&Tr(e.type)&&(o=e.stateNode),e=e.child,e!==null))for(nc(e,a,o),e=e.sibling;e!==null;)nc(e,a,o),e=e.sibling}function ky(e){var a=e.stateNode,o=e.memoizedProps;try{for(var l=e.type,d=a.attributes;d.length;)a.removeAttributeNode(d[0]);rn(a,l,o),a[en]=e,a[bn]=o}catch(m){ht(e,e.return,m)}}var Ga=!1,Pt=!1,Sf=!1,My=typeof WeakSet=="function"?WeakSet:Set,Wt=null;function c_(e,a){if(e=e.containerInfo,qf=Ec,e=$p(e),hd(e)){if("selectionStart"in e)var o={start:e.selectionStart,end:e.selectionEnd};else e:{o=(o=e.ownerDocument)&&o.defaultView||window;var l=o.getSelection&&o.getSelection();if(l&&l.rangeCount!==0){o=l.anchorNode;var d=l.anchorOffset,m=l.focusNode;l=l.focusOffset;try{o.nodeType,m.nodeType}catch{o=null;break e}var x=0,_=-1,M=-1,F=0,ne=0,ce=e,G=null;t:for(;;){for(var J;ce!==o||d!==0&&ce.nodeType!==3||(_=x+d),ce!==m||l!==0&&ce.nodeType!==3||(M=x+l),ce.nodeType===3&&(x+=ce.nodeValue.length),(J=ce.firstChild)!==null;)G=ce,ce=J;for(;;){if(ce===e)break t;if(G===o&&++F===d&&(_=x),G===m&&++ne===l&&(M=x),(J=ce.nextSibling)!==null)break;ce=G,G=ce.parentNode}ce=J}o=_===-1||M===-1?null:{start:_,end:M}}else o=null}o=o||{start:0,end:0}}else o=null;for(Ff={focusedElem:e,selectionRange:o},Ec=!1,Wt=a;Wt!==null;)if(a=Wt,e=a.child,(a.subtreeFlags&1028)!==0&&e!==null)e.return=a,Wt=e;else for(;Wt!==null;){switch(a=Wt,m=a.alternate,e=a.flags,a.tag){case 0:if((e&4)!==0&&(e=a.updateQueue,e=e!==null?e.events:null,e!==null))for(o=0;o title"))),rn(m,l,o),m[en]=e,Qt(m),l=m;break e;case"link":var x=Pv("link","href",d).get(l+(o.href||""));if(x){for(var _=0;_vt&&(x=vt,vt=ze,ze=x);var B=qp(_,ze),z=qp(_,vt);if(B&&z&&(J.rangeCount!==1||J.anchorNode!==B.node||J.anchorOffset!==B.offset||J.focusNode!==z.node||J.focusOffset!==z.offset)){var q=ce.createRange();q.setStart(B.node,B.offset),J.removeAllRanges(),ze>vt?(J.addRange(q),J.extend(z.node,z.offset)):(q.setEnd(z.node,z.offset),J.addRange(q))}}}}for(ce=[],J=_;J=J.parentNode;)J.nodeType===1&&ce.push({element:J,left:J.scrollLeft,top:J.scrollTop});for(typeof _.focus=="function"&&_.focus(),_=0;_o?32:o,j.T=null,o=Tf,Tf=null;var m=Nr,x=Qa;if(Gt=0,oo=Nr=null,Qa=0,(dt&6)!==0)throw Error(s(331));var _=dt;if(dt|=4,Fy(m.current),Vy(m,m.current,x,o),dt=_,Ti(0,!1),Nt&&typeof Nt.onPostCommitFiberRoot=="function")try{Nt.onPostCommitFiberRoot(Ft,m)}catch{}return!0}finally{Z.p=d,j.T=l,lv(e,a)}}function uv(e,a,o){a=Zn(o,a),a=lf(e.stateNode,a,2),e=br(e,a,2),e!==null&&(At(e,2),Sa(e))}function ht(e,a,o){if(e.tag===3)uv(e,e,o);else for(;a!==null;){if(a.tag===3){uv(a,e,o);break}else if(a.tag===1){var l=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof l.componentDidCatch=="function"&&(Cr===null||!Cr.has(l))){e=Zn(o,e),o=dy(2),l=br(a,o,2),l!==null&&(fy(o,l,a,e),At(l,2),Sa(l));break}}a=a.return}}function Mf(e,a,o){var l=e.pingCache;if(l===null){l=e.pingCache=new f_;var d=new Set;l.set(a,d)}else d=l.get(a),d===void 0&&(d=new Set,l.set(a,d));d.has(o)||(Cf=!0,d.add(o),e=y_.bind(null,e,a,o),a.then(e,e))}function y_(e,a,o){var l=e.pingCache;l!==null&&l.delete(a),e.pingedLanes|=e.suspendedLanes&o,e.warmLanes&=~o,bt===e&&(et&o)===o&&(Tt===4||Tt===3&&(et&62914560)===et&&300>pe()-sc?(dt&2)===0&&io(e,0):Nf|=o,so===et&&(so=0)),Sa(e)}function dv(e,a){a===0&&(a=ln()),e=ts(e,a),e!==null&&(At(e,a),Sa(e))}function v_(e){var a=e.memoizedState,o=0;a!==null&&(o=a.retryLane),dv(e,o)}function b_(e,a){var o=0;switch(e.tag){case 31:case 13:var l=e.stateNode,d=e.memoizedState;d!==null&&(o=d.retryLane);break;case 19:l=e.stateNode;break;case 22:l=e.stateNode._retryCache;break;default:throw Error(s(314))}l!==null&&l.delete(a),dv(e,o)}function x_(e,a){return k(e,a)}var fc=null,co=null,Df=!1,mc=!1,zf=!1,Rr=0;function Sa(e){e!==co&&e.next===null&&(co===null?fc=co=e:co=co.next=e),mc=!0,Df||(Df=!0,S_())}function Ti(e,a){if(!zf&&mc){zf=!0;do for(var o=!1,l=fc;l!==null;){if(e!==0){var d=l.pendingLanes;if(d===0)var m=0;else{var x=l.suspendedLanes,_=l.pingedLanes;m=(1<<31-$t(42|e)+1)-1,m&=d&~(x&~_),m=m&201326741?m&201326741|1:m?m|2:0}m!==0&&(o=!0,pv(l,m))}else m=et,m=Be(l,l===bt?m:0,l.cancelPendingCommit!==null||l.timeoutHandle!==-1),(m&3)===0||Et(l,m)||(o=!0,pv(l,m));l=l.next}while(o);zf=!1}}function w_(){fv()}function fv(){mc=Df=!1;var e=0;Rr!==0&&k_()&&(e=Rr);for(var a=pe(),o=null,l=fc;l!==null;){var d=l.next,m=mv(l,a);m===0?(l.next=null,o===null?fc=d:o.next=d,d===null&&(co=o)):(o=l,(e!==0||(m&3)!==0)&&(mc=!0)),l=d}Gt!==0&&Gt!==5||Ti(e),Rr!==0&&(Rr=0)}function mv(e,a){for(var o=e.suspendedLanes,l=e.pingedLanes,d=e.expirationTimes,m=e.pendingLanes&-62914561;0_)break;var ne=M.transferSize,ce=M.initiatorType;ne&&Ev(ce)&&(M=M.responseEnd,x+=ne*(M<_?1:(_-F)/(M-F)))}if(--l,a+=8*(m+x)/(d.duration/1e3),e++,10"u"?null:document;function zv(e,a,o){var l=uo;if(l&&typeof a=="string"&&a){var d=Gn(a);d='link[rel="'+e+'"][href="'+d+'"]',typeof o=="string"&&(d+='[crossorigin="'+o+'"]'),Dv.has(d)||(Dv.add(d),e={rel:e,crossOrigin:o,href:a},l.querySelector(d)===null&&(a=l.createElement("link"),rn(a,"link",e),Qt(a),l.head.appendChild(a)))}}function V_(e){Wa.D(e),zv("dns-prefetch",e,null)}function I_(e,a){Wa.C(e,a),zv("preconnect",e,a)}function q_(e,a,o){Wa.L(e,a,o);var l=uo;if(l&&e&&a){var d='link[rel="preload"][as="'+Gn(a)+'"]';a==="image"&&o&&o.imageSrcSet?(d+='[imagesrcset="'+Gn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(d+='[imagesizes="'+Gn(o.imageSizes)+'"]')):d+='[href="'+Gn(e)+'"]';var m=d;switch(a){case"style":m=fo(e);break;case"script":m=mo(e)}ea.has(m)||(e=y({rel:"preload",href:a==="image"&&o&&o.imageSrcSet?void 0:e,as:a},o),ea.set(m,e),l.querySelector(d)!==null||a==="style"&&l.querySelector(Mi(m))||a==="script"&&l.querySelector(Di(m))||(a=l.createElement("link"),rn(a,"link",e),Qt(a),l.head.appendChild(a)))}}function F_(e,a){Wa.m(e,a);var o=uo;if(o&&e){var l=a&&typeof a.as=="string"?a.as:"script",d='link[rel="modulepreload"][as="'+Gn(l)+'"][href="'+Gn(e)+'"]',m=d;switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":m=mo(e)}if(!ea.has(m)&&(e=y({rel:"modulepreload",href:e},a),ea.set(m,e),o.querySelector(d)===null)){switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(Di(m)))return}l=o.createElement("link"),rn(l,"link",e),Qt(l),o.head.appendChild(l)}}}function $_(e,a,o){Wa.S(e,a,o);var l=uo;if(l&&e){var d=Ms(l).hoistableStyles,m=fo(e);a=a||"default";var x=d.get(m);if(!x){var _={loading:0,preload:null};if(x=l.querySelector(Mi(m)))_.loading=5;else{e=y({rel:"stylesheet",href:e,"data-precedence":a},o),(o=ea.get(m))&&Qf(e,o);var M=x=l.createElement("link");Qt(M),rn(M,"link",e),M._p=new Promise(function(F,ne){M.onload=F,M.onerror=ne}),M.addEventListener("load",function(){_.loading|=1}),M.addEventListener("error",function(){_.loading|=2}),_.loading|=4,vc(x,a,l)}x={type:"stylesheet",instance:x,count:1,state:_},d.set(m,x)}}}function G_(e,a){Wa.X(e,a);var o=uo;if(o&&e){var l=Ms(o).hoistableScripts,d=mo(e),m=l.get(d);m||(m=o.querySelector(Di(d)),m||(e=y({src:e,async:!0},a),(a=ea.get(d))&&Wf(e,a),m=o.createElement("script"),Qt(m),rn(m,"link",e),o.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},l.set(d,m))}}function Y_(e,a){Wa.M(e,a);var o=uo;if(o&&e){var l=Ms(o).hoistableScripts,d=mo(e),m=l.get(d);m||(m=o.querySelector(Di(d)),m||(e=y({src:e,async:!0,type:"module"},a),(a=ea.get(d))&&Wf(e,a),m=o.createElement("script"),Qt(m),rn(m,"link",e),o.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},l.set(d,m))}}function Lv(e,a,o,l){var d=(d=fe.current)?yc(d):null;if(!d)throw Error(s(446));switch(e){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(a=fo(o.href),o=Ms(d).hoistableStyles,l=o.get(a),l||(l={type:"style",instance:null,count:0,state:null},o.set(a,l)),l):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){e=fo(o.href);var m=Ms(d).hoistableStyles,x=m.get(e);if(x||(d=d.ownerDocument||d,x={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},m.set(e,x),(m=d.querySelector(Mi(e)))&&!m._p&&(x.instance=m,x.state.loading=5),ea.has(e)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},ea.set(e,o),m||Z_(d,e,o,x.state))),a&&l===null)throw Error(s(528,""));return x}if(a&&l!==null)throw Error(s(529,""));return null;case"script":return a=o.async,o=o.src,typeof o=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=mo(o),o=Ms(d).hoistableScripts,l=o.get(a),l||(l={type:"script",instance:null,count:0,state:null},o.set(a,l)),l):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,e))}}function fo(e){return'href="'+Gn(e)+'"'}function Mi(e){return'link[rel="stylesheet"]['+e+"]"}function Uv(e){return y({},e,{"data-precedence":e.precedence,precedence:null})}function Z_(e,a,o,l){e.querySelector('link[rel="preload"][as="style"]['+a+"]")?l.loading=1:(a=e.createElement("link"),l.preload=a,a.addEventListener("load",function(){return l.loading|=1}),a.addEventListener("error",function(){return l.loading|=2}),rn(a,"link",o),Qt(a),e.head.appendChild(a))}function mo(e){return'[src="'+Gn(e)+'"]'}function Di(e){return"script[async]"+e}function Bv(e,a,o){if(a.count++,a.instance===null)switch(a.type){case"style":var l=e.querySelector('style[data-href~="'+Gn(o.href)+'"]');if(l)return a.instance=l,Qt(l),l;var d=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return l=(e.ownerDocument||e).createElement("style"),Qt(l),rn(l,"style",d),vc(l,o.precedence,e),a.instance=l;case"stylesheet":d=fo(o.href);var m=e.querySelector(Mi(d));if(m)return a.state.loading|=4,a.instance=m,Qt(m),m;l=Uv(o),(d=ea.get(d))&&Qf(l,d),m=(e.ownerDocument||e).createElement("link"),Qt(m);var x=m;return x._p=new Promise(function(_,M){x.onload=_,x.onerror=M}),rn(m,"link",l),a.state.loading|=4,vc(m,o.precedence,e),a.instance=m;case"script":return m=mo(o.src),(d=e.querySelector(Di(m)))?(a.instance=d,Qt(d),d):(l=o,(d=ea.get(m))&&(l=y({},o),Wf(l,d)),e=e.ownerDocument||e,d=e.createElement("script"),Qt(d),rn(d,"link",l),e.head.appendChild(d),a.instance=d);case"void":return null;default:throw Error(s(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(l=a.instance,a.state.loading|=4,vc(l,o.precedence,e));return a.instance}function vc(e,a,o){for(var l=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),d=l.length?l[l.length-1]:null,m=d,x=0;x title"):null)}function X_(e,a,o){if(o===1||a.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return e=a.disabled,typeof a.precedence=="string"&&e==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function Vv(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function K_(e,a,o,l){if(o.type==="stylesheet"&&(typeof l.media!="string"||matchMedia(l.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var d=fo(l.href),m=a.querySelector(Mi(d));if(m){a=m._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(e.count++,e=xc.bind(e),a.then(e,e)),o.state.loading|=4,o.instance=m,Qt(m);return}m=a.ownerDocument||a,l=Uv(l),(d=ea.get(d))&&Qf(l,d),m=m.createElement("link"),Qt(m);var x=m;x._p=new Promise(function(_,M){x.onload=_,x.onerror=M}),rn(m,"link",l),o.instance=m}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(o,a),(a=o.state.preload)&&(o.state.loading&3)===0&&(e.count++,o=xc.bind(e),a.addEventListener("load",o),a.addEventListener("error",o))}}var Jf=0;function Q_(e,a){return e.stylesheets&&e.count===0&&Sc(e,e.stylesheets),0Jf?50:800)+a);return e.unsuspend=o,function(){e.unsuspend=null,clearTimeout(l),clearTimeout(d)}}:null}function xc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Sc(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var wc=null;function Sc(e,a){e.stylesheets=null,e.unsuspend!==null&&(e.count++,wc=new Map,a.forEach(W_,e),wc=null,xc.call(e))}function W_(e,a){if(!(a.state.loading&4)){var o=wc.get(e);if(o)var l=o.get(null);else{o=new Map,wc.set(e,o);for(var d=e.querySelectorAll("link[data-precedence],style[data-precedence]"),m=0;m"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),lm.exports=gC(),lm.exports}var vC=yC();/** + * react-router v7.9.5 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */var fb="popstate";function bC(t={}){function n(s,i){let{pathname:c,search:u,hash:f}=s.location;return Um("",{pathname:c,search:u,hash:f},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function r(s,i){return typeof i=="string"?i:Wi(i)}return wC(n,r,null,t)}function Ct(t,n){if(t===!1||t===null||typeof t>"u")throw new Error(n)}function da(t,n){if(!t){typeof console<"u"&&console.warn(n);try{throw new Error(n)}catch{}}}function xC(){return Math.random().toString(36).substring(2,10)}function mb(t,n){return{usr:t.state,key:t.key,idx:n}}function Um(t,n,r=null,s){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof n=="string"?Bo(n):n,state:r,key:n&&n.key||s||xC()}}function Wi({pathname:t="/",search:n="",hash:r=""}){return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Bo(t){let n={};if(t){let r=t.indexOf("#");r>=0&&(n.hash=t.substring(r),t=t.substring(0,r));let s=t.indexOf("?");s>=0&&(n.search=t.substring(s),t=t.substring(0,s)),t&&(n.pathname=t)}return n}function wC(t,n,r,s={}){let{window:i=document.defaultView,v5Compat:c=!1}=s,u=i.history,f="POP",g=null,h=v();h==null&&(h=0,u.replaceState({...u.state,idx:h},""));function v(){return(u.state||{idx:null}).idx}function y(){f="POP";let C=v(),A=C==null?null:C-h;h=C,g&&g({action:f,location:S.location,delta:A})}function w(C,A){f="PUSH";let O=Um(S.location,C,A);h=v()+1;let R=mb(O,h),L=S.createHref(O);try{u.pushState(R,"",L)}catch(I){if(I instanceof DOMException&&I.name==="DataCloneError")throw I;i.location.assign(L)}c&&g&&g({action:f,location:S.location,delta:1})}function N(C,A){f="REPLACE";let O=Um(S.location,C,A);h=v();let R=mb(O,h),L=S.createHref(O);u.replaceState(R,"",L),c&&g&&g({action:f,location:S.location,delta:0})}function E(C){return SC(C)}let S={get action(){return f},get location(){return t(i,u)},listen(C){if(g)throw new Error("A history only accepts one active listener");return i.addEventListener(fb,y),g=C,()=>{i.removeEventListener(fb,y),g=null}},createHref(C){return n(i,C)},createURL:E,encodeLocation(C){let A=E(C);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:w,replace:N,go(C){return u.go(C)}};return S}function SC(t,n=!1){let r="http://localhost";typeof window<"u"&&(r=window.location.origin!=="null"?window.location.origin:window.location.href),Ct(r,"No window.location.(origin|href) available to create URL");let s=typeof t=="string"?t:Wi(t);return s=s.replace(/ $/,"%20"),!n&&s.startsWith("//")&&(s=r+s),new URL(s,r)}function cx(t,n,r="/"){return EC(t,n,r,!1)}function EC(t,n,r,s){let i=typeof n=="string"?Bo(n):n,c=ar(i.pathname||"/",r);if(c==null)return null;let u=ux(t);_C(u);let f=null;for(let g=0;f==null&&g{let v={relativePath:h===void 0?u.path||"":h,caseSensitive:u.caseSensitive===!0,childrenIndex:f,route:u};if(v.relativePath.startsWith("/")){if(!v.relativePath.startsWith(s)&&g)return;Ct(v.relativePath.startsWith(s),`Absolute route path "${v.relativePath}" nested under path "${s}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),v.relativePath=v.relativePath.slice(s.length)}let y=nr([s,v.relativePath]),w=r.concat(v);u.children&&u.children.length>0&&(Ct(u.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${y}".`),ux(u.children,n,w,y,g)),!(u.path==null&&!u.index)&&n.push({path:y,score:OC(y,u.index),routesMeta:w})};return t.forEach((u,f)=>{var g;if(u.path===""||!((g=u.path)!=null&&g.includes("?")))c(u,f);else for(let h of dx(u.path))c(u,f,!0,h)}),n}function dx(t){let n=t.split("/");if(n.length===0)return[];let[r,...s]=n,i=r.endsWith("?"),c=r.replace(/\?$/,"");if(s.length===0)return i?[c,""]:[c];let u=dx(s.join("/")),f=[];return f.push(...u.map(g=>g===""?c:[c,g].join("/"))),i&&f.push(...u),f.map(g=>t.startsWith("/")&&g===""?"/":g)}function _C(t){t.sort((n,r)=>n.score!==r.score?r.score-n.score:kC(n.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}var CC=/^:[\w-]+$/,NC=3,AC=2,RC=1,TC=10,jC=-2,hb=t=>t==="*";function OC(t,n){let r=t.split("/"),s=r.length;return r.some(hb)&&(s+=jC),n&&(s+=AC),r.filter(i=>!hb(i)).reduce((i,c)=>i+(CC.test(c)?NC:c===""?RC:TC),s)}function kC(t,n){return t.length===n.length&&t.slice(0,-1).every((s,i)=>s===n[i])?t[t.length-1]-n[n.length-1]:0}function MC(t,n,r=!1){let{routesMeta:s}=t,i={},c="/",u=[];for(let f=0;f{if(v==="*"){let E=f[w]||"";u=c.slice(0,c.length-E.length).replace(/(.)\/+$/,"$1")}const N=f[w];return y&&!N?h[v]=void 0:h[v]=(N||"").replace(/%2F/g,"/"),h},{}),pathname:c,pathnameBase:u,pattern:t}}function DC(t,n=!1,r=!0){da(t==="*"||!t.endsWith("*")||t.endsWith("/*"),`Route path "${t}" will be treated as if it were "${t.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${t.replace(/\*$/,"/*")}".`);let s=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(u,f,g)=>(s.push({paramName:f,isOptional:g!=null}),g?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return t.endsWith("*")?(s.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,n?void 0:"i"),s]}function zC(t){try{return t.split("/").map(n=>decodeURIComponent(n).replace(/\//g,"%2F")).join("/")}catch(n){return da(!1,`The URL path "${t}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${n}).`),t}}function ar(t,n){if(n==="/")return t;if(!t.toLowerCase().startsWith(n.toLowerCase()))return null;let r=n.endsWith("/")?n.length-1:n.length,s=t.charAt(r);return s&&s!=="/"?null:t.slice(r)||"/"}function LC(t,n="/"){let{pathname:r,search:s="",hash:i=""}=typeof t=="string"?Bo(t):t;return{pathname:r?r.startsWith("/")?r:UC(r,n):n,search:HC(s),hash:VC(i)}}function UC(t,n){let r=n.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?r.length>1&&r.pop():i!=="."&&r.push(i)}),r.length>1?r.join("/"):"/"}function fm(t,n,r,s){return`Cannot include a '${t}' character in a manually specified \`to.${n}\` field [${JSON.stringify(s)}]. Please separate it out to the \`to.${r}\` field. Alternatively you may provide the full path as a string in and the router will parse it for you.`}function BC(t){return t.filter((n,r)=>r===0||n.route.path&&n.route.path.length>0)}function hh(t){let n=BC(t);return n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase)}function ph(t,n,r,s=!1){let i;typeof t=="string"?i=Bo(t):(i={...t},Ct(!i.pathname||!i.pathname.includes("?"),fm("?","pathname","search",i)),Ct(!i.pathname||!i.pathname.includes("#"),fm("#","pathname","hash",i)),Ct(!i.search||!i.search.includes("#"),fm("#","search","hash",i)));let c=t===""||i.pathname==="",u=c?"/":i.pathname,f;if(u==null)f=r;else{let y=n.length-1;if(!s&&u.startsWith("..")){let w=u.split("/");for(;w[0]==="..";)w.shift(),y-=1;i.pathname=w.join("/")}f=y>=0?n[y]:"/"}let g=LC(i,f),h=u&&u!=="/"&&u.endsWith("/"),v=(c||u===".")&&r.endsWith("/");return!g.pathname.endsWith("/")&&(h||v)&&(g.pathname+="/"),g}var nr=t=>t.join("/").replace(/\/\/+/g,"/"),PC=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),HC=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,VC=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function IC(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var fx=["POST","PUT","PATCH","DELETE"];new Set(fx);var qC=["GET",...fx];new Set(qC);var Po=b.createContext(null);Po.displayName="DataRouter";var Cu=b.createContext(null);Cu.displayName="DataRouterState";b.createContext(!1);var mx=b.createContext({isTransitioning:!1});mx.displayName="ViewTransition";var FC=b.createContext(new Map);FC.displayName="Fetchers";var $C=b.createContext(null);$C.displayName="Await";var ha=b.createContext(null);ha.displayName="Navigation";var il=b.createContext(null);il.displayName="Location";var aa=b.createContext({outlet:null,matches:[],isDataRoute:!1});aa.displayName="Route";var gh=b.createContext(null);gh.displayName="RouteError";function GC(t,{relative:n}={}){Ct(Ho(),"useHref() may be used only in the context of a component.");let{basename:r,navigator:s}=b.useContext(ha),{hash:i,pathname:c,search:u}=ll(t,{relative:n}),f=c;return r!=="/"&&(f=c==="/"?r:nr([r,c])),s.createHref({pathname:f,search:u,hash:i})}function Ho(){return b.useContext(il)!=null}function Yr(){return Ct(Ho(),"useLocation() may be used only in the context of a component."),b.useContext(il).location}var hx="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function px(t){b.useContext(ha).static||b.useLayoutEffect(t)}function Vo(){let{isDataRoute:t}=b.useContext(aa);return t?l2():YC()}function YC(){Ct(Ho(),"useNavigate() may be used only in the context of a component.");let t=b.useContext(Po),{basename:n,navigator:r}=b.useContext(ha),{matches:s}=b.useContext(aa),{pathname:i}=Yr(),c=JSON.stringify(hh(s)),u=b.useRef(!1);return px(()=>{u.current=!0}),b.useCallback((g,h={})=>{if(da(u.current,hx),!u.current)return;if(typeof g=="number"){r.go(g);return}let v=ph(g,JSON.parse(c),i,h.relative==="path");t==null&&n!=="/"&&(v.pathname=v.pathname==="/"?n:nr([n,v.pathname])),(h.replace?r.replace:r.push)(v,h.state,h)},[n,r,c,i,t])}var ZC=b.createContext(null);function XC(t){let n=b.useContext(aa).outlet;return b.useMemo(()=>n&&b.createElement(ZC.Provider,{value:t},n),[n,t])}function KC(){let{matches:t}=b.useContext(aa),n=t[t.length-1];return n?n.params:{}}function ll(t,{relative:n}={}){let{matches:r}=b.useContext(aa),{pathname:s}=Yr(),i=JSON.stringify(hh(r));return b.useMemo(()=>ph(t,JSON.parse(i),s,n==="path"),[t,i,s,n])}function QC(t,n){return gx(t,n)}function gx(t,n,r,s,i){var O;Ct(Ho(),"useRoutes() may be used only in the context of a component.");let{navigator:c}=b.useContext(ha),{matches:u}=b.useContext(aa),f=u[u.length-1],g=f?f.params:{},h=f?f.pathname:"/",v=f?f.pathnameBase:"/",y=f&&f.route;{let R=y&&y.path||"";yx(h,!y||R.endsWith("*")||R.endsWith("*?"),`You rendered descendant (or called \`useRoutes()\`) at "${h}" (under ) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. + +Please change the parent to .`)}let w=Yr(),N;if(n){let R=typeof n=="string"?Bo(n):n;Ct(v==="/"||((O=R.pathname)==null?void 0:O.startsWith(v)),`When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${v}" but pathname "${R.pathname}" was given in the \`location\` prop.`),N=R}else N=w;let E=N.pathname||"/",S=E;if(v!=="/"){let R=v.replace(/^\//,"").split("/");S="/"+E.replace(/^\//,"").split("/").slice(R.length).join("/")}let C=cx(t,{pathname:S});da(y||C!=null,`No routes matched location "${N.pathname}${N.search}${N.hash}" `),da(C==null||C[C.length-1].route.element!==void 0||C[C.length-1].route.Component!==void 0||C[C.length-1].route.lazy!==void 0,`Matched leaf route at location "${N.pathname}${N.search}${N.hash}" does not have an element or Component. This means it will render an with a null value by default resulting in an "empty" page.`);let A=n2(C&&C.map(R=>Object.assign({},R,{params:Object.assign({},g,R.params),pathname:nr([v,c.encodeLocation?c.encodeLocation(R.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?v:nr([v,c.encodeLocation?c.encodeLocation(R.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathnameBase])})),u,r,s,i);return n&&A?b.createElement(il.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...N},navigationType:"POP"}},A):A}function WC(){let t=i2(),n=IC(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,s="rgba(200,200,200, 0.5)",i={padding:"0.5rem",backgroundColor:s},c={padding:"2px 4px",backgroundColor:s},u=null;return console.error("Error handled by React Router default ErrorBoundary:",t),u=b.createElement(b.Fragment,null,b.createElement("p",null,"💿 Hey developer 👋"),b.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",b.createElement("code",{style:c},"ErrorBoundary")," or"," ",b.createElement("code",{style:c},"errorElement")," prop on your route.")),b.createElement(b.Fragment,null,b.createElement("h2",null,"Unexpected Application Error!"),b.createElement("h3",{style:{fontStyle:"italic"}},n),r?b.createElement("pre",{style:i},r):null,u)}var JC=b.createElement(WC,null),e2=class extends b.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){this.props.unstable_onError?this.props.unstable_onError(t,n):console.error("React Router caught the following error during render",t)}render(){return this.state.error!==void 0?b.createElement(aa.Provider,{value:this.props.routeContext},b.createElement(gh.Provider,{value:this.state.error,children:this.props.component})):this.props.children}};function t2({routeContext:t,match:n,children:r}){let s=b.useContext(Po);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),b.createElement(aa.Provider,{value:t},r)}function n2(t,n=[],r=null,s=null,i=null){if(t==null){if(!r)return null;if(r.errors)t=r.matches;else if(n.length===0&&!r.initialized&&r.matches.length>0)t=r.matches;else return null}let c=t,u=r==null?void 0:r.errors;if(u!=null){let h=c.findIndex(v=>v.route.id&&(u==null?void 0:u[v.route.id])!==void 0);Ct(h>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(u).join(",")}`),c=c.slice(0,Math.min(c.length,h+1))}let f=!1,g=-1;if(r)for(let h=0;h=0?c=c.slice(0,g+1):c=[c[0]];break}}}return c.reduceRight((h,v,y)=>{let w,N=!1,E=null,S=null;r&&(w=u&&v.route.id?u[v.route.id]:void 0,E=v.route.errorElement||JC,f&&(g<0&&y===0?(yx("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),N=!0,S=null):g===y&&(N=!0,S=v.route.hydrateFallbackElement||null)));let C=n.concat(c.slice(0,y+1)),A=()=>{let O;return w?O=E:N?O=S:v.route.Component?O=b.createElement(v.route.Component,null):v.route.element?O=v.route.element:O=h,b.createElement(t2,{match:v,routeContext:{outlet:h,matches:C,isDataRoute:r!=null},children:O})};return r&&(v.route.ErrorBoundary||v.route.errorElement||y===0)?b.createElement(e2,{location:r.location,revalidation:r.revalidation,component:E,error:w,children:A(),routeContext:{outlet:null,matches:C,isDataRoute:!0},unstable_onError:s}):A()},null)}function yh(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function a2(t){let n=b.useContext(Po);return Ct(n,yh(t)),n}function r2(t){let n=b.useContext(Cu);return Ct(n,yh(t)),n}function s2(t){let n=b.useContext(aa);return Ct(n,yh(t)),n}function vh(t){let n=s2(t),r=n.matches[n.matches.length-1];return Ct(r.route.id,`${t} can only be used on routes that contain a unique "id"`),r.route.id}function o2(){return vh("useRouteId")}function i2(){var s;let t=b.useContext(gh),n=r2("useRouteError"),r=vh("useRouteError");return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function l2(){let{router:t}=a2("useNavigate"),n=vh("useNavigate"),r=b.useRef(!1);return px(()=>{r.current=!0}),b.useCallback(async(i,c={})=>{da(r.current,hx),r.current&&(typeof i=="number"?t.navigate(i):await t.navigate(i,{fromRouteId:n,...c}))},[t,n])}var pb={};function yx(t,n,r){!n&&!pb[t]&&(pb[t]=!0,da(!1,r))}b.memo(c2);function c2({routes:t,future:n,state:r,unstable_onError:s}){return gx(t,void 0,r,s,n)}function mm({to:t,replace:n,state:r,relative:s}){Ct(Ho()," may be used only in the context of a component.");let{static:i}=b.useContext(ha);da(!i," must not be used on the initial render in a . This is a no-op, but you should modify your code so the is only ever rendered in response to some user interaction or state change.");let{matches:c}=b.useContext(aa),{pathname:u}=Yr(),f=Vo(),g=ph(t,hh(c),u,s==="path"),h=JSON.stringify(g);return b.useEffect(()=>{f(JSON.parse(h),{replace:n,state:r,relative:s})},[f,h,s,n,r]),null}function u2(t){return XC(t.context)}function ta(t){Ct(!1,"A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .")}function d2({basename:t="/",children:n=null,location:r,navigationType:s="POP",navigator:i,static:c=!1}){Ct(!Ho(),"You cannot render a inside another . You should never have more than one in your app.");let u=t.replace(/^\/*/,"/"),f=b.useMemo(()=>({basename:u,navigator:i,static:c,future:{}}),[u,i,c]);typeof r=="string"&&(r=Bo(r));let{pathname:g="/",search:h="",hash:v="",state:y=null,key:w="default"}=r,N=b.useMemo(()=>{let E=ar(g,u);return E==null?null:{location:{pathname:E,search:h,hash:v,state:y,key:w},navigationType:s}},[u,g,h,v,y,w,s]);return da(N!=null,` is not able to match the URL "${g}${h}${v}" because it does not start with the basename, so the won't render anything.`),N==null?null:b.createElement(ha.Provider,{value:f},b.createElement(il.Provider,{children:n,value:N}))}function f2({children:t,location:n}){return QC(Bm(t),n)}function Bm(t,n=[]){let r=[];return b.Children.forEach(t,(s,i)=>{if(!b.isValidElement(s))return;let c=[...n,i];if(s.type===b.Fragment){r.push.apply(r,Bm(s.props.children,c));return}Ct(s.type===ta,`[${typeof s.type=="string"?s.type:s.type.name}] is not a component. All component children of must be a or `),Ct(!s.props.index||!s.props.children,"An index route cannot have child routes.");let u={id:s.props.id||c.join("-"),caseSensitive:s.props.caseSensitive,element:s.props.element,Component:s.props.Component,index:s.props.index,path:s.props.path,middleware:s.props.middleware,loader:s.props.loader,action:s.props.action,hydrateFallbackElement:s.props.hydrateFallbackElement,HydrateFallback:s.props.HydrateFallback,errorElement:s.props.errorElement,ErrorBoundary:s.props.ErrorBoundary,hasErrorBoundary:s.props.hasErrorBoundary===!0||s.props.ErrorBoundary!=null||s.props.errorElement!=null,shouldRevalidate:s.props.shouldRevalidate,handle:s.props.handle,lazy:s.props.lazy};s.props.children&&(u.children=Bm(s.props.children,c)),r.push(u)}),r}var Fc="get",$c="application/x-www-form-urlencoded";function Nu(t){return t!=null&&typeof t.tagName=="string"}function m2(t){return Nu(t)&&t.tagName.toLowerCase()==="button"}function h2(t){return Nu(t)&&t.tagName.toLowerCase()==="form"}function p2(t){return Nu(t)&&t.tagName.toLowerCase()==="input"}function g2(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function y2(t,n){return t.button===0&&(!n||n==="_self")&&!g2(t)}var jc=null;function v2(){if(jc===null)try{new FormData(document.createElement("form"),0),jc=!1}catch{jc=!0}return jc}var b2=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function hm(t){return t!=null&&!b2.has(t)?(da(!1,`"${t}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${$c}"`),null):t}function x2(t,n){let r,s,i,c,u;if(h2(t)){let f=t.getAttribute("action");s=f?ar(f,n):null,r=t.getAttribute("method")||Fc,i=hm(t.getAttribute("enctype"))||$c,c=new FormData(t)}else if(m2(t)||p2(t)&&(t.type==="submit"||t.type==="image")){let f=t.form;if(f==null)throw new Error('Cannot submit a