# PUQcloud Module Development Documentation

<p class="callout info">✨ **COMPREHENSIVE GUIDE:** Complete documentation for developing professional modules in PUQcloud billing system.</p>

### **📚 Documentation Structure**

This documentation suite provides everything you need to build professional, scalable modules for PUQcloud:

#### **🎯 Start Here**

- [**What is a Module?** ](https://doc.puq.info/books/puqcloud-panel-for-developers/page/what-is-a-module)- Complete introduction to PUQcloud's modular architecture

#### **📖 Development Resources**

- [**Module Development Guide**](https://doc.puq.info/books/puqcloud-panel-for-developers/page/module-development-guide) - Step-by-step development tutorial with real examples
- [**API Reference** ](https://doc.puq.info/books/puqcloud-panel-for-developers/page/api-reference)- Complete method documentation and usage examples
- [**Practical Examples**](https://doc.puq.info/books/puqcloud-panel-for-developers/page/practical-examples) - Real-world module implementations

#### **🛠️ Support &amp; Quality**

- [**FAQ &amp; Troubleshooting** ](https://doc.puq.info/books/puqcloud-panel-for-developers/page/faq-troubleshooting)- Solutions to common development problems
- [**Development Checklist** ](https://doc.puq.info/books/puqcloud-panel-for-developers/page/development-checklist)- Quality assurance and best practices guide

### **🏗️ PUQcloud Module Architecture**

- - - - - -

#### **Module System Overview**

PUQcloud uses a sophisticated modular architecture with four distinct module types:

```VBScript
App\Modules\Module (Base Class)
├── Product      → Service lifecycle management (hosting, VPS, domains)
├── Plugin       → System extensions (monitoring, analytics, reports)
├── Payment      → Payment gateway integrations (Stripe, PayPal, crypto)
└── Notification → Communication channels (SMTP, SMS, Slack, webhooks)
```

#### **Class Responsibilities and APIs**

Every module is a PHP class inheriting from `App\Modules\Module` and shares a consistent contract:

- **Lifecycle**: `activate()`, `update()`, `deactivate()`
- **Rendering**: `view(string $template, array $data = [])`
- **Configuration**: `config(string $key): mixed`
- **Async jobs**: `Task::add('ModuleJob', 'Module', $data, $tags)`
- **Logging**: `logInfo()`, `logError()`, `logDebug()`
- **Security**: permissions and access control in admin routes/controllers

#### **Derived Module Types and Typical Methods**

##### **Product (Service Management)**

- **Product config**: `getProductData()`, `saveProductData()`, `getProductPage()`
- **Service config**: `getServiceData()`, `saveServiceData()`, `getServicePage()`
- **Service lifecycle**: `create()`/`createJob()`, `suspend()`/`suspendJob()`, `unsuspend()`/`unsuspendJob()`, `termination()`/`terminationJob()`, `change_package()`/`change_packageJob()`
- **Client area**: `getClientAreaMenuConfig()`, `variables_{tab}()`, `controllerClient_{tab}{Method}()`
- **Admin area**: `adminPermissions()`, `adminSidebar()`, `adminWebRoutes()`, `adminApiRoutes()`

##### **Plugin (System Extensions)**

- **Lifecycle**: `activate()`, `deactivate()`, `update()`
- **Admin**: `adminSidebar()`, `adminWebRoutes()`, `adminApiRoutes()`
- **Background work**: scheduled tasks via `Task::add()` and event hooks in `hooks.php`
- **Client area**: typically none

##### **Payment (Payment Processing)**

- **Config**: `getModuleData()`, admin settings via `getSettingsPage()`
- **Checkout UI**: `getClientAreaHtml()`
- **Webhooks**: `apiWebhookPost()`/`apiWebhookGet()`
- **Actions**: success/failure handlers, optional `refund()`

##### **Notification (Communication Channels)**

- **Config**: `getModuleData()` (server, credentials, encryption, sender)
- **Delivery**: `send(array $data)` with validation, retries, logging
- **Templates**: render content with Blade templates

#### **Real Module Structure**

Every module follows this standardized structure:

```VBScript
modules/{Type}/{ModuleName}/
├── {ModuleName}.php              # Main module class (required)
├── config.php                    # Module metadata (required)
├── hooks.php                     # Event hooks (optional)
├── Controllers/                  # HTTP request handlers
│   └── {ModuleName}Controller.php
├── Services/                     # External API clients
│   └── {ExternalService}Client.php
├── Models/                       # Database models
│   └── {ModuleName}Model.php
├── views/                        # Blade templates
│   ├── admin_area/              # Admin interface views
│   ├── client_area/             # Client interface views
│   └── assets/                  # CSS, JS, images
└── lang/                        # Internationalization
    ├── en.php
    └── pl.php
```

### **🚀 Quick Start Examples**

#### **Product Module (Service Management)**

**Real implementation example based on puqNextcloud:**

```PHP
<?php

use App\Models\Service;
use App\Models\Task;
use App\Modules\Product;

class MyNextcloudService extends Product
{
    public function __construct()
    {
        parent::__construct();
    }

    // Product configuration
    public function getProductData(array $data = []): array
    {
        $this->product_data = [
            'group_uuid' => $data['group_uuid'] ?? '',
            'username_prefix' => $data['username_prefix'] ?? 'nc_',
            'username_suffix' => $data['username_suffix'] ?? '',
            'quota' => $data['quota'] ?? '1GB',
        ];
        return $this->product_data;
    }

    // Service creation (asynchronous)
    public function create(): array
    {
        $data = [
            'module' => $this,              // Module instance reference
            'method' => 'createJob',        // Method to execute
            'tries' => 1,                   // Retry attempts
            'backoff' => 60,                // Delay between retries (seconds)
            'timeout' => 600,               // Max execution time
            'maxExceptions' => 1,           // Max exceptions before failure
        ];

        $tags = ['create'];
        
        $service = Service::find($this->service_uuid);
        $service->setProvisionStatus('processing');
        Task::add('ModuleJob', 'Module', $data, $tags);

        return ['status' => 'success'];
    }

    // Actual provisioning logic
    public function createJob(): array
    {
        try {
            $service = Service::find($this->service_uuid);
            
            // Generate service credentials
            $this->service_data['username'] = $this->product_data['username_prefix'] . 
                                             random_int(100000, 999999) . 
                                             $this->product_data['username_suffix'];
            $this->service_data['password'] = generateStrongPassword(10);
            
            // Create API client
            $apiClient = new NextcloudAPIClient($this->getServerConfig());
            
            // Provision account via API
            $response = $apiClient->createUser([
                'userid' => $this->service_data['username'],
                'password' => $this->service_data['password'],
            ]);
            
            if ($response['status'] === 'success') {
                $service->setProvisionStatus('completed');
                $this->logInfo('createJob', 'User created successfully');
                return ['status' => 'success'];
            } else {
                $service->setProvisionStatus('failed');
                $this->logError('createJob', 'User creation failed', $response);
                return ['status' => 'error', 'message' => $response['error']];
            }
            
        } catch (Exception $e) {
            $service->setProvisionStatus('failed');
            $this->logError('createJob', 'Exception occurred', $e->getMessage());
            return ['status' => 'error'];
        }
    }
}
```

#### **Payment Module (Stripe Integration)**

**Real implementation example based on puqStripe:**

```PHP
<?php

use App\Modules\Payment;

class MyStripePayment extends Payment
{
    public function getModuleData(array $data = []): array
    {
        return [
            'publishable_key' => $data['publishable_key'] ?? '',
            'secret_key' => $data['secret_key'] ?? '',
            'webhook_secret' => $data['webhook_secret'] ?? '',
            'sandbox' => $data['sandbox'] ?? false,
        ];
    }

    public function getClientAreaHtml(array $data = []): string
    {
        $invoice = $data['invoice'];
        $amount = $invoice->getDueAmountAttribute();
        $currency = $invoice->client->currency->code;

        $stripe = new StripeClient($this->module_data);
        
        $session = $stripe->createSession(
            referenceId: $invoice->uuid,
            invoiceId: $invoice->number,
            description: 'Invoice #' . $invoice->number,
            amount: $amount,
            currency: $currency,
            return_url: $this->getReturnUrl(),
            cancel_url: $this->getCancelUrl(),
        );

        return $this->view('client_area', ['session' => $session]);
    }
}
```

#### **Notification Module (SMTP Email)**

**Real implementation example based on puqSMTP:**

```PHP
<?php

use App\Modules\Notification;

class MySMTPNotification extends Notification
{
    public function getModuleData(array $data = []): array
    {
        return [
            'email' => $data['email'] ?? '',
            'server' => $data['server'] ?? '',
            'sender_name' => $data['sender_name'] ?? '',
            'port' => $data['port'] ?? 587,
            'encryption' => $data['encryption'] ?? 'tls',
            'username' => $data['username'] ?? '',
            'password' => $data['password'] ?? '',
        ];
    }

    public function send(array $data = []): array
    {
        try {
            $config = $this->buildMailConfig();
            
            Mail::mailer($config)->send(new NotificationMail(
                $data['to'],
                $data['subject'],
                $data['message']
            ));
            
            $this->logInfo('send', 'Email sent successfully', [
                'to' => $data['to'],
                'subject' => $data['subject']
            ]);
            
            return ['status' => 'success'];
            
        } catch (Exception $e) {
            $this->logError('send', 'Email sending failed', $e->getMessage());
            return ['status' => 'error', 'message' => $e->getMessage()];
        }
    }
}
```

### **🔧 Key Implementation Details**

#### **Task System (Asynchronous Processing)**

**Correct Task::add usage:**

```PHP
// Standard task configuration
$data = [
    'module' => $this,                    // Required: module instance
    'method' => 'methodName',             // Required: method to execute
    'tries' => 1,                         // Optional: retry attempts (default: 1)
    'backoff' => 60,                      // Optional: delay between retries
    'timeout' => 600,                     // Optional: max execution time
    'maxExceptions' => 1,                 // Optional: max exceptions
];

$tags = ['operation_type', 'service:' . $this->service_uuid];
Task::add('ModuleJob', 'Module', $data, $tags);
```

#### **Database Integration**

**Table creation in activate():**

```PHP
public function activate(): string
{
    try {
        if (!Schema::hasTable('module_servers')) {
            Schema::create('module_servers', function (Blueprint $table) {
                $table->uuid()->primary();
                $table->string('name')->unique();
                $table->string('host');
                $table->string('username');
                $table->string('password');
                $table->boolean('active')->default(true);
                $table->integer('port')->default(443);
                $table->timestamps();
            });
        }
        
        $this->logInfo('activate', 'Module activated successfully');
        return 'success';
    } catch (Exception $e) {
        $this->logError('activate', 'Activation failed: ' . $e->getMessage());
        return 'Error: ' . $e->getMessage();
    }
}
```

#### **Configuration File**

**Standard config.php structure:**

```PHP
<?php

return [
    'name' => 'My Module Name',
    'description' => 'Professional module description',
    'version' => '1.0.0',
    'author' => 'Developer Name',
    'email' => 'developer@domain.com',
    'website' => 'https://developer-website.com',
    'logo' => __DIR__ . '/views/assets/img/logo.png',
    'icon' => 'fas fa-server',  // FontAwesome icon
];
```

### **📋 Module Types Comparison**

<table border="1" id="bkmrk-%C2%A0-feature-product-pl" style="height: 173px; width: 100%; border-collapse: collapse;"><caption> </caption><tbody><tr style="height: 28px;"><td style="width: 18.2716%; height: 28px;">**Feature**</td><td style="width: 26.4198%; height: 28px;">**Product**</td><td style="width: 28.395%; height: 28px;">**Plugin**</td><td style="width: 26.9137%; height: 28px;">**Payment**</td><td style="width: 31.7957%; height: 28px;">**Notification**</td></tr><tr style="height: 29px;"><td style="width: 18.2716%; height: 29px;">**Purpose**</td><td style="width: 26.4198%; height: 29px;">Service lifecycle</td><td style="width: 28.395%; height: 29px;">System extension</td><td style="width: 26.9137%; height: 29px;">Payment processing</td><td style="width: 31.7957%; height: 29px;">Communication</td></tr><tr style="height: 29px;"><td style="width: 18.2716%; height: 29px;">**Base Class**</td><td style="width: 26.4198%; height: 29px;">`App\Modules\Product`</td><td style="width: 28.395%; height: 29px;">`App\Modules\Plugin`</td><td style="width: 26.9137%; height: 29px;">`App\Modules\Payment`</td><td style="width: 31.7957%; height: 29px;">`App\Modules\Notification`</td></tr><tr style="height: 29px;"><td style="width: 18.2716%; height: 29px;">**Key Methods**</td><td style="width: 26.4198%; height: 29px;">`create()`, `suspend()`, `terminate()`</td><td style="width: 28.395%; height: 29px;">`activate()`, custom methods</td><td style="width: 26.9137%; height: 29px;">`getClientAreaHtml()`</td><td style="width: 31.7957%; height: 29px;">`send()`</td></tr><tr style="height: 29px;"><td style="width: 18.2716%; height: 29px;">**Client Area**</td><td style="width: 26.4198%; height: 29px;">Full interface with tabs</td><td style="width: 28.395%; height: 29px;">None</td><td style="width: 26.9137%; height: 29px;">Payment forms</td><td style="width: 31.7957%; height: 29px;">Configuration only</td></tr><tr style="height: 29px;"><td style="width: 18.2716%; height: 29px;">**Examples**</td><td style="width: 26.4198%; height: 29px;">Nextcloud, VPS hosting</td><td style="width: 28.395%; height: 29px;">Monitoring, analytics</td><td style="width: 26.9137%; height: 29px;">Stripe, PayPal, MonoBank</td><td style="width: 31.7957%; height: 29px;">SMTP, SMS</td></tr></tbody></table>

### **🛠️ Development Environment**

#### **Prerequisites**

```PHP
# Required stack
PHP 8.1+
Laravel 9.0+
Composer
MySQL/PostgreSQL
Redis (for queues)
Node.js & NPM (for assets)

# Recommended tools
Docker & Docker Compose
Git
PHPStorm/VSCode
```

#### **Quick Setup**

```PHP
# 1. Create module directory
mkdir -p modules/Product/MyModule

# 2. Create basic files
cat > modules/Product/MyModule/MyModule.php << 'EOF'
<?php

use App\Modules\Product;

class MyModule extends Product
{
    public function __construct()
    {
        parent::__construct();
    }
}
EOF

# 3. Create configuration
cat > modules/Product/MyModule/config.php << 'EOF'
<?php

return [
    'name' => 'My Module',
    'description' => 'Module description',
    'version' => '1.0.0',
    'author' => 'Your Name',
    'email' => 'your.email@domain.com',
    'website' => 'https://yourdomain.com',
    'icon' => 'fas fa-server',
];
EOF
```

### **📖 Next Steps**

#### **Learning Path**

- **📚 Read [What is a Module?](https://doc.puq.info/books/puqcloud-panel-for-developers/page/what-is-a-module)** - Understand the architecture
- **🛠️ Follow [Development Guide ](https://doc.puq.info/books/puqcloud-panel-for-developers/page/module-development-guide)**- Build your first module
- **📋 Use [API Reference ](https://doc.puq.info/books/puqcloud-panel-for-developers/page/api-reference)**- Implement specific features
- **💼 Study [Examples](https://doc.puq.info/books/puqcloud-panel-for-developers/page/practical-examples)** - Learn from real implementations
- **✅ Apply [Checklist](https://doc.puq.info/books/puqcloud-panel-for-developers/page/development-checklist)** - Ensure quality

#### **Development Support**

<table border="1" id="bkmrk-issue-type-resource-" style="border-collapse: collapse; width: 100%; height: 145px;"><tbody><tr style="height: 29px;"><td style="width: 33.3333%; height: 29px;">**Issue Type**</td><td style="width: 33.3333%; height: 29px;">**Resource**</td><td style="width: 33.3333%; height: 29px;">**Description**</td></tr><tr style="height: 29px;"><td style="width: 33.3333%; height: 29px;">**Getting Started**</td><td style="width: 33.3333%; height: 29px;">Development Guide</td><td style="width: 33.3333%; height: 29px;">Step-by-step tutorial</td></tr><tr style="height: 29px;"><td style="width: 33.3333%; height: 29px;">**Technical Issues**</td><td style="width: 33.3333%; height: 29px;">FAQ &amp; Troubleshooting</td><td style="width: 33.3333%; height: 29px;">Common problems &amp; solutions</td></tr><tr style="height: 29px;"><td style="width: 33.3333%; height: 29px;">**API Questions**</td><td style="width: 33.3333%; height: 29px;">API Reference</td><td style="width: 33.3333%; height: 29px;">Method documentation</td></tr><tr style="height: 29px;"><td style="width: 33.3333%; height: 29px;">**Best Practices**</td><td style="width: 33.3333%; height: 29px;">Development Checklist</td><td style="width: 33.3333%; height: 29px;">Quality guidelines</td></tr></tbody></table>

### **⚡ Key Success Factors**

#### **🎯 Accuracy First**

- Follow real implementation patterns from existing modules
- Use correct `Task::add()` syntax and parameters
- Implement proper error handling and logging

#### **🔒 Security &amp; Performance**

- Validate all inputs with Laravel Validator
- Use encrypted storage for sensitive data
- Implement caching for expensive operations
- Handle external API failures gracefully

#### **🧪 Quality Assurance**

- Test all module functionality thoroughly
- Follow PSR-12 coding standards
- Use proper type hints and documentation
- Implement comprehensive error handling

##### **Ready to build professional modules?** Start with [**What is a Module?**](https://doc.puq.info/books/puqcloud-panel-for-developers/page/what-is-a-module) and create modules that integrate seamlessly with PUQcloud's architecture!