CluPilotCloud/app/Services/Billing/DowngradeCheck.php

71 lines
2.4 KiB
PHP

<?php
namespace App\Services\Billing;
use App\Models\Customer;
use App\Models\Instance;
use App\Models\InstanceMetric;
use App\Models\Seat;
use App\Support\Bytes;
/**
* Whether a customer may move down to a smaller plan, and if not, why.
*
* A downgrade is not the mirror of an upgrade. Going up always fits; going
* down can ask an instance to hold more than the target plan allows, and the
* failure has to be explained in the customer's own numbers — "you have 31
* users, Start allows 10" — rather than as a disabled button. A greyed-out
* control that does not say what is in the way is the thing people ring about.
*
* Checked against what is MEASURED, not what was sold: a customer sitting on
* 480 GB of a 500 GB plan cannot move to a 200 GB one, whatever their contract
* says the allowance is.
*/
final readonly class DowngradeCheck
{
private function __construct(
public bool $allowed,
/** @var array<int, array{key: string, current: string, limit: string}> */
public array $blockers,
) {}
/**
* @param array<string, mixed> $target the catalogue entry being moved to
*/
public static function for(Customer $customer, ?Instance $instance, array $target): self
{
$blockers = [];
$seats = Seat::query()
->where('customer_id', $customer->id)
->whereIn('status', ['active', 'invited'])
->count();
$seatLimit = (int) ($target['seats'] ?? 0);
if ($seatLimit > 0 && $seats > $seatLimit) {
$blockers[] = [
'key' => 'seats',
'current' => (string) $seats,
'limit' => (string) $seatLimit,
];
}
// Storage is checked against the last real reading. Falling back to the
// contractual allowance would refuse a downgrade to anyone who has ever
// bought a large plan, however empty their instance is.
$quotaGb = (int) ($target['quota_gb'] ?? 0);
$metric = $instance !== null ? InstanceMetric::latestDisk($instance) : null;
if ($quotaGb > 0 && $metric !== null && $metric->disk_used_bytes > $quotaGb * 1024 ** 3) {
$blockers[] = [
'key' => 'storage',
'current' => Bytes::human($metric->disk_used_bytes),
'limit' => $quotaGb.' GB',
];
}
return new self($blockers === [], $blockers);
}
}