# 📋 SPECIFICATIONS - desk-moloni

## 🎯 PROJECT OVERVIEW
**Integração Bidirecional DeskCRM ↔ Moloni**

Sistema de sincronização automática entre DeskCRM (Customer Relationship Management) e Moloni (Sistema de Faturação) para automatizar processos financeiros e melhorar eficiência operacional.

## 🏗️ ARCHITECTURE

### Core Components
```php
DeskMoloniIntegration
├── APIConnectors/
│   ├── DeskCRMConnector     # DeskCRM API integration
│   └── MoloniConnector      # Moloni API integration
├── DataMappers/
│   ├── CustomerMapper       # Customer field mappings
│   ├── InvoiceMapper        # Invoice field mappings  
│   └── PaymentMapper        # Payment field mappings
├── SyncEngines/
│   ├── CustomerSyncEngine   # Customer synchronization
│   ├── InvoiceSyncEngine    # Invoice synchronization
│   └── PaymentSyncEngine    # Payment synchronization
└── Utils/
    ├── Logger               # Comprehensive logging
    ├── Validator            # Data validation
    └── ConfigManager        # Configuration management
```

## 📡 API INTEGRATIONS

### DeskCRM API v3
```php
Endpoint: https://desk.descomplicar.pt/api/
Authentication: API Key + Bearer Token
Rate Limit: 1000 requests/hour

Entities:
- Customers (GET, POST, PUT)
- Invoices (GET, POST, PUT) 
- Payments (GET, POST)
- Projects (GET)
```

### Moloni API
```php
Endpoint: https://api.moloni.pt/v1/
Authentication: OAuth 2.0
Rate Limit: 10000 requests/day

Entities:
- Clients (GET, POST, PUT, DELETE)
- Documents (GET, POST, PUT)
- Products (GET, POST, PUT)
- Payments (GET, POST)
```

## 🔄 SYNCHRONIZATION FLOWS

### 1. Customer Sync (DeskCRM → Moloni)
```php
Trigger: New customer created in DeskCRM
Process:
1. Fetch customer data from DeskCRM
2. Map fields to Moloni format
3. Validate required fields
4. Create/Update client in Moloni
5. Store mapping in sync_mappings table
6. Log operation result
```

### 2. Invoice Import (Moloni → DeskCRM)
```php  
Trigger: New invoice issued in Moloni
Process:
1. Fetch invoice data from Moloni
2. Identify corresponding DeskCRM customer
3. Map invoice fields to DeskCRM format
4. Create invoice record in DeskCRM
5. Update customer financial data
6. Log operation result
```

### 3. Payment Reconciliation (Bidirectional)
```php
Trigger: Payment recorded in either system
Process:
1. Fetch payment data from source system
2. Find matching invoice in target system  
3. Update payment status
4. Reconcile balances
5. Generate reconciliation report
```

## 💾 DATABASE SCHEMA

### Core Tables
```sql
-- Sync mappings between systems
sync_mappings (
    id INT PRIMARY KEY AUTO_INCREMENT,
    deskcrm_type VARCHAR(50),     # customer, invoice, payment
    deskcrm_id VARCHAR(50),       # DeskCRM entity ID
    moloni_type VARCHAR(50),      # client, document, payment
    moloni_id VARCHAR(50),        # Moloni entity ID
    sync_status ENUM('synced', 'pending', 'failed'),
    last_sync TIMESTAMP,
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);

-- Sync operations log
sync_operations (
    id INT PRIMARY KEY AUTO_INCREMENT,
    operation_type VARCHAR(50),   # create, update, delete
    entity_type VARCHAR(50),      # customer, invoice, payment
    entity_id VARCHAR(50),        # Entity identifier
    source_system VARCHAR(20),    # deskcrm, moloni
    target_system VARCHAR(20),    # moloni, deskcrm
    status ENUM('success', 'failed', 'pending'),
    error_message TEXT,
    execution_time DECIMAL(10,3), # Execution time in seconds
    created_at TIMESTAMP
);

-- Configuration settings
sync_config (
    id INT PRIMARY KEY AUTO_INCREMENT,
    config_key VARCHAR(100) UNIQUE,
    config_value TEXT,
    description TEXT,
    updated_at TIMESTAMP
);
```

## ⚙️ CONFIGURATION

