# KiviCare API - Especificações Técnicas

**Projeto**: KiviCare MCP Integration  
**Versão**: 1.0.0  
**Data**: 2025-01-12  
**Autor**: Descomplicar® Crescimento Digital  
**URL**: https://descomplicar.pt

---

## 🎯 OVERVIEW DO SISTEMA

### Descrição
KiviCare é um sistema completo de gestão de clínicas médicas implementado como plugin WordPress. O sistema gere pacientes, médicos, consultas, prescrições, faturas e relatórios médicos através de uma estrutura de base de dados com 35 tabelas especializadas.

### Funcionalidades Core
- **Gestão de Pacientes**: Registo, histórico médico, consultas
- **Gestão de Médicos**: Perfis, horários, especializações
- **Agendamento**: Consultas, lembretes, integrações (Zoom/Google Meet)
- **Consultas Médicas**: Encounters, prescrições, relatórios
- **Faturação**: Bills, pagamentos, serviços
- **Administração**: Clínicas, utilizadores, configurações

---

## 🏗️ ARQUITETURA DA BASE DE DADOS

### Tabelas Principais (Core)

#### 🏥 **wp_kc_clinics** - Gestão de Clínicas
```sql
- id (bigint, PK)
- name (varchar 191)
- email (varchar 191) 
- telephone_no (varchar 191)
- specialties (longtext)
- address (text)
- city, state, country (varchar 191)
- postal_code (varchar 191)
- status (tinyint)
- clinic_admin_id (bigint)
- clinic_logo, profile_image (bigint)
- extra (longtext)
```

#### 👨‍⚕️ **wp_kc_appointments** - Agendamentos
```sql
- id (bigint, PK)
- appointment_start_date (date)
- appointment_start_time (time)
- appointment_end_date (date)
- appointment_end_time (time)
- visit_type (varchar 191)
- clinic_id (bigint) → FK wp_kc_clinics
- doctor_id (bigint) → FK wp_users
- patient_id (bigint) → FK wp_users  
- description (text)
- status (tinyint)
- created_at (datetime)
- appointment_report (longtext)
```

#### 🩺 **wp_kc_patient_encounters** - Consultas Médicas
```sql
- id (bigint, PK)
- encounter_date (date)
- clinic_id (bigint) → FK wp_kc_clinics
- doctor_id (bigint) → FK wp_users
- patient_id (bigint) → FK wp_users
- appointment_id (bigint) → FK wp_kc_appointments
- description (text)
- status (tinyint)
- added_by (bigint)
- created_at (datetime)
- template_id (bigint)
```

#### 💊 **wp_kc_prescription** - Prescrições
```sql
- id (bigint, PK)
- encounter_id (bigint) → FK wp_kc_patient_encounters
- patient_id (bigint) → FK wp_users
- name (text) - Nome do medicamento
- frequency (varchar 199)
- duration (varchar 199)
- instruction (text)
- added_by (bigint)
- created_at (datetime)
- is_from_template (tinyint)
```

#### 💰 **wp_kc_bills** - Faturação
```sql
- id (bigint, PK)
- encounter_id (bigint) → FK wp_kc_patient_encounters
- appointment_id (bigint) → FK wp_kc_appointments
- title (varchar 191)
- total_amount (varchar 50)
- discount (varchar 50)
- actual_amount (varchar 50)
- status (bigint)
- payment_status (varchar 10)
- created_at (datetime)
- clinic_id (bigint)
```

### Tabelas de Relacionamentos

#### 🔗 **wp_kc_doctor_clinic_mappings**
```sql
- doctor_id → wp_users
- clinic_id → wp_kc_clinics
```

#### 🔗 **wp_kc_patient_clinic_mappings**
```sql
- patient_id → wp_users
- clinic_id → wp_kc_clinics
```

#### 🔗 **wp_kc_appointment_service_mapping**
```sql
- appointment_id → wp_kc_appointments
- service_id → wp_kc_services
```

### Tabelas Especializadas

#### ⚕️ **wp_kc_services** - Serviços Médicos
```sql
- id, type, name, price, status, created_at
```

