add alersts api

This commit is contained in:
2024-11-26 01:16:49 +05:00
parent 55060d1ad2
commit 5d5e269285
6 changed files with 116 additions and 1 deletions

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AlertController extends Controller
{
/**
* Get alerts for user
*/
public function index()
{
$alerstQuery = auth()->user()->alerts()->whereNull('seen_at');
$alerts = $alerstQuery->get();
$alerstQuery->update([
'seen_at' => now()
]);
return response()->json($this->format($alerts));
}
/**
* Format
*/
public function format($alerts)
{
return $alerts->map(fn ($alert) => [
'name' => $alert->name,
'value' => $alert->value,
]);
}
}

27
app/Models/Alert.php Normal file
View File

@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Alert extends Model
{
use HasFactory;
/**
* Casts
*/
protected $casts = [
'seen_at' => 'datetime'
];
/**
* User
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

View File

@@ -196,5 +196,14 @@ class LoanOrder extends Model
static::creating(LoanOrderRepo::creating());
static::created(LoanOrderRepo::created());
static::updated(function (LoanOrder $model) {
info($model->notes);
if ($model->notes && $model->wasChanged('notes')) {
auth()->user()->alerts()->create([
'name' => 'Duýdyryş',
'value' => $model->notes,
]);
}
});
}
}

View File

@@ -97,6 +97,14 @@ class User extends Authenticatable
return $this->hasMany(CardOrder::class);
}
/**
* Alerts
*/
public function alerts(): HasMany
{
return $this->hasMany(Alert::class);
}
/**
* Check if user has role.
*/

View File

@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('alerts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->text('name');
$table->text('value');
$table->timestamp('seen_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('alerts');
}
};

View File

@@ -1,5 +1,6 @@
<?php
use App\Http\Controllers\AlertController;
use App\Http\Controllers\Api\FetchLoanHistoryController;
use App\Http\Controllers\FetchCardHistoryController;
use App\Http\Controllers\MetricsController;
@@ -64,5 +65,6 @@ Route::middleware(['auth:sanctum', 'not_banned'])->group(function () {
Route::post('loan-order/{loanOrder}', [LoanOrderController::class, 'update']);
Route::delete('loan-order/{loanOrder}', [LoanOrderController::class, 'destroy']);
// Route::get('alerts', []);
// Alerts...
Route::get('alerts', [AlertController::class, 'index']);
});