Files
database-pertani-web/app/Models/Concerns/CatatAktivitas.php
T
2026-11-05 17:06:11 +07:00

55 lines
2.0 KiB
PHP

<?php
namespace App\Models\Concerns;
use Illuminate\Support\Str;
use Spatie\Activitylog\Contracts\Activity;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
trait CatatAktivitas
{
use LogsActivity;
protected static array $kolomTidakDicatat = [
'created_by', 'updated_by', 'deleted_by', 'created_at', 'updated_at', 'deleted_at',
'password', 'remember_token', 'sync_status',
'foto', 'foto_url', 'path', 'path_kk', 'path_ktp', 'file_kk', 'file_ktp',
];
protected static array $kataEvent = [
'created' => 'ditambahkan',
'updated' => 'diubah',
'deleted' => 'dihapus',
'restored' => 'dipulihkan',
];
// Aturan log: kolom fillable yang berubah saja
public function getActivitylogOptions(): LogOptions
{
$label = property_exists($this, 'labelAktivitas') ? $this->labelAktivitas : Str::headline(class_basename($this));
$logName = property_exists($this, 'logAktivitas') ? $this->logAktivitas : Str::snake(explode('\\', static::class)[2]);
return LogOptions::defaults()
->useLogName($logName)
->logFillable()
->logExcept([...self::$kolomTidakDicatat, ...$this->getHidden()])
->dontLogIfAttributesChangedOnly(self::$kolomTidakDicatat)
->logOnlyDirty()
->dontSubmitEmptyLogs()
->setDescriptionForEvent(fn (string $event) => $label . ' ' . (self::$kataEvent[$event] ?? $event));
}
// Simpan nama data & petani terkait di log (halaman log tak perlu memuat data asli)
public function tapActivity(Activity $activity, string $eventName): void
{
$label = $this->getAttribute('nama') ?? $this->getAttribute('name');
$petaniId = $this->getAttribute('petani_id');
$activity->properties = $activity->properties->merge(array_filter([
'label' => is_string($label) ? Str::limit($label, 100) : null,
'petani_id' => $petaniId ? (int) $petaniId : null,
]));
}
}