#### 📋 **wp_kc_medical_history** - Histórico Médico
```sql
- encounter_id, patient_id, type, title, added_by
```

#### 🔧 **wp_kc_custom_fields** - Campos Personalizados
```sql
- name, type, status, created_at
```

#### 📞 **wp_kc_appointment_reminder_mapping** - Lembretes
```sql
- appointment_id, status, created_at
```

#### 🎥 **Integrações Video**
- `wp_kc_appointment_zoom_mappings`
- `wp_kc_appointment_google_meet_mappings`
- `wp_kc_gcal_appointment_mapping`

---

## 🎛️ ENDPOINTS API PROPOSTOS

### **Authentication**
```http
POST /wp-json/kivicare/v1/auth/login
POST /wp-json/kivicare/v1/auth/refresh
POST /wp-json/kivicare/v1/auth/logout
```

### **Clínicas**
```http
GET    /wp-json/kivicare/v1/clinics
POST   /wp-json/kivicare/v1/clinics
GET    /wp-json/kivicare/v1/clinics/{id}
PUT    /wp-json/kivicare/v1/clinics/{id}
DELETE /wp-json/kivicare/v1/clinics/{id}
```

### **Pacientes**
```http
GET    /wp-json/kivicare/v1/patients
POST   /wp-json/kivicare/v1/patients
GET    /wp-json/kivicare/v1/patients/{id}
PUT    /wp-json/kivicare/v1/patients/{id}
GET    /wp-json/kivicare/v1/patients/{id}/history
GET    /wp-json/kivicare/v1/patients/{id}/encounters
GET    /wp-json/kivicare/v1/patients/{id}/prescriptions
```

### **Médicos**
```http
GET    /wp-json/kivicare/v1/doctors
GET    /wp-json/kivicare/v1/doctors/{id}
GET    /wp-json/kivicare/v1/doctors/{id}/schedule
GET    /wp-json/kivicare/v1/doctors/{id}/appointments
PUT    /wp-json/kivicare/v1/doctors/{id}/schedule
```

### **Agendamentos**
```http
GET    /wp-json/kivicare/v1/appointments
POST   /wp-json/kivicare/v1/appointments
GET    /wp-json/kivicare/v1/appointments/{id}
PUT    /wp-json/kivicare/v1/appointments/{id}
DELETE /wp-json/kivicare/v1/appointments/{id}
GET    /wp-json/kivicare/v1/appointments/available-slots
```

### **Consultas Médicas**
```http
GET    /wp-json/kivicare/v1/encounters
POST   /wp-json/kivicare/v1/encounters
GET    /wp-json/kivicare/v1/encounters/{id}
PUT    /wp-json/kivicare/v1/encounters/{id}
GET    /wp-json/kivicare/v1/encounters/{id}/prescriptions
POST   /wp-json/kivicare/v1/encounters/{id}/prescriptions
```

### **Faturação**
```http
GET    /wp-json/kivicare/v1/bills
POST   /wp-json/kivicare/v1/bills
GET    /wp-json/kivicare/v1/bills/{id}
PUT    /wp-json/kivicare/v1/bills/{id}
POST   /wp-json/kivicare/v1/bills/{id}/payment
```

### **Serviços**
```http
GET    /wp-json/kivicare/v1/services
POST   /wp-json/kivicare/v1/services
PUT    /wp-json/kivicare/v1/services/{id}
DELETE /wp-json/kivicare/v1/services/{id}
```

### **Relatórios**
```http
GET /wp-json/kivicare/v1/reports/appointments
GET /wp-json/kivicare/v1/reports/revenue
GET /wp-json/kivicare/v1/reports/patients
GET /wp-json/kivicare/v1/reports/doctors
```

---

## 🔐 SEGURANÇA E AUTENTICAÇÃO

### WordPress Authentication
- **JWT Token** baseado em wp_users
- **Role-based access**: administrator, doctor, patient, receptionist
- **Capability checks** por endpoint
- **Nonce verification** para operações críticas

### Permissions Matrix
```php
'administrator' => ['all_operations'],
'doctor' => ['read_own_patients', 'create_encounters', 'prescriptions'],
'patient' => ['read_own_data', 'book_appointments'],
'receptionist' => ['manage_appointments', 'basic_patient_data']
```

