106 lines
2.9 KiB
PHP
106 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Attributes\Appends;
|
|
use Illuminate\Database\Eloquent\Attributes\Guarded;
|
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Spatie\Activitylog\LogOptions;
|
|
use Spatie\Activitylog\Models\Activity;
|
|
use Spatie\Activitylog\Traits\LogsActivity;
|
|
|
|
#[Guarded(['id'])]
|
|
#[Appends(['unit_price_formatted', 'total_price_formatted'])]
|
|
class PurchaseItem extends Model
|
|
{
|
|
use HasFactory, LogsActivity, SoftDeletes;
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'quantity' => 'integer',
|
|
'unit_price' => 'integer',
|
|
'total_price' => 'integer',
|
|
];
|
|
}
|
|
|
|
protected function unitPriceFormatted(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: fn () => 'Rp '.number_format($this->unit_price, 0, ',', '.'),
|
|
);
|
|
}
|
|
|
|
protected function totalPriceFormatted(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: fn () => 'Rp '.number_format($this->total_price, 0, ',', '.'),
|
|
);
|
|
}
|
|
|
|
public function purchase(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Purchase::class);
|
|
}
|
|
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
public function product(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Product::class);
|
|
}
|
|
|
|
public function getActivitylogOptions(): LogOptions
|
|
{
|
|
return LogOptions::defaults()
|
|
->logOnly(['quantity', 'unit_price', 'total_price'])
|
|
->logOnlyDirty()
|
|
->useLogName('Item Pembelian');
|
|
}
|
|
|
|
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 = [
|
|
'quantity' => 'Jumlah',
|
|
'unit_price' => 'Harga Satuan',
|
|
'total_price' => 'Total Harga',
|
|
];
|
|
|
|
$properties = $activity->properties->toArray();
|
|
|
|
$localizeValues = function ($attrs) use ($attributeMap) {
|
|
$newAttrs = [];
|
|
foreach ($attrs as $key => $value) {
|
|
$label = $attributeMap[$key] ?? $key;
|
|
$newAttrs[$label] = $value;
|
|
}
|
|
|
|
return $newAttrs;
|
|
};
|
|
|
|
$properties['attributes'] = $localizeValues($properties['attributes']);
|
|
|
|
if (isset($properties['old'])) {
|
|
$properties['old'] = $localizeValues($properties['old']);
|
|
}
|
|
|
|
$activity->properties = collect($properties);
|
|
}
|
|
}
|
|
}
|