*/ use HasFactory, SerializesIdToUuid; 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 id}>." : "Suggestion was created by 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' => "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' => "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)); // Trigger the real-time creation broadcast dynamically broadcast(new \App\Events\MutationCreated($mutation)); }); static::updated(function (Mutation $mutation) { if ($mutation->wasChanged('status')) { broadcast(new \App\Events\MutationUpdated($mutation)); } }); } protected $appends = ['can']; public function getCanAttribute(): array { return [ 'update' => auth()->user()?->can('update', $this) ?? false, 'void' => auth()->user()?->can('void', $this) ?? false, ]; } public function getRouteKeyName() { return 'uuid'; } }