### Environment Variables
```bash
# DeskCRM Configuration
DESKCRM_API_URL=https://desk.descomplicar.pt/api/
DESKCRM_API_KEY=your_api_key
DESKCRM_BEARER_TOKEN=your_bearer_token

# Moloni Configuration
MOLONI_CLIENT_ID=your_client_id
MOLONI_CLIENT_SECRET=your_client_secret
MOLONI_ACCESS_TOKEN=your_access_token
MOLONI_COMPANY_ID=your_company_id

# Database Configuration
DB_HOST=localhost
DB_NAME=desk_moloni
DB_USER=deskcrm_user
DB_PASS=secure_password

# Sync Configuration
SYNC_BATCH_SIZE=100
SYNC_RATE_LIMIT=50
LOG_LEVEL=INFO
DEBUG_MODE=false
```

## 🎯 FUNCTIONAL REQUIREMENTS

### FR1: Customer Synchronization
- **Priority**: HIGH
- **Description**: Automatic sync of customer data from DeskCRM to Moloni
- **Acceptance Criteria**:
  - New DeskCRM customers appear in Moloni within 5 minutes
  - Customer updates are reflected in both systems
  - Field mappings are configurable
  - Duplicate detection and handling

### FR2: Invoice Management
- **Priority**: HIGH  
- **Description**: Import Moloni invoices into DeskCRM
- **Acceptance Criteria**:
  - Moloni invoices create corresponding DeskCRM records
  - Invoice status updates are synchronized
  - Payment tracking across both systems
  - Tax and financial data accuracy

### FR3: Reporting & Monitoring
- **Priority**: MEDIUM
- **Description**: Comprehensive sync monitoring and reporting
- **Acceptance Criteria**:
  - Real-time sync status dashboard
  - Error reporting and notifications
  - Performance metrics tracking
  - Audit trail maintenance

### FR4: Configuration Management
- **Priority**: MEDIUM
- **Description**: Dynamic configuration of sync parameters
- **Acceptance Criteria**:
  - Web-based configuration interface
  - Field mapping customization
  - Sync frequency settings
  - Error handling preferences

## 🛡️ NON-FUNCTIONAL REQUIREMENTS

### Performance
- **Response Time**: <2 seconds for individual operations
- **Throughput**: 500+ sync operations per day
- **Batch Processing**: 100 records per batch
- **Memory Usage**: <512MB during operation

### Reliability
- **Uptime**: 99.9% availability
- **Error Rate**: <0.5% failed operations
- **Recovery Time**: <5 minutes for service restoration
- **Data Consistency**: 100% accuracy requirement

### Security
- **Authentication**: OAuth 2.0 and API Key based
- **Encryption**: HTTPS for all API communications
- **Data Protection**: GDPR compliant data handling
- **Audit Trail**: Complete operation logging

### Maintainability
- **Code Quality**: PSR-12 compliance
- **Documentation**: 100% PHPDoc coverage
- **Testing**: 80%+ code coverage
- **Modularity**: Component-based architecture

## 🧪 TESTING STRATEGY

### Unit Testing
```php
Tests/Unit/
├── APIConnectors/
├── DataMappers/
├── SyncEngines/
└── Utils/
```

### Integration Testing
```php
Tests/Integration/
├── DeskCRMIntegrationTest
├── MoloniIntegrationTest
└── EndToEndSyncTest
```

### Performance Testing
- Load testing with 1000+ concurrent operations
- Memory leak detection
- API rate limit compliance
- Database performance optimization

## 🚀 DEPLOYMENT STRATEGY

### Development Environment
- Local PHP 8.4+ with MySQL 8.0/MariaDB 10.6+
- PHPUnit 12.3+ with modern attribute syntax
- Docker containers for isolation
- Git-based version control with pre-commit hooks
- Automated testing with coverage reporting

### Production Environment  
- LAMP stack on dedicated server
- SSL certificates for HTTPS
- Database backups and replication
- Application monitoring and logging

### CI/CD Pipeline
```yaml
Stages:
1. Code Quality Check (PHPStan level 8, PSR-12)
2. Unit Tests (PHPUnit 12.3+ with PHP 8.4 attributes)
3. Integration Tests (MockWebServer framework)
4. Security Scan (OWASP + vulnerability analysis)
5. Performance Tests (Memory profiling + load testing)
6. Coverage Report (80%+ requirement)
7. Deployment to Staging
8. Production Deployment (manual approval)
```

---
**Version**: 1.1 | **Last Update**: 2025-09-12 23:30 | **Status**: ✅ PHP 8.4 Ready