---

## 📊 MODELOS DE DADOS

### Patient Profile
```json
{
  "id": 123,
  "name": "João Silva",
  "email": "joao@email.com",
  "phone": "+351912345678",
  "birth_date": "1985-05-15",
  "gender": "M",
  "address": {
    "street": "Rua da Saúde, 123",
    "city": "Lisboa",
    "postal_code": "1000-001"
  },
  "medical_history": [
    {
      "type": "chronic_disease",
      "title": "Diabetes Tipo 2",
      "date": "2020-01-15"
    }
  ],
  "last_visit": "2024-12-15",
  "clinic_id": 1
}
```

### Appointment
```json
{
  "id": 456,
  "start_date": "2024-12-20",
  "start_time": "14:30:00",
  "end_date": "2024-12-20", 
  "end_time": "15:00:00",
  "visit_type": "consultation",
  "status": "scheduled",
  "patient": {
    "id": 123,
    "name": "João Silva"
  },
  "doctor": {
    "id": 789,
    "name": "Dr. Maria Santos"
  },
  "clinic": {
    "id": 1,
    "name": "Clínica Central"
  },
  "services": ["consultation_general"],
  "notes": "Consulta de rotina"
}
```

### Medical Encounter
```json
{
  "id": 789,
  "encounter_date": "2024-12-20",
  "patient_id": 123,
  "doctor_id": 789,
  "appointment_id": 456,
  "diagnosis": "Gripe comum",
  "symptoms": ["febre", "tosse", "dor de garganta"],
  "prescriptions": [
    {
      "medication": "Paracetamol 500mg",
      "frequency": "8/8h",
      "duration": "7 dias",
      "instructions": "Tomar com água após refeições"
    }
  ],
  "next_visit": "2024-12-27",
  "status": "completed"
}
```

---

## 🚀 IMPLEMENTAÇÃO TÉCNICA

### Plugin WordPress Structure
```
kivicare-api/
├── kivicare-api.php (main plugin file)
├── includes/
│   ├── class-kivicare-api.php
│   ├── class-rest-controller.php
│   └── endpoints/
│       ├── class-clinics-endpoint.php
│       ├── class-patients-endpoint.php
│       ├── class-appointments-endpoint.php
│       ├── class-encounters-endpoint.php
│       └── class-bills-endpoint.php
├── models/
│   ├── class-clinic.php
│   ├── class-patient.php
│   ├── class-appointment.php
│   └── class-encounter.php
└── utils/
    ├── class-auth-helper.php
    ├── class-data-validator.php
    └── class-db-helper.php
```

### Core Classes
```php
class KiviCare_API_Clinics_Endpoint extends WP_REST_Controller {
    protected $namespace = 'kivicare/v1';
    protected $rest_base = 'clinics';
    
    public function register_routes() {
        register_rest_route($this->namespace, '/' . $this->rest_base, [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_items'],
            'permission_callback' => [$this, 'get_items_permissions_check']
        ]);
    }
}
```

### Database Queries Optimization
```php
class KiviCare_DB_Helper {
    public static function get_patient_full_data($patient_id) {
        global $wpdb;
        
        $query = "
            SELECT p.*, pm.clinic_id, c.name as clinic_name
            FROM {$wpdb->users} p
            LEFT JOIN {$wpdb->prefix}kc_patient_clinic_mappings pm ON p.ID = pm.patient_id
            LEFT JOIN {$wpdb->prefix}kc_clinics c ON pm.clinic_id = c.id
            WHERE p.ID = %d
        ";
        
        return $wpdb->get_row($wpdb->prepare($query, $patient_id));
    }
}
```

---

## 🧪 TESTES E VALIDAÇÃO

### Unit Tests
```php
class Test_KiviCare_Appointments extends WP_UnitTestCase {
    public function test_create_appointment() {
        $appointment_data = [
            'patient_id' => 1,
            'doctor_id' => 2,
            'clinic_id' => 1,
            'start_date' => '2024-12-20',
            'start_time' => '14:30:00'
        ];
        
        $result = KiviCare_Appointments::create($appointment_data);
        $this->assertIsInt($result);
        $this->assertGreaterThan(0, $result);
    }
}
```

