Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ DB_PASSWORD=
# Optional: use Unix socket instead of TCP (leave commented for TCP)
# DB_SOCKET=/var/run/mysqld/mysqld.sock

# ── Add-on fulfilment ───────────────────────────────────────────────────────
# Off by default. This only controls the technical add-on executor; sales,
# invoicing and billing are unaffected.
ADDONS_FULFILLMENT_ENABLED=false
ADDONS_FULFILLMENT_PROCESSING_TIMEOUT=15
# The AddonTest module is only registered in local/testing, and only when
# this is on. Never enable it in production.
ADDONS_TEST_MODULE_ENABLED=false

# ── Session / Cache / Queue ─────────────────────────────────────────────────
# "file" drivers work out of the box. Switch to redis/database once tables exist.
SESSION_DRIVER=file
Expand Down
52 changes: 52 additions & 0 deletions app/Console/Commands/ProcessAddonExecutionsCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace App\Console\Commands;

use App\Enums\AddonExecutionStatus;
use App\Models\ServiceAddonExecution;
use App\Services\Addons\AddonExecutionService;
use Illuminate\Console\Command;

class ProcessAddonExecutionsCommand extends Command
{
protected $signature = 'pnlcs:addon-executions:process {--limit=25 : Maximum executions to process} {--id= : Process one execution}';

protected $description = 'Process pending and retryable service add-on executions';

public function handle(AddonExecutionService $executor): int
{
if (! $executor->enabled()) {
$this->info('Addon fulfillment is disabled.');

return self::SUCCESS;
}

$reclaimed = $executor->reclaimStale(max(1, (int) $this->option('limit')));
if ($reclaimed > 0) {
$this->info('Reclaimed '.$reclaimed.' stale execution(s).');
}

$query = ServiceAddonExecution::query()
->whereIn('status', [
AddonExecutionStatus::Pending->value,
AddonExecutionStatus::Retry->value,
])
->where(function ($query): void {
$query->whereNull('available_at')->orWhere('available_at', '<=', now());
});

if ($id = $this->option('id')) {
$query->whereKey((int) $id);
}

$executions = $query->orderBy('id')->limit(max(1, (int) $this->option('limit')))->get();

foreach ($executions as $execution) {
$executor->execute($execution);
}

$this->info('Processed '.$executions->count().' add-on execution(s).');

return self::SUCCESS;
}
}
42 changes: 42 additions & 0 deletions app/Contracts/ServiceAddonModuleInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace App\Contracts;

use App\Models\Service;
use App\Support\Addons\AddonInstruction;

/**
* Optional capability for server modules that can apply purchased add-on
* effects. ServerModuleInterface stays unchanged, so modules that do not
* support add-ons keep working exactly as before.
*/
interface ServiceAddonModuleInterface
{
/**
* @return array{
* operations?: array<int, string>,
* parameters?: array<string, array{unit?: string|null, min?: int|float|null, max?: int|float|null}>
* }
*/
public function addonCapabilities(): array;

/**
* @return array{success: bool, message: string, data?: array<string, mixed>}
*/
public function validateAddon(Service $service, AddonInstruction $instruction): array;

/**
* @return array{success: bool, message: string, data?: array<string, mixed>}
*/
public function applyAddon(Service $service, AddonInstruction $instruction): array;

/**
* @return array{success: bool, message: string, data?: array<string, mixed>}
*/
public function removeAddon(Service $service, AddonInstruction $instruction): array;

/**
* @return array{success: bool, message: string, data?: array<string, mixed>}
*/
public function getAddonStatus(Service $service, AddonInstruction $instruction): array;
}
9 changes: 9 additions & 0 deletions app/Enums/AddonExecutionAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace App\Enums;

enum AddonExecutionAction: string
{
case Apply = 'apply';
case Remove = 'remove';
}
32 changes: 32 additions & 0 deletions app/Enums/AddonExecutionStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace App\Enums;

enum AddonExecutionStatus: string
{
case NotConfigured = 'not_configured';
case Pending = 'pending';
case Processing = 'processing';
case Completed = 'completed';
case Failed = 'failed';
case Retry = 'retry';
case Cancelled = 'cancelled';
case ManualRequired = 'manual_required';
case Unsupported = 'unsupported';

public function isFinished(): bool
{
return in_array($this, [
self::Completed,
self::Failed,
self::Cancelled,
self::ManualRequired,
self::Unsupported,
], true);
}

public function isRetryable(): bool
{
return in_array($this, [self::Pending, self::Retry], true);
}
}
22 changes: 22 additions & 0 deletions app/Enums/AddonOperation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace App\Enums;

enum AddonOperation: string
{
case Increment = 'increment';
case Decrement = 'decrement';
case Set = 'set';
case Attach = 'attach';
case Detach = 'detach';

public function usesNumericValue(): bool
{
return in_array($this, [self::Increment, self::Decrement, self::Set], true);
}

public function isRemoval(): bool
{
return in_array($this, [self::Decrement, self::Detach], true);
}
}
7 changes: 7 additions & 0 deletions app/Exceptions/AddonModuleUnavailableException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace App\Exceptions;

use RuntimeException;

