95 lines
2.5 KiB
PHP
95 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Models\Concerns\HasModuleMedia;
|
|
use App\Models\Concerns\InteractsWithActivityLog;
|
|
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\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Spatie\MediaLibrary\HasMedia;
|
|
|
|
#[Guarded(['id'])]
|
|
#[Appends(['price_formatted', 'price_input', 'stock_formatted', 'stock_input'])]
|
|
class RawMaterialPrice extends Model implements HasMedia
|
|
{
|
|
// 1. Use Trait
|
|
use HasFactory, HasModuleMedia, InteractsWithActivityLog, SoftDeletes;
|
|
|
|
// 2. Casting
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'price' => 'integer',
|
|
'stock' => 'decimal:4',
|
|
];
|
|
}
|
|
|
|
// 3. Attribute
|
|
public function priceFormatted(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: fn () => 'Rp '.number_format($this->price, 0, ',', '.'),
|
|
);
|
|
}
|
|
|
|
public function priceInput(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: fn () => (string) $this->price,
|
|
);
|
|
}
|
|
|
|
public function stockFormatted(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: function () {
|
|
$formatted = rtrim(rtrim(number_format((float) $this->stock, 4, ',', '.'), '0'), ',');
|
|
$unitAbbreviation = $this->attributes['unit_abbreviation']
|
|
?? $this->rawMaterial?->unit?->abbreviation();
|
|
|
|
return "{$formatted} {$unitAbbreviation}";
|
|
},
|
|
);
|
|
}
|
|
|
|
public function stockInput(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: fn () => rtrim(rtrim(number_format((float) $this->stock, 4, '.', ''), '0'), '.'),
|
|
);
|
|
}
|
|
|
|
// 4. Other Methods
|
|
public static function mediaModuleName(): string
|
|
{
|
|
return 'raw-material';
|
|
}
|
|
|
|
public function registerMediaCollections(): void
|
|
{
|
|
$this->addMediaCollection('images');
|
|
}
|
|
|
|
// 5. Relation
|
|
public function cuttingMaterials(): HasMany
|
|
{
|
|
return $this->hasMany(CuttingMaterial::class);
|
|
}
|
|
|
|
public function purchaseItems(): HasMany
|
|
{
|
|
return $this->hasMany(PurchaseItem::class);
|
|
}
|
|
|
|
public function rawMaterial(): BelongsTo
|
|
{
|
|
return $this->belongsTo(RawMaterial::class);
|
|
}
|
|
}
|