dress/app/Models/ProductPrice.php

99 lines
2.7 KiB
PHP

<?php
namespace App\Models;
use App\Enums\PriceType;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Traits\LogsActivity;
#[Guarded(['id'])]
#[Appends(['price_formatted', 'price_type_label'])]
class ProductPrice extends Model
{
use LogsActivity;
protected function casts(): array
{
return [
'price_type' => PriceType::class,
'price' => 'integer',
];
}
protected function priceTypeLabel(): Attribute
{
return Attribute::make(
get: fn () => $this->price_type->label(),
);
}
protected function priceFormatted(): Attribute
{
return Attribute::make(
get: fn () => 'Rp '.number_format($this->price, 0, ',', '.'),
);
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['price_type', 'price'])
->logOnlyDirty()
->useLogName('Harga Produk');
}
public function tapActivity(Activity $activity, string $eventName)
{
$activity->description = match ($eventName) {
'created' => 'TAMBAH',
'updated' => 'UBAH',
'deleted' => 'HAPUS',
default => $activity->description,
};
if (isset($activity->properties['attributes'])) {
$attributeMap = [
'price_type' => 'Jenis Harga',
'price' => 'Harga',
];
$properties = $activity->properties->toArray();
$localizeValues = function ($attrs) use ($attributeMap) {
$newAttrs = [];
foreach ($attrs as $key => $value) {
$label = $attributeMap[$key] ?? $key;
$displayValue = $value;
if ($key === 'price_type' && $value instanceof \BackedEnum) {
$displayValue = $value->value;
}
$newAttrs[$label] = $displayValue;
}
return $newAttrs;
};
$properties['attributes'] = $localizeValues($properties['attributes']);
if (isset($properties['old'])) {
$properties['old'] = $localizeValues($properties['old']);
}
$activity->properties = collect($properties);
}
}
}