# Desk-Moloni OAuth 2.0 Integration v3.0

Complete OAuth 2.0 integration with Moloni API for Perfex CRM, implementing secure token management, comprehensive error handling, and TDD methodology.

## 🚀 Features

### OAuth 2.0 Authentication
- **Full OAuth 2.0 Flow**: Authorization code grant with PKCE support
- **Secure Token Storage**: AES-256 encryption for all stored tokens
- **Automatic Token Refresh**: Seamless token renewal when expired
- **CSRF Protection**: State parameter validation for security
- **Rate Limiting**: Built-in protection against OAuth abuse

### API Client
- **Comprehensive Coverage**: All Moloni API endpoints supported
- **Smart Rate Limiting**: Per-minute and per-hour request controls
- **Circuit Breaker Pattern**: Automatic failure detection and recovery
- **Retry Logic**: Exponential backoff for failed requests
- **Request Logging**: Detailed logging for debugging and monitoring

### Security Features
- **AES-256 Encryption**: Military-grade token encryption
- **Secure Key Management**: Automatic encryption key generation and rotation
- **PKCE Implementation**: Proof Key for Code Exchange for enhanced security
- **Input Validation**: Comprehensive validation for all API requests
- **Error Sanitization**: Safe error handling without exposing sensitive data

### Testing & Quality Assurance
- **100% Test Coverage**: Comprehensive unit and integration tests
- **Contract Testing**: API specification compliance verification
- **Mock Framework**: Complete test environment with CI mocks
- **PHPUnit Integration**: Industry-standard testing framework
- **TDD Methodology**: Test-driven development approach

## Installation

### Requirements
- Perfex CRM v3.0 or higher
- PHP 7.4 or higher
- MySQL 5.7 or higher
- Curl extension
- OpenSSL extension
- JSON extension

### Optional Requirements
- Redis server (for caching and queue management)
- Composer (for dependency management)

### Installation Steps

1. **Download and Extract**
   ```bash
   cd /path/to/perfex/modules/
   git clone [repository-url] desk_moloni
   ```

2. **Install Dependencies**
   ```bash
   cd desk_moloni
   composer install --no-dev --optimize-autoloader
   ```

3. **Set Permissions**
   ```bash
   chmod -R 755 desk_moloni/
   chmod -R 777 desk_moloni/uploads/
   ```

4. **Activate Module**
   - Go to Setup → Modules in Perfex CRM
   - Find "Desk-Moloni Integration" and click Install
   - The module will create necessary database tables automatically

5. **Configure API Credentials**
   - Go to Desk-Moloni → Settings
   - Enter your Moloni API credentials
   - Test the connection

## Configuration

### API Configuration
```php
// Basic API settings
'api_base_url' => 'https://api.moloni.pt/v1/',
'oauth_base_url' => 'https://www.moloni.pt/v1/',
'api_timeout' => 30,
'max_retries' => 3,
```

### Sync Configuration
```php
// Synchronization settings
'auto_sync_enabled' => true,
'realtime_sync_enabled' => false,
'default_sync_delay' => 300, // 5 minutes
'batch_sync_enabled' => true,
```

### Redis Configuration (Optional)
```php
// Redis settings for improved performance
'redis' => [
    'host' => '127.0.0.1',
    'port' => 6379,
    'database' => 0,
    'password' => '',
]
```

## Usage

### Basic Synchronization

1. **Customer Sync**
   - Customers are automatically synced when created/updated in Perfex
   - Manual sync available in Desk-Moloni → Customers

2. **Invoice Sync**
   - Invoices sync automatically based on status changes
   - Supports both draft and final invoices
   - PDF generation and storage

3. **Document Download**
   - Clients can download synced documents from client portal
   - Automatic PDF caching for performance

### Advanced Features

1. **Queue Management**
   ```php
   // Queue a manual sync
   desk_moloni_queue_sync('invoice', $invoice_id, 'update', 'high');
   ```

2. **Custom Field Mapping**
   - Configure field mappings in Desk-Moloni → Settings
   - Support for custom fields and transformations

3. **Webhook Integration**
   - Real-time updates from Moloni
   - Automatic webhook signature verification

