subscription ?? app(CustomDomainAccess::class)->contractOf($instance->customer); return self::forPlan((int) ($instance->quota_gb ?? $contract?->quota_gb ?? 0), $contract); } /** * The same question about a package the customer is not on yet. * * The downgrade check needs it: whether a smaller package is big enough * depends on the packs the customer has ALREADY paid for, which move with * them. */ public static function forPlan(int $planGb, ?Subscription $subscription): self { return new self(max(0, $planGb), self::bookedPacks($subscription), self::packSizeGb()); } /** Everything the booked packs add. */ public function packGb(): int { return $this->packs * $this->packSizeGb; } /** The figure Nextcloud is told, the disk is sized for, and the portal shows. */ public function totalGb(): int { return $this->planGb + $this->packGb(); } public function hasPacks(): bool { return $this->packs > 0; } /** * How many MORE packs it would take to cover this many bytes. * * Zero when the allowance already covers it. Rounded up, because half a pack * is not for sale and an answer that leaves the customer one gigabyte short * is an answer that sends them back a second time. */ public function packsToCover(int $bytes): int { $short = $bytes - $this->totalGb() * 1024 ** 3; if ($short <= 0 || $this->packSizeGb <= 0) { return 0; } return (int) ceil($short / ($this->packSizeGb * 1024 ** 3)); } /** * Every pack still running on this contract, counted by quantity. * * Queried rather than read off a loaded relation: this is asked immediately * after a pack is booked or cancelled, and a relation loaded before that * would answer with the state the caller has just changed. */ private static function bookedPacks(?Subscription $subscription): int { if ($subscription === null) { return 0; } return (int) $subscription->addons()->active() ->where('addon_key', AddonCatalogue::STORAGE) ->sum('quantity'); } /** * What one pack is worth, from the catalogue. * * Read live rather than frozen onto the booking, unlike the PRICE. That is * not an oversight but it is a limit worth naming: `subscription_addons` * freezes what the customer agreed to PAY, and if the owner ever re-cuts the * pack from 100 GB to 200 GB, existing bookings would grow with it. Today * there is one pack size and it has never moved; the day it does, the size * belongs on the booking beside the price. */ private static function packSizeGb(): int { return max(0, (int) config('provisioning.storage_addon.gb', 0)); } }