store/app/Models/CuttingMaterial.php
Yoga Pangestu 15e2b7ec5b
Some checks are pending
linter / quality (push) Waiting to run
tests / ci (8.3) (push) Waiting to run
tests / ci (8.4) (push) Waiting to run
tests / ci (8.5) (push) Waiting to run
feat: add material_result field to CuttingMaterial and CuttingMaterialCombination; update validation rules and service logic to handle new material result calculations; enhance frontend components for displaying material results in cutting management
2026-07-04 23:14:37 +07:00

102 lines
2.6 KiB
PHP

<?php
namespace App\Models;
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\SoftDeletes;
#[Guarded(['id'])]
#[Appends([
'material_usage_formatted',
'material_usage_input',
'unit_abbreviation',
])]
class CuttingMaterial extends Model
{
// 1. Use Trait
use HasFactory, InteractsWithActivityLog, SoftDeletes;
// 2. Casting
protected function casts(): array
{
return [
'material_usage' => 'decimal:4',
'material_result' => 'integer',
];
}
// 3. Attribute
public function materialUsageFormatted(): Attribute
{
return Attribute::make(
get: fn () => $this->formatQuantity($this->material_usage),
);
}
public function materialUsageInput(): Attribute
{
return Attribute::make(
get: fn () => $this->formatQuantityInput($this->material_usage),
);
}
public function unitAbbreviation(): Attribute
{
return Attribute::make(
get: fn () => $this->attributes['unit_abbreviation']
?? $this->rawMaterialPrice?->rawMaterial?->unit?->abbreviation(),
);
}
// 4. Other Methods
public function materialCost(): int
{
$price = $this->rawMaterialPrice;
if ($price === null) {
return 0;
}
return (int) round((float) $this->material_usage * (int) $price->price);
}
private function formatQuantity(float|string|null $value): string
{
$formatted = rtrim(rtrim(number_format((float) $value, 4, ',', '.'), '0'), ',');
return "{$formatted} {$this->unitAbbreviation}";
}
private function formatQuantityInput(float|string|null $value): string
{
return rtrim(rtrim(number_format((float) $value, 4, '.', ''), '0'), '.');
}
// 5. Relation
public function cutting(): BelongsTo
{
return $this->belongsTo(Cutting::class);
}
public function rawMaterialPrice(): BelongsTo
{
return $this->belongsTo(RawMaterialPrice::class);
}
public function combination(): BelongsTo
{
return $this->belongsTo(CuttingMaterialCombination::class, 'combination_id');
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}