store/app/Models/CashTransaction.php

113 lines
2.7 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\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
#[Guarded(['id'])]
#[Appends([
'amount_formatted',
'balance_after_formatted',
'reference_label',
'is_incoming',
'created_at_formatted',
'created_by_name',
])]
class CashTransaction extends Model
{
use SoftDeletes;
protected function casts(): array
{
return [
'amount' => 'integer',
'balance_after' => 'integer',
];
}
public function amountFormatted(): Attribute
{
return Attribute::make(
get: fn () => 'Rp '.number_format($this->amount, 0, ',', '.'),
);
}
public function balanceAfterFormatted(): Attribute
{
return Attribute::make(
get: fn () => 'Rp '.number_format($this->balance_after, 0, ',', '.'),
);
}
public function referenceLabel(): Attribute
{
return Attribute::make(
get: fn () => self::labelForReferenceType($this->reference_type),
);
}
public function isIncoming(): Attribute
{
return Attribute::make(
get: fn () => self::isIncomingReference($this->reference_type),
);
}
public function createdAtFormatted(): Attribute
{
return Attribute::make(
get: fn () => $this->created_at?->translatedFormat('l, d F Y H:i'),
);
}
public function createdByName(): Attribute
{
return Attribute::make(
get: fn () => $this->createdBy?->profile?->full_name ?? $this->createdBy?->username,
);
}
public static function labelForReferenceType(?string $referenceType): string
{
if ($referenceType === null) {
return 'Setor Kas';
}
return match ($referenceType) {
default => class_basename($referenceType),
};
}
public static function isIncomingReference(?string $referenceType): bool
{
if ($referenceType === null) {
return true;
}
return match ($referenceType) {
default => false,
};
}
public function cashAccount(): BelongsTo
{
return $this->belongsTo(CashAccount::class);
}
public function createdBy(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by_id');
}
public function reference(): MorphTo
{
return $this->morphTo();
}
}