### API Integration Tests
```bash
# Test Authentication
curl -X POST http://site.local/wp-json/kivicare/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"doctor","password":"password"}'

# Test Get Appointments  
curl -X GET http://site.local/wp-json/kivicare/v1/appointments \
  -H "Authorization: Bearer TOKEN"

# Test Create Appointment
curl -X POST http://site.local/wp-json/kivicare/v1/appointments \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer TOKEN" \
  -d '{"patient_id":1,"doctor_id":2,"start_date":"2024-12-20"}'
```

---

## 📈 PERFORMANCE E ESCALABILIDADE

### Database Indexes
```sql
ALTER TABLE wp_kc_appointments 
ADD INDEX idx_doctor_date (doctor_id, appointment_start_date);

ALTER TABLE wp_kc_patient_encounters 
ADD INDEX idx_patient_date (patient_id, encounter_date);

ALTER TABLE wp_kc_bills 
ADD INDEX idx_clinic_status (clinic_id, status);
```

### Caching Strategy
```php
class KiviCare_Cache {
    public static function get_patient_encounters($patient_id) {
        $cache_key = "patient_encounters_{$patient_id}";
        $encounters = wp_cache_get($cache_key, 'kivicare');
        
        if (false === $encounters) {
            $encounters = self::fetch_from_db($patient_id);
            wp_cache_set($cache_key, $encounters, 'kivicare', 3600);
        }
        
        return $encounters;
    }
}
```

---

## 🔧 CONFIGURAÇÃO E DEPLOYMENT

### Plugin Activation
```php
register_activation_hook(__FILE__, 'kivicare_api_activate');

function kivicare_api_activate() {
    // Verificar se KiviCare plugin está ativo
    if (!is_plugin_active('kivicare-clinic-&-patient-management-system/kivicare-clinic-&-patient-management-system.php')) {
        wp_die('KiviCare Plugin é necessário para ativar a API.');
    }
    
    // Criar capabilities
    $role = get_role('doctor');
    $role->add_cap('manage_kivicare_api');
    
    // Flush rewrite rules
    flush_rewrite_rules();
}
```

### Environment Configuration
```php
// wp-config.php additions
define('KIVICARE_API_VERSION', '1.0.0');
define('KIVICARE_API_DEBUG', false);
define('KIVICARE_API_CACHE_TTL', 3600);
define('KIVICARE_JWT_SECRET', 'your-secret-key');
```

---

## 📋 CHECKLIST DE IMPLEMENTAÇÃO

### Fase 1 - Core API (Semana 1-2)
- [ ] Plugin base e estrutura
- [ ] Authentication endpoints  
- [ ] Clinics CRUD endpoints
- [ ] Patients CRUD endpoints
- [ ] Basic error handling

### Fase 2 - Appointments & Encounters (Semana 3-4)
- [ ] Appointments CRUD endpoints
- [ ] Slot availability logic
- [ ] Patient encounters endpoints
- [ ] Prescription management

### Fase 3 - Billing & Advanced (Semana 5-6)
- [ ] Bills and payments endpoints
- [ ] Services management
- [ ] Reporting endpoints
- [ ] Advanced filtering and search

### Fase 4 - Testing & Documentation (Semana 7-8)
- [ ] Unit tests completos
- [ ] Integration tests
- [ ] API documentation
- [ ] Performance optimization

---

## 🔮 ROADMAP FUTURO

### v1.1 - Integrações
- Sincronização com calendários externos
- Integração com sistemas de pagamento
- Notificações push/email automatizadas

### v1.2 - Analytics  
- Dashboard de métricas médicas
- Relatórios financeiros avançados
- Business intelligence integrado

### v1.3 - Mobile
- App mobile nativo
- Offline synchronization
- Patient portal app

---

**Assinatura**: Descomplicar® Crescimento Digital  
**URL**: https://descomplicar.pt  
**Contacto**: Desenvolvimento técnico especializado

---

*Especificações técnicas detalhadas para implementação de API KiviCare com arquitetura WordPress robusta e escalável.*