trypost/app/Models/Traits/HasUsage.php
Paulo Castellano aacc4390a2 refactor(billing): replace MonthlyCreditsLimit Pennant feature with BillingCycle
Credit allotment is now derived directly from BillingCycle::for($account)->creditAllotment()
instead of a cached Pennant feature, removing the dynamic cache-invalidation footgun
(forgetPlanFeatureCache) that had to be called from every subscription/workspace mutation.
2026-06-22 09:55:03 -03:00

79 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models\Traits;
use App\Models\Account;
use App\Models\Invite;
use App\Models\Post;
use App\Support\BillingCycle;
use Illuminate\Support\Facades\Cache;
/**
* Provides account-level usage counts and plan-resolved feature limits.
*
* `featureLimits()` resolves the account's per-cycle credit allotment directly
* from BillingCycle, computed fresh from the plan, workspace count, and billing
* interval — no caching, so there is nothing to invalidate.
*/
trait HasUsage
{
/**
* Cache TTL for the per-account post count. Posts are unbounded by plan
* limits and not used for any quota gating, so a few minutes of staleness
* is acceptable in exchange for skipping a potentially heavy aggregate
* query on every authenticated request.
*/
private const POST_COUNT_CACHE_TTL = 300;
/**
* @return array{workspaceCount: int, socialAccountCount: int, memberCount: int, pendingInviteCount: int, postCount: int, creditsUsed: int}
*/
public function usage(): array
{
$workspaces = $this->workspaces()
->withCount('socialAccounts')
->get();
return [
'workspaceCount' => $workspaces->count(),
'socialAccountCount' => (int) $workspaces->sum('social_accounts_count'),
'memberCount' => $this->users()->count(),
'pendingInviteCount' => Invite::where('account_id', $this->id)
->whereNull('accepted_at')
->count(),
'postCount' => $this->cachedPostCount($workspaces->pluck('id')->all()),
'creditsUsed' => BillingCycle::for($this)->usedCredits(),
];
}
/**
* @return array{monthlyCreditsLimit: int}
*/
public function featureLimits(): array
{
return [
'monthlyCreditsLimit' => BillingCycle::for($this)->creditAllotment(),
];
}
/**
* The `(int)` cast is load-bearing: Laravel's RedisStore stores numeric
* values raw (for atomic INCR) and returns them as strings on read.
*
* @param array<int, string> $workspaceIds
*/
private function cachedPostCount(array $workspaceIds): int
{
if (empty($workspaceIds)) {
return 0;
}
return (int) Cache::remember(
Account::postsCountCacheKey((string) $this->id),
self::POST_COUNT_CACHE_TTL,
fn () => Post::whereIn('workspace_id', $workspaceIds)->count(),
);
}
}