2025-09-14 01:06:12 +01:00

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

  • Expanded Test Coverage: 80%+ comprehensive unit and integration tests
  • Contract Testing: API specification compliance verification
  • Mock Framework: Complete test environment with MockWebServer
  • PHPUnit 12.3+: Latest testing framework with PHP 8.4 attributes
  • TDD Methodology: Test-driven development approach
  • Performance Testing: Memory profiling and load testing
  • Security Testing: OWASP compliance verification

Installation

Requirements

  • Perfex CRM v3.0 or higher
  • PHP 8.4 or higher (LTS support until 2028)
  • MySQL 8.0 or MariaDB 10.6+
  • Curl extension
  • OpenSSL extension
  • JSON extension
  • PDO extension
  • Mbstring extension

Optional Requirements

  • Redis server (for caching and queue management)
  • Composer (for dependency management)

Installation Steps

  1. Download and Extract

    cd /path/to/perfex/modules/
    git clone [repository-url] desk_moloni
    
  2. Install Dependencies

    cd desk_moloni
    composer install --no-dev --optimize-autoloader
    
  3. Set Permissions

    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

// 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

// Synchronization settings
'auto_sync_enabled' => true,
'realtime_sync_enabled' => false,
'default_sync_delay' => 300, // 5 minutes
'batch_sync_enabled' => true,

Redis Configuration (Optional)

// 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

    // 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

// 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

// 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

# Run all tests with PHPUnit 12.3+
composer test

# Run specific test suite
./vendor/bin/phpunit --testsuite unit
./vendor/bin/phpunit --testsuite integration
./vendor/bin/phpunit --testsuite feature

# Run with coverage (HTML, XML, Text reports)
composer test-coverage

# Run performance tests
./vendor/bin/phpunit --group performance

Test Configuration

  • Tests use SQLite in-memory database for isolation
  • Mock API responses via MockWebServer extension
  • Comprehensive fixtures in tests/fixtures/
  • Performance listeners for memory and timing analysis
  • PHPUnit 12.3 schema with modern attributes

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

// 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

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®


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

Description
Integração Desk-Moloni
Readme 32 MiB
Languages
PHP 91.4%
Shell 5.4%
JavaScript 2.5%
CSS 0.7%