91 lines
2.2 KiB
PHP
91 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Livewire\Forms\Studio\Loyalty;
|
|
|
|
use App\Models\Tier;
|
|
use App\Rules\UnsignedInteger;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Livewire\Form;
|
|
|
|
class TierForm extends Form
|
|
{
|
|
public ?Tier $tier = null;
|
|
|
|
public string $name = '';
|
|
|
|
public string $min_points = '';
|
|
|
|
public ?string $max_points = null;
|
|
|
|
public function rules(): array
|
|
{
|
|
return [
|
|
'name' => ['required', 'string', 'max:50'],
|
|
'min_points' => ['required', new UnsignedInteger],
|
|
'max_points' => ['nullable', new UnsignedInteger, 'gte:min_points'],
|
|
];
|
|
}
|
|
|
|
public function withValidator($validator): void
|
|
{
|
|
$validator->after(function ($validator) {
|
|
$minPoints = parseRupiahToInt($this->min_points);
|
|
$maxPoints = $this->max_points ? parseRupiahToInt($this->max_points) : null;
|
|
$ignoreId = $this->tier?->id;
|
|
|
|
$tierErrors = Tier::validateTierPoints($minPoints, $maxPoints, $ignoreId);
|
|
|
|
foreach ($tierErrors as $error) {
|
|
$validator->errors()->add('min_points', $error);
|
|
}
|
|
});
|
|
}
|
|
|
|
public function validationAttributes(): array
|
|
{
|
|
return [
|
|
'name' => 'nama',
|
|
'min_points' => 'min. poin',
|
|
'max_points' => 'maks. poin',
|
|
];
|
|
}
|
|
|
|
public function setTier(Tier $tier): void
|
|
{
|
|
$this->tier = $tier;
|
|
|
|
$this->name = $tier->name;
|
|
$this->min_points = $tier->min_points;
|
|
$this->max_points = $tier->max_points;
|
|
}
|
|
|
|
public function store(): Tier
|
|
{
|
|
$this->validate();
|
|
|
|
return DB::transaction(function () {
|
|
return Tier::create($this->prepareSavedData());
|
|
});
|
|
}
|
|
|
|
public function update(): Tier
|
|
{
|
|
$this->validate();
|
|
|
|
return DB::transaction(function () {
|
|
$this->tier->update($this->prepareSavedData());
|
|
|
|
return $this->tier;
|
|
});
|
|
}
|
|
|
|
private function prepareSavedData(): array
|
|
{
|
|
return [
|
|
'name' => $this->name,
|
|
'min_points' => parseRupiahToInt($this->min_points),
|
|
'max_points' => parseRupiahToInt($this->max_points),
|
|
];
|
|
}
|
|
}
|