class AddonModuleUnavailableException extends RuntimeException {}
36 changes: 36 additions & 0 deletions app/Jobs/ExecuteServiceAddonJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace App\Jobs;

use App\Models\ServiceAddonExecution;
use App\Services\Addons\AddonExecutionService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ExecuteServiceAddonJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public int $tries = 3;

/** @var array<int, int> */
public array $backoff = [60, 300];

public int $timeout = 300;

public function __construct(public int $executionId) {}

public function handle(AddonExecutionService $executor): void
{
$execution = ServiceAddonExecution::find($this->executionId);

if (! $execution) {
return;
}

$executor->execute($execution);
}
}
28 changes: 27 additions & 1 deletion app/Models/ProductAddon.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,40 @@ class ProductAddon extends Model

protected $table = 'product_addons';

protected $fillable = ['name', 'description', 'packages', 'hidden', 'retired', 'sort_order', 'tax'];
protected $fillable = [
'name', 'description', 'packages', 'hidden', 'retired', 'sort_order', 'tax',
'fulfillment_module', 'operation', 'parameter', 'value', 'unit', 'options', 'auto_fulfill',
];

protected function casts(): array
{
return [
'hidden' => 'boolean',
'retired' => 'boolean',
'tax' => 'boolean',
'options' => 'array',
'auto_fulfill' => 'boolean',
];
}

/** Whether this addon carries anything the executor can perform. */
public function hasFulfillmentConfig(): bool
{
return trim((string) $this->operation) !== ''
&& trim((string) $this->parameter) !== '';
}

/** The snapshot copied to a ServiceAddon at purchase time. */
public function fulfillmentConfig(): array
{
return [
'module' => $this->fulfillment_module,
'operation' => $this->operation,
'parameter' => $this->parameter,
'value' => $this->value,
'unit' => $this->unit,
'options' => $this->options ?? [],
'auto_fulfill' => (bool) $this->auto_fulfill,
];
}

Expand Down
26 changes: 25 additions & 1 deletion app/Models/ServiceAddon.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

namespace App\Models;

use App\Enums\AddonExecutionStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class ServiceAddon extends Model
{
use HasFactory;

protected $fillable = ['order_id', 'service_id', 'addon_id', 'client_id', 'server_id', 'qty', 'amount', 'prorated', 'proration_days', 'proration_cycle_days', 'billing_cycle', 'next_due_date', 'first_invoice_date', 'status', 'notes'];
protected $fillable = ['order_id', 'service_id', 'addon_id', 'client_id', 'server_id', 'qty', 'amount', 'prorated', 'proration_days', 'proration_cycle_days', 'billing_cycle', 'next_due_date', 'first_invoice_date', 'status', 'notes', 'fulfillment_config', 'fulfillment_status', 'fulfilled_at', 'fulfillment_error'];

protected function casts(): array
{
Expand All @@ -20,6 +23,9 @@ protected function casts(): array
'prorated' => 'boolean',
'proration_days' => 'integer',
'proration_cycle_days' => 'integer',
'fulfillment_config' => 'array',
'fulfillment_status' => AddonExecutionStatus::class,
'fulfilled_at' => 'datetime',
];
}

Expand All @@ -43,6 +49,24 @@ public function addon()
return $this->belongsTo(ProductAddon::class, 'addon_id');
}

public function executions(): HasMany
{
return $this->hasMany(ServiceAddonExecution::class);
}

public function latestExecution(): HasOne
{
return $this->hasOne(ServiceAddonExecution::class)->latestOfMany();
}

public function latestCompletedApply(): HasOne
{
return $this->hasOne(ServiceAddonExecution::class)
->where('action', 'apply')
->where('status', 'completed')
->latestOfMany();
}

/** What to call this on an invoice or in the customer's service page. */
public function label(): string
{
Expand Down
60 changes: 60 additions & 0 deletions app/Models/ServiceAddonExecution.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace App\Models;

use App\Enums\AddonExecutionAction;
use App\Enums\AddonExecutionStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ServiceAddonExecution extends Model
{
protected $fillable = [
'service_addon_id', 'service_id', 'client_id', 'source_invoice_id',
'action', 'status', 'module', 'operation', 'parameter', 'value', 'unit',
'request_payload', 'response_payload', 'result_message',
'idempotency_key', 'claim_token', 'attempts', 'max_attempts',
'available_at', 'started_at', 'finished_at',
];

protected function casts(): array
{
return [
'action' => AddonExecutionAction::class,
'status' => AddonExecutionStatus::class,
'request_payload' => 'array',
'response_payload' => 'array',
'attempts' => 'integer',
'max_attempts' => 'integer',
'available_at' => 'datetime',
'started_at' => 'datetime',
'finished_at' => 'datetime',
];
}

public function serviceAddon(): BelongsTo
{
return $this->belongsTo(ServiceAddon::class);
}

public function service(): BelongsTo
{
return $this->belongsTo(Service::class);
}

public function client(): BelongsTo
{
return $this->belongsTo(Client::class);
}

public function sourceInvoice(): BelongsTo
{
return $this->belongsTo(Invoice::class, 'source_invoice_id');
}

public function attempts(): HasMany
{
return $this->hasMany(ServiceAddonExecutionAttempt::class, 'execution_id')->orderBy('attempt_no');
}
}
Loading
Loading