Fix API controllers to use correct database column names

- Fix model_pricing table references (model_id -> model, display_name -> model)
- Fix price columns (output_price_per_1k -> output_price_per_million)
- Add price conversion (per_million / 1000 = per_1k) in all API responses
- Add whereNotNull('model') filters to exclude invalid entries
- Add getModelDisplayName() helper method to all controllers
- Fix AccountController to use gateway_users budget fields directly
- Remove Budget model dependencies from AccountController
- Add custom Scramble server URL configuration for API docs
- Create ScrambleServiceProvider to set correct /api prefix
- Add migration to rename user_id to gateway_user_id in llm_requests
- Add custom ApiGuard for gateway_users authentication
- Update all API controllers: AccountController, ModelController, PricingController, ProviderController

All API endpoints now working correctly:
- GET /api/account
- GET /api/models
- GET /api/pricing
- GET /api/providers/{provider}
This commit is contained in:
wtrinkl
2025-11-19 19:36:58 +01:00
parent c65643ac1f
commit cb495e18e3
38 changed files with 1045 additions and 823 deletions

View File

@@ -55,8 +55,6 @@ class Budget extends Model
return 'Unlimited';
}
public function gatewayUsers()
{
return $this->hasMany(GatewayUser::class, 'budget_id', 'budget_id');
}
// Note: gateway_users have their own budget system (monthly_budget_limit, current_month_spending)
// and are not linked to this budgets table
}

View File

@@ -4,10 +4,12 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Auth\Authenticatable as AuthenticatableTrait;
class GatewayUser extends Model
class GatewayUser extends Model implements Authenticatable
{
use HasFactory;
use HasFactory, AuthenticatableTrait;
protected $table = 'gateway_users';
protected $primaryKey = 'user_id';
@@ -17,8 +19,10 @@ class GatewayUser extends Model
protected $fillable = [
'user_id',
'alias',
'budget_id',
'spend',
'monthly_budget_limit',
'current_month_spending',
'budget_alert_threshold',
'rate_limit_per_hour',
'blocked',
'metadata',
];
@@ -26,48 +30,78 @@ class GatewayUser extends Model
protected $casts = [
'metadata' => 'array',
'blocked' => 'boolean',
'spend' => 'decimal:2',
'monthly_budget_limit' => 'decimal:2',
'current_month_spending' => 'decimal:2',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
/**
* Get the budget associated with the user.
*/
public function budget()
{
return $this->belongsTo(Budget::class, 'budget_id', 'budget_id');
}
/**
* Get the API keys for the user.
*/
// Relationships
public function apiKeys()
{
return $this->hasMany(ApiKey::class, 'user_id', 'user_id');
return $this->hasMany(ApiKey::class, 'gateway_user_id', 'user_id');
}
public function credentials()
{
return $this->hasMany(GatewayUserCredential::class, 'user_id', 'user_id');
}
/**
* Get the usage logs for the user.
*/
public function usageLogs()
{
return $this->hasMany(UsageLog::class, 'user_id', 'user_id');
return $this->hasMany(UsageLog::class, 'gateway_user_id', 'user_id');
}
/**
* Scope a query to only include active users.
*/
// Scopes
public function scopeActive($query)
{
return $query->where('blocked', false);
}
/**
* Scope a query to only include blocked users.
*/
public function scopeBlocked($query)
{
return $query->where('blocked', true);
}
// Helper methods for budget management
public function isBlocked(): bool
{
return $this->blocked;
}
public function hasExceededBudget(): bool
{
if (!$this->monthly_budget_limit) {
return false;
}
return $this->current_month_spending >= $this->monthly_budget_limit;
}
public function incrementSpending(float $amount): void
{
$this->increment('current_month_spending', $amount);
}
public function resetMonthlySpending(): void
{
$this->update(['current_month_spending' => 0]);
}
public function getBudgetUsagePercentage(): ?float
{
if (!$this->monthly_budget_limit || $this->monthly_budget_limit == 0) {
return null;
}
return ($this->current_month_spending / $this->monthly_budget_limit) * 100;
}
public function shouldSendBudgetAlert(): bool
{
if (!$this->budget_alert_threshold || !$this->monthly_budget_limit) {
return false;
}
$percentage = $this->getBudgetUsagePercentage();
return $percentage !== null && $percentage >= $this->budget_alert_threshold;
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;
class GatewayUserCredential extends Model
{
protected $fillable = [
'gateway_user_id',
'provider',
'api_key',
'organization_id',
'is_active',
'last_used_at',
'last_tested_at',
'test_status',
'test_error',
];
protected $hidden = ['api_key'];
protected $casts = [
'is_active' => 'boolean',
'last_used_at' => 'datetime',
'last_tested_at' => 'datetime',
];
// Automatic encryption for API keys
public function setApiKeyAttribute($value): void
{
$this->attributes['api_key'] = Crypt::encryptString($value);
}
public function getApiKeyAttribute($value): string
{
return Crypt::decryptString($value);
}
// Relationships
public function gatewayUser()
{
return $this->belongsTo(GatewayUser::class, 'gateway_user_id', 'user_id');
}
// Helper methods
public function markAsUsed(): void
{
$this->update(['last_used_at' => now()]);
}
public function markAsTested(bool $success, ?string $error = null): void
{
$this->update([
'last_tested_at' => now(),
'test_status' => $success ? 'success' : 'failed',
'test_error' => $error,
]);
}
}

View File

@@ -17,7 +17,7 @@ class UsageLog extends Model
protected $fillable = [
'request_id',
'user_id',
'gateway_user_id', // Changed from user_id
'api_key',
'model',
'provider',
@@ -30,6 +30,11 @@ class UsageLog extends Model
'error_message',
'timestamp',
'metadata',
'request_payload',
'response_payload',
'response_time_ms',
'ip_address',
'user_agent',
];
protected $casts = [
@@ -39,16 +44,15 @@ class UsageLog extends Model
'cost' => 'decimal:6',
'timestamp' => 'datetime',
'metadata' => 'array',
'request_payload' => 'array',
'response_payload' => 'array',
'response_time_ms' => 'integer',
];
public function user()
{
return $this->belongsTo(GatewayUser::class, 'user_id', 'user_id');
}
// Relationships
public function gatewayUser()
{
return $this->belongsTo(GatewayUser::class, 'user_id', 'user_id');
return $this->belongsTo(GatewayUser::class, 'gateway_user_id', 'user_id');
}
public function apiKey()
@@ -66,4 +70,19 @@ class UsageLog extends Model
{
return $query->where('status', 'failed');
}
public function scopeRecent($query, $days = 7)
{
return $query->where('timestamp', '>=', now()->subDays($days));
}
public function scopeByProvider($query, string $provider)
{
return $query->where('provider', $provider);
}
public function scopeByModel($query, string $model)
{
return $query->where('model', $model);
}
}