Skip to content

Commit 35627ef

Browse files
committed
feat: Make ai usage counter polymorphic
1 parent 6e27c7a commit 35627ef

3 files changed

Lines changed: 9 additions & 6 deletions

File tree

database/migrations/2026_06_16_201941_create_ai_usage_counters_table.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,10 @@ public function up(): void
1212
{
1313
Schema::create('ai_usage_counters', function (Blueprint $table) {
1414
$table->id();
15-
$table->unsignedBigInteger('user_id');
15+
$table->morphs('owner');
1616
$table->timestamp('period_start');
1717
$table->integer('tokens_used');
1818

19-
$table->foreign('user_id')->references('id')->on('users');
2019
$table->timestamps();
2120
});
2221
}

src/Models/AiUsageCounter.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ class AiUsageCounter extends Model
2020
* @var array<int, string>
2121
*/
2222
protected $fillable = [
23-
'user_id',
23+
'owner_id',
24+
'owner_type',
2425
'period_start',
2526
'tokens_used',
2627
];

src/Support/CloudEntitlements.php

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ public function remaining(?Model $owner, string $meter): int|float
6262
}
6363

6464
$periodStart = Carbon::now()->startOfMonth();
65-
$used = AiUsageCounter::where('user_id', $owner->id)
65+
$used = AiUsageCounter::where('owner_id', $owner->id)
66+
->where('owner_type', get_class($owner))
6667
->where('period_start', $periodStart)
6768
->value('tokens_used') ?? 0;
6869

@@ -101,15 +102,17 @@ public function consume(?Model $owner, string $meter, int $amount): void
101102

102103
$periodStart = Carbon::now()->startOfMonth();
103104

104-
$counter = AiUsageCounter::where('user_id', $owner->id)
105+
$counter = AiUsageCounter::where('owner_id', $owner->id)
106+
->where('owner_type', get_class($owner))
105107
->where('period_start', $periodStart)
106108
->first();
107109

108110
if ($counter) {
109111
$counter->increment('tokens_used', $amount);
110112
} else {
111113
AiUsageCounter::create([
112-
'user_id' => $owner->id,
114+
'owner_id' => $owner->id,
115+
'owner_type' => get_class($owner),
113116
'period_start' => $periodStart,
114117
'tokens_used' => $amount,
115118
]);

0 commit comments

Comments
 (0)