store-manage/app/Models/Ledger.php

87 lines
2.2 KiB
PHP

<?php
namespace App\Models;
use App\Traits\HasCheckable;
use App\Traits\HasDateTimeFormatter;
use EloquentFilter\Filterable;
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\Relations\HasMany;
class Ledger extends Model
{
use Filterable, HasCheckable, HasDateTimeFormatter, HasFactory;
protected $appends = ['ledger_difference'];
protected $attributes = [
'new_customers' => 0,
'ledger_amount' => null,
'actual_commission' => null,
'actual_income' => null,
];
protected $fillable = [
'store_id',
'date',
'new_customers',
'sales',
'expenditure',
'handover_amount',
'ledger_amount',
'expected_commission',
'actual_commission',
'expected_income',
'actual_income',
'photos',
];
public function store(): BelongsTo
{
return $this->belongsTo(Store::class);
}
public function items(): HasMany
{
return $this->hasMany(LedgerItem::class);
}
/**
* 是否允许重新上报
*/
public function allowReReport(): bool
{
return is_null($this->ledger_amount) && is_null($this->actual_commission) && is_null($this->actual_income);
}
protected function ledgerDifference(): Attribute
{
return Attribute::make(
get: function (mixed $value, array $attributes) {
if (is_numeric($attributes['ledger_amount'])) {
return bcsub($attributes['handover_amount'], $attributes['ledger_amount'], 2);
}
return null;
},
);
}
protected function photos(): Attribute
{
return Attribute::make(
get: function (mixed $value) {
if (! is_array($photos = json_decode($value ?? '', true))) {
$photos = [];
}
return $photos;
},
set: fn (mixed $value) => json_encode(is_array($value) ? $value : []),
);
}
}