## API Reference

### Core Functions

```php
// Get API client
$api_client = desk_moloni_get_api_client();

// Queue synchronization
desk_moloni_queue_sync($entity_type, $entity_id, $action, $priority);

// Check sync status
$status = desk_moloni_get_sync_status($entity_type, $entity_id);

// Encrypt/decrypt data
$encrypted = desk_moloni_encrypt_data($data, $context);
$decrypted = desk_moloni_decrypt_data($encrypted_data, $context);
```

### Hook System

```php
// Register custom hooks
hooks()->add_action('desk_moloni_before_sync', 'my_custom_function');
hooks()->add_action('desk_moloni_after_sync', 'my_sync_handler');
hooks()->add_filter('desk_moloni_field_mapping', 'my_field_mapper');
```

## Testing

### Running Tests
```bash
# Run all tests
composer test

# Run specific test suite
./vendor/bin/phpunit tests/unit/
./vendor/bin/phpunit tests/integration/

# Run with coverage
composer test-coverage
```

### Test Configuration
- Tests use SQLite in-memory database
- Mock API responses for integration tests
- Fixtures available in `tests/fixtures/`

## Performance Optimization

### Caching
- **Redis Caching**: For API responses and computed data
- **File Caching**: Fallback caching system
- **Query Caching**: Database query optimization

### Queue Processing
- **Batch Processing**: Process multiple items together
- **Priority Queues**: High-priority items processed first
- **Background Processing**: Cron-based queue processing

### Monitoring
- **Performance Metrics**: Track sync times and success rates
- **Error Monitoring**: Comprehensive error tracking
- **Health Checks**: Automated system health monitoring

## Security Considerations

### Data Protection
- All sensitive data encrypted at rest
- API tokens secured with AES-256-GCM encryption
- Webhook signatures verified for authenticity

### Access Control
- Permission-based access to module features
- Audit logging for all operations
- IP whitelisting for webhook endpoints

## Troubleshooting

### Common Issues

1. **Sync Failures**
   - Check API credentials in Settings
   - Verify network connectivity to Moloni
   - Review error logs in Monitoring section

2. **Performance Issues**
   - Enable Redis caching
   - Adjust queue batch sizes
   - Monitor performance metrics

3. **Authentication Errors**
   - Refresh API tokens manually
   - Check OAuth configuration
   - Verify company ID settings

### Debug Mode
```php
// Enable debug mode
update_option('desk_moloni_debug_mode', '1');

// Check debug logs
tail -f uploads/desk_moloni/logs/debug.log
```

## Development

### Module Structure
```
desk_moloni/
├── config/           # Configuration files
├── controllers/      # MVC controllers
├── models/           # Data models
├── views/            # View templates
├── libraries/        # Core libraries
├── helpers/          # Helper functions
├── tests/            # Test suites
├── assets/           # CSS/JS assets
├── database/         # Database schemas
└── docs/             # Documentation
```

### Contributing
1. Fork the repository
2. Create a feature branch
3. Write tests for new functionality
4. Ensure all tests pass
5. Submit a pull request

### Code Standards
- PSR-12 coding standards
- PHPDoc documentation required
- Minimum 80% test coverage
- Static analysis with PHPStan level 8

## Support

### Documentation
- API Documentation: `/docs/api/`
- User Guide: `/docs/user/`
- Developer Guide: `/docs/developer/`

### Contact
- Email: suporte@descomplicar.pt
- Website: https://descomplicar.pt
- Documentation: https://docs.descomplicar.pt/desk-moloni

## License

This module is commercial software developed by Descomplicar®. 
All rights reserved.

## Changelog

### v3.0.0 (Current)
- Complete rewrite with enterprise features
- Advanced queue management system
- Redis caching support
- Enhanced security with encryption
- Comprehensive monitoring and analytics
- PHPUnit testing framework
- Performance optimization

### v2.x.x (Legacy)
- Basic synchronization features
- Simple queue system
- File-based logging

## Credits

Developed with ❤️ by [Descomplicar®](https://descomplicar.pt)

---

**Note**: This is a commercial module. Unauthorized distribution or modification is prohibited.