103 lines
3.1 KiB
PHP
103 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Events\MessageSent;
|
|
use Database\Factories\MutationFactory;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
|
use Illuminate\Database\Eloquent\Relations\MorphOne;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Mutation extends Model
|
|
{
|
|
/** @use HasFactory<MutationFactory> */
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'ledger_id',
|
|
'user_id',
|
|
'type',
|
|
'amount',
|
|
'description',
|
|
'status',
|
|
'predefined_mutation_id',
|
|
];
|
|
|
|
public function ledger(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Ledger::class);
|
|
}
|
|
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
public function predefinedMutation(): BelongsTo
|
|
{
|
|
return $this->belongsTo(PredefinedMutation::class);
|
|
}
|
|
|
|
public function chat(): MorphOne
|
|
{
|
|
return $this->morphOne(Chat::class, 'chatable');
|
|
}
|
|
|
|
public function media(): MorphMany
|
|
{
|
|
return $this->morphMany(Media::class, 'mediable');
|
|
}
|
|
|
|
protected static function booted(): void
|
|
{
|
|
static::creating(function ($model) {
|
|
$model->uuid = (string) Str::uuid();
|
|
});
|
|
|
|
static::created(function (Mutation $mutation) {
|
|
$mutation->chat()->create([]);
|
|
|
|
// Create system messages automatically!
|
|
$user = $mutation->user;
|
|
$ledger = $mutation->ledger;
|
|
$dynamic = $ledger->dynamic;
|
|
$status = $mutation->status;
|
|
|
|
$mutationMsg = $mutation->chat->messages()->create([
|
|
'user_id' => null,
|
|
'content' => $status === 'approved'
|
|
? "Entry was created by <user:{$user->id}>."
|
|
: "Suggestion was created by <user:{$user->id}>.",
|
|
'subject_id' => $mutation->id,
|
|
'subject_type' => Mutation::class,
|
|
]);
|
|
broadcast(new MessageSent($mutationMsg));
|
|
|
|
if ($status === 'approved') {
|
|
$dynamicMsg = $dynamic->chat->messages()->create([
|
|
'user_id' => null,
|
|
'content' => "<user:{$user->id}> added entry \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger.",
|
|
'subject_id' => $mutation->id,
|
|
'subject_type' => Mutation::class,
|
|
]);
|
|
} else {
|
|
$dynamicMsg = $dynamic->chat->messages()->create([
|
|
'user_id' => null,
|
|
'content' => "<user:{$user->id}> suggested \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger.",
|
|
'subject_id' => $mutation->id,
|
|
'subject_type' => Mutation::class,
|
|
]);
|
|
}
|
|
broadcast(new MessageSent($dynamicMsg));
|
|
});
|
|
}
|
|
|
|
public function getRouteKeyName()
|
|
{
|
|
return 'uuid';
|
|
}
|
|
}
|