# KiviCare API - Quickstart Guide **Plugin WordPress completo para gestão de clínicas médicas via REST API** --- ## 🚀 INSTALAÇÃO RÁPIDA ### 1. Pré-requisitos - WordPress 6.0+ - PHP 8.1+ - MySQL 5.7+ / MariaDB 10.3+ - Plugin KiviCare base instalado e ativo - Memoria: 512MB+ (recomendado: 1GB+) ### 2. Instalação ```bash # 1. Upload dos ficheiros wp-content/plugins/kivicare-api/ # 2. Ativar o plugin wp plugin activate kivicare-api # 3. Verificar dependências wp plugin list --field=name --status=active | grep kivicare ``` ### 3. Configuração Inicial ```bash # Configurar permissões (wp-config.php) define('KIVICARE_API_VERSION', '1.0.0'); define('KIVICARE_API_DEBUG', true); // Apenas desenvolvimento define('KIVICARE_API_CACHE_TTL', 3600); define('KIVICARE_JWT_SECRET', 'your-secure-secret-key-here'); ``` --- ## ⚡ TESTE RÁPIDO DE FUNCIONAMENTO ### 1. Verificação do Sistema ```bash # Teste de saúde da API curl -X GET http://yoursite.com/wp-json/kivicare/v1/system/health # Resposta esperada: { "success": true, "message": "API is healthy", "data": { "status": "operational", "version": "1.0.0", "database": "connected", "cache": "active" } } ``` ### 2. Autenticação ```bash # Login e obtenção de token JWT curl -X POST http://yoursite.com/wp-json/kivicare/v1/auth/login \ -H "Content-Type: application/json" \ -d '{ "username": "admin", "password": "your_password" }' # Resposta esperada: { "success": true, "message": "Login successful", "data": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", "user": { "id": 1, "user_type": "admin", "full_name": "Administrator" } } } ``` ### 3. Teste de Endpoints Principais ```bash # Listar clínicas (usar token obtido) curl -X GET http://yoursite.com/wp-json/kivicare/v1/clinics \ -H "Authorization: Bearer YOUR_TOKEN_HERE" # Listar pacientes curl -X GET http://yoursite.com/wp-json/kivicare/v1/patients \ -H "Authorization: Bearer YOUR_TOKEN_HERE" # Listar médicos curl -X GET http://yoursite.com/wp-json/kivicare/v1/doctors \ -H "Authorization: Bearer YOUR_TOKEN_HERE" ``` --- ## 📊 VALIDAÇÃO COMPLETA DO SISTEMA ### Executar Suite de Testes Completa ```php // No WordPress Admin ou via WP-CLI $test_results = \KiviCare_API\Testing\Unit_Test_Suite::run_all_tests(array( 'verbose' => true, 'timeout' => 60 )); print_r($test_results['summary']); ``` ### Verificação Manual dos Componentes #### ✅ **1. Autenticação & Segurança** ```bash # Teste sem token (deve falhar) curl -X GET http://yoursite.com/wp-json/kivicare/v1/patients # Expected: 401 Unauthorized # Teste com token inválido (deve falhar) curl -X GET http://yoursite.com/wp-json/kivicare/v1/patients \ -H "Authorization: Bearer invalid_token" # Expected: 401 Invalid token # Teste com token válido (deve passar) curl -X GET http://yoursite.com/wp-json/kivicare/v1/patients \ -H "Authorization: Bearer VALID_TOKEN" # Expected: 200 OK with data ``` #### ✅ **2. CRUD Operations** ```bash # Criar paciente curl -X POST http://yoursite.com/wp-json/kivicare/v1/patients \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "first_name": "João", "last_name": "Silva", "user_email": "joao@example.com", "clinic_id": 1 }' # Obter paciente por ID curl -X GET http://yoursite.com/wp-json/kivicare/v1/patients/123 \ -H "Authorization: Bearer TOKEN" # Atualizar paciente curl -X PUT http://yoursite.com/wp-json/kivicare/v1/patients/123 \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{"first_name": "João Pedro"}' ``` #### ✅ **3. Agendamentos & Consultas** ```bash # Criar agendamento curl -X POST http://yoursite.com/wp-json/kivicare/v1/appointments \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "patient_id": 123, "doctor_id": 456, "clinic_id": 1, "appointment_start_date": "2025-01-15", "appointment_start_time": "14:30:00" }' # Verificar slots disponíveis curl -X GET "http://yoursite.com/wp-json/kivicare/v1/appointments/available-slots?doctor_id=456&date=2025-01-15" \ -H "Authorization: Bearer TOKEN" ``` #### ✅ **4. Consultas Médicas & Prescrições** ```bash # Criar encounter curl -X POST http://yoursite.com/wp-json/kivicare/v1/encounters \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "patient_id": 123, "doctor_id": 456, "clinic_id": 1, "description": "Consulta de rotina" }' # Adicionar prescrição curl -X POST http://yoursite.com/wp-json/kivicare/v1/prescriptions \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "encounter_id": 789, "patient_id": 123, "medication_name": "Paracetamol 500mg", "frequency": "8/8h", "duration": "7 dias" }' ``` #### ✅ **5. Faturação** ```bash # Criar fatura curl -X POST http://yoursite.com/wp-json/kivicare/v1/bills \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "encounter_id": 789, "clinic_id": 1, "title": "Consulta Médica", "total_amount": 50.00 }' ``` --- ## 🔧 TROUBLESHOOTING ### Problemas Comuns #### ❌ **Plugin não ativa** ```bash # Verificar dependências wp plugin list --status=must-use,active | grep kivicare # Verificar logs tail -f /wp-content/debug.log | grep kivicare ``` #### ❌ **Erro 500 em endpoints** ```bash # Verificar permissões de ficheiros find /wp-content/plugins/kivicare-api -type f -exec chmod 644 {} \; find /wp-content/plugins/kivicare-api -type d -exec chmod 755 {} \; # Verificar memory limit wp config get WP_MEMORY_LIMIT ``` #### ❌ **Problemas de autenticação** ```bash # Verificar .htaccess (Apache) # Adicionar se necessário: SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 # Verificar configuração Nginx # location ~ \.php$ { # fastcgi_param HTTP_AUTHORIZATION $http_authorization; # } ``` #### ❌ **Database errors** ```bash # Verificar tabelas KiviCare wp db query "SHOW TABLES LIKE '%kc_%'" # Verificar conexões wp db check ``` --- ## 📈 MONITORIZAÇÃO & PERFORMANCE ### Métricas em Tempo Real ```bash # Performance da API curl -X GET http://yoursite.com/wp-json/kivicare/v1/system/performance \ -H "Authorization: Bearer TOKEN" # Estatísticas de cache curl -X GET http://yoursite.com/wp-json/kivicare/v1/system/cache-stats \ -H "Authorization: Bearer TOKEN" ``` ### Logs Importantes ```bash # Logs da API tail -f /wp-content/uploads/kivicare-api-logs/api-requests.log # Logs de performance tail -f /wp-content/uploads/kivicare-api-logs/performance.log # Logs de segurança tail -f /wp-content/uploads/kivicare-api-logs/security.log ``` --- ## 🎯 ENDPOINTS DISPONÍVEIS ### **Authentication** - `POST /auth/login` - Login utilizador - `POST /auth/refresh` - Refresh token - `POST /auth/logout` - Logout ### **Clínicas** - `GET /clinics` - Listar clínicas - `POST /clinics` - Criar clínica - `GET /clinics/{id}` - Obter clínica - `PUT /clinics/{id}` - Atualizar clínica ### **Pacientes** - `GET /patients` - Listar pacientes - `POST /patients` - Criar paciente - `GET /patients/{id}` - Obter paciente - `PUT /patients/{id}` - Atualizar paciente - `GET /patients/{id}/history` - Histórico médico ### **Médicos** - `GET /doctors` - Listar médicos - `GET /doctors/{id}` - Obter médico - `GET /doctors/{id}/schedule` - Horário do médico - `GET /doctors/{id}/appointments` - Agendamentos do médico ### **Agendamentos** - `GET /appointments` - Listar agendamentos - `POST /appointments` - Criar agendamento - `GET /appointments/{id}` - Obter agendamento - `PUT /appointments/{id}` - Atualizar agendamento - `DELETE /appointments/{id}` - Cancelar agendamento - `GET /appointments/available-slots` - Slots disponíveis ### **Consultas Médicas** - `GET /encounters` - Listar encounters - `POST /encounters` - Criar encounter - `GET /encounters/{id}` - Obter encounter - `PUT /encounters/{id}` - Atualizar encounter ### **Prescrições** - `GET /prescriptions` - Listar prescrições - `POST /prescriptions` - Criar prescrição - `PUT /prescriptions/{id}` - Atualizar prescrição - `GET /encounters/{id}/prescriptions` - Prescrições do encounter ### **Faturação** - `GET /bills` - Listar faturas - `POST /bills` - Criar fatura - `GET /bills/{id}` - Obter fatura - `PUT /bills/{id}` - Atualizar fatura - `POST /bills/{id}/payment` - Registar pagamento ### **Relatórios** - `GET /reports/appointments` - Relatório de agendamentos - `GET /reports/revenue` - Relatório de receita - `GET /reports/patients` - Relatório de pacientes - `GET /reports/doctors` - Relatório de médicos ### **Sistema** - `GET /system/health` - Estado da API - `GET /system/version` - Versão da API - `GET /system/performance` - Métricas de performance --- ## 📞 SUPORTE ### Logs & Debug ```bash # Ativar modo debug (wp-config.php) define('KIVICARE_API_DEBUG', true); define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); ``` ### Contactos - **Desenvolvimento Técnico**: Descomplicar® Crescimento Digital - **Website**: https://descomplicar.pt - **Documentação Completa**: Ver SPEC_CARE_API.md --- ## ✅ CHECKLIST FINAL - [ ] Plugin KiviCare base instalado e ativo - [ ] Plugin KiviCare API ativado com sucesso - [ ] Endpoint de saúde responde corretamente - [ ] Autenticação JWT funcional - [ ] Endpoints principais testados - [ ] Logs a funcionar corretamente - [ ] Cache ativo e otimizado - [ ] Testes unitários executados com sucesso - [ ] Monitorização de performance ativa - [ ] Backup da base de dados realizado **🎉 PARABÉNS! A KiviCare API está 100% operacional!** --- *Desenvolvido com ❤️ pela **Descomplicar® Crescimento Digital*** *Sistema completo de gestão de clínicas médicas via REST API*