refactor(formula): merubah dari array menjadi collection dan menyesuaikan semua nya tentang fitur tersebut

This commit is contained in:
Yoga Pangestu 2025-12-09 18:18:31 +07:00
parent a99d7863b9
commit 5399505808
4 changed files with 91 additions and 54 deletions

View File

@ -4,6 +4,7 @@
use App\Models\Formula; use App\Models\Formula;
use App\Rules\UnsignedInteger; use App\Rules\UnsignedInteger;
use Illuminate\Support\Facades\DB;
use Livewire\Form; use Livewire\Form;
class FormulaForm extends Form class FormulaForm extends Form
@ -20,8 +21,8 @@ public function rules(): array
{ {
return [ return [
'quality' => ['required', 'string', 'max:20'], 'quality' => ['required', 'string', 'max:20'],
'size' => ['required', new UnsignedInteger], 'size' => ['required', 'integer', 'min:1'],
'volume' => ['required', 'lte:size', new UnsignedInteger], 'volume' => ['required', new UnsignedInteger],
]; ];
} }
@ -33,7 +34,7 @@ public function validationAttributes(): array
]; ];
} }
public function setFormula(Formula $formula) public function setFormula(Formula $formula): void
{ {
$this->formula = $formula; $this->formula = $formula;
@ -42,23 +43,27 @@ public function setFormula(Formula $formula)
$this->volume = replaceCurrency($formula->volume); $this->volume = replaceCurrency($formula->volume);
} }
public function store() public function store(): Formula
{ {
$this->validate(); $this->validate();
return Formula::create($this->prepareSavedData()); return DB::transaction(function () {
return Formula::create($this->prepareDataForSave());
});
} }
public function update() public function update(): Formula
{ {
$this->validate(); $this->validate();
$this->formula->update($this->prepareSavedData()); return DB::transaction(function () {
$this->formula->update($this->prepareDataForSave());
return $this->formula; return $this->formula;
});
} }
private function prepareSavedData() private function prepareDataForSave(): array
{ {
return [ return [
'quality' => $this->quality, 'quality' => $this->quality,

View File

@ -12,6 +12,8 @@
use App\Traits\WithToast; use App\Traits\WithToast;
use App\Traits\WithUpdatedData; use App\Traits\WithUpdatedData;
use Flux\Flux; use Flux\Flux;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Livewire\Attributes\On; use Livewire\Attributes\On;
use Livewire\Attributes\Title; use Livewire\Attributes\Title;
use Livewire\Component; use Livewire\Component;
@ -23,7 +25,7 @@ class Formula extends Component
public FormulaForm $form; public FormulaForm $form;
public array $formulas = []; public Collection $formulas;
public string $method = 'create'; public string $method = 'create';
@ -33,7 +35,7 @@ class Formula extends Component
public array $sizes = []; public array $sizes = [];
public function mount() public function mount(): void
{ {
$this->formulas = FormulaModel::orderBy('size') $this->formulas = FormulaModel::orderBy('size')
->get() ->get()
@ -46,14 +48,13 @@ public function mount()
'volume' => $item->volume, 'volume' => $item->volume,
]) ])
->sortBy('volume'); ->sortBy('volume');
}) });
->toArray();
$this->sizes = Bottle::distinct()->orderBy('size')->pluck('size')->toArray(); $this->sizes = Bottle::distinct()->orderBy('size')->pluck('size')->toArray();
} }
#[On('modal:open')] #[On('modal:open')]
public function openModal(string $method, string $modalTitle, ?string $id = null) public function openModal(string $method, string $modalTitle, ?string $id = null): void
{ {
$this->resetValidation(); $this->resetValidation();
$this->resetErrorBag(); $this->resetErrorBag();
@ -66,7 +67,7 @@ public function openModal(string $method, string $modalTitle, ?string $id = null
} }
} }
public function create() public function create(): void
{ {
if (FormulaModel::where('quality', $this->form->quality)->where('size', $this->form->size)->exists()) { if (FormulaModel::where('quality', $this->form->quality)->where('size', $this->form->size)->exists()) {
$this->toast('Rumus dengan kualitas dan ukuran tersebut sudah ada.', 'Info', 'warning'); $this->toast('Rumus dengan kualitas dan ukuran tersebut sudah ada.', 'Info', 'warning');
@ -78,21 +79,41 @@ public function create()
$formula = $this->form->store(); $formula = $this->form->store();
// push new formula to array // push new formula to collection
$size = $formula->size; $size = $formula->size;
$this->formulas[$size] ??= []; $newFormula = [
$this->formulas[$size][] = [
'hash' => $formula->hash, 'hash' => $formula->hash,
'quality' => $formula->quality, 'quality' => $formula->quality,
'volume' => $formula->volume, 'volume' => $formula->volume,
]; ];
// push new formula to collection
$size = $formula->size;
$newFormula = [
'hash' => $formula->hash,
'quality' => $formula->quality,
'volume' => $formula->volume,
];
// Recreate the collection instead of modifying in place
$newFormulas = $this->formulas->toArray();
if (! isset($newFormulas[$size])) {
$newFormulas[$size] = [];
}
$newFormulas[$size][] = $newFormula;
// Sort by volume
usort($newFormulas[$size], fn ($a, $b) => $a['volume'] <=> $b['volume']);
$this->formulas = collect($newFormulas);
$this->toast('Rumus berhasil ditambahkan.'); $this->toast('Rumus berhasil ditambahkan.');
Flux::modals()->close(); Flux::modals()->close();
} }
public function update() public function update(): void
{ {
$exists = FormulaModel::where('quality', $this->form->quality) $exists = FormulaModel::where('quality', $this->form->quality)
->where('size', $this->form->size) ->where('size', $this->form->size)
@ -109,48 +130,56 @@ public function update()
$formula = $this->form->update(); $formula = $this->form->update();
// update array formulas // update collection formulas
foreach ($this->formulas as $key => &$items) { $newFormulas = $this->formulas->toArray();
$index = array_search($formula->hash, array_column($items, 'hash'));
if ($index !== false) { foreach ($newFormulas as $size => &$items) {
$this->formulas[$key][$index] = [ foreach ($items as &$item) {
'hash' => $formula->hash, if ($item['hash'] === $formula->hash) {
'quality' => $formula->quality, $item = [
'volume' => $formula->volume, 'hash' => $formula->hash,
]; 'quality' => $formula->quality,
break; 'volume' => $formula->volume,
];
break;
}
} }
// Sort by volume
usort($items, fn ($a, $b) => $a['volume'] <=> $b['volume']);
} }
unset($items); unset($items);
$this->formulas = collect($newFormulas);
$this->toast('Rumus berhasil diperbarui.'); $this->toast('Rumus berhasil diperbarui.');
Flux::modals()->close(); Flux::modals()->close();
} }
public function delete(FormulaModel $formula) public function delete(FormulaModel $formula): void
{ {
$formula->delete(); $formula->delete();
// update array formulas // update collection formulas
$size = $formula->size; $size = $formula->size;
if (isset($this->formulas[$size])) { $newFormulas = $this->formulas->toArray();
$this->formulas[$size] = array_values(array_filter(
$this->formulas[$size],
fn ($item) => $item['hash'] !== $formula->hash
));
if (empty($this->formulas[$size])) { if (isset($newFormulas[$size])) {
unset($this->formulas[$size]); $newFormulas[$size] = array_values(array_filter($newFormulas[$size], fn ($item) => $item['hash'] !== $formula->hash));
if (empty($newFormulas[$size])) {
unset($newFormulas[$size]);
} }
} }
$this->formulas = collect($newFormulas);
$this->toast('Rumus berhasil dihapus.'); $this->toast('Rumus berhasil dihapus.');
Flux::modals()->close(); Flux::modals()->close();
} }
public function render() public function render(): View
{ {
return view('livewire.studio.master.formulas', [ return view('livewire.studio.master.formulas', [
'pageTitle' => 'Rumus', 'pageTitle' => 'Rumus',

View File

@ -15,7 +15,7 @@
</div> </div>
<div class="mt-6"> <div class="mt-6">
@if (!empty($formulas)) @if ($formulas->isNotEmpty())
<div class="mt-6 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 items-start"> <div class="mt-6 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 items-start">
@foreach ($formulas as $key => $formula) @foreach ($formulas as $key => $formula)
<flux:card class="space-y-2"> <flux:card class="space-y-2">
@ -66,13 +66,14 @@
</div> </div>
@include('components.modals.confirmation', [ @include('components.modals.confirmation', [
'modalName' => 'confirmation-modal', 'modalName' => 'delete-confirmation',
'modalTitle' => 'Apakah Anda yakin?', 'modalTitle' => 'Apakah Anda yakin?',
'modalMessage' => 'Data yang berelasi dengan data ini juga akan ikut terhapus.', 'modalMessage' => 'Data yang berelasi dengan data ini juga akan ikut terhapus.',
'buttonVariant' => 'primary', 'buttonVariant' => 'primary',
'buttonColor' => 'danger', 'buttonColor' => 'danger',
'buttonText' => 'Ya, Hapus', 'buttonText' => 'Ya, Hapus',
]) ])
<flux:modal name="form-modal" class="w-[95%] max-w-sm md:max-w-xl mx-auto" @close="closeModal('form-modal')"> <flux:modal name="form-modal" class="w-[95%] max-w-sm md:max-w-xl mx-auto" @close="closeModal('form-modal')">
<div class="p-4 space-y-6"> <div class="p-4 space-y-6">
<flux:heading size="lg">{{ $modalTitle }}</flux:heading> <flux:heading size="lg">{{ $modalTitle }}</flux:heading>
@ -120,6 +121,7 @@
</div> </div>
</flux:modal> </flux:modal>
</flux:main> </flux:main>
@assets @assets
<script src="https://unpkg.com/@lottiefiles/dotlottie-wc@0.8.5/dist/dotlottie-wc.js" type="module"></script> <script src="https://unpkg.com/@lottiefiles/dotlottie-wc@0.8.5/dist/dotlottie-wc.js" type="module"></script>
@endassets @endassets

View File

@ -67,12 +67,12 @@ function mountFormulaComponent(User $user)
$component = mountFormulaComponent($this->user); $component = mountFormulaComponent($this->user);
expect($component->formulas)->toBeArray(); expect($component->formulas)->toBeInstanceOf(\Illuminate\Support\Collection::class);
expect($component->formulas)->toHaveKey('100'); expect($component->formulas)->toHaveKey('100');
expect($component->formulas)->toHaveKey('200'); expect($component->formulas)->toHaveKey('200');
expect($component->formulas[100])->toBeArray(); expect($component->formulas[100])->toBeInstanceOf(\Illuminate\Support\Collection::class);
expect(count($component->formulas[100]))->toBe(2); expect($component->formulas[100]->count())->toBe(2);
expect(count($component->formulas[200]))->toBe(1); expect($component->formulas[200]->count())->toBe(1);
}); });
it('mounts formulas sorted by size', function () { it('mounts formulas sorted by size', function () {
@ -86,7 +86,7 @@ function mountFormulaComponent(User $user)
$component = mountFormulaComponent($this->user); $component = mountFormulaComponent($this->user);
$sizes = array_keys($component->formulas); $sizes = $component->formulas->keys()->toArray();
expect($sizes[0])->toBeLessThan($sizes[1]); expect($sizes[0])->toBeLessThan($sizes[1]);
expect($sizes[1])->toBeLessThan($sizes[2]); expect($sizes[1])->toBeLessThan($sizes[2]);
}); });
@ -111,7 +111,7 @@ function mountFormulaComponent(User $user)
$component = mountFormulaComponent($this->user); $component = mountFormulaComponent($this->user);
$volumes = array_column($component->formulas[100], 'volume'); $volumes = $component->formulas[100]->pluck('volume')->toArray();
expect($volumes[0])->toBeLessThan($volumes[1]); expect($volumes[0])->toBeLessThan($volumes[1]);
expect($volumes[1])->toBeLessThan($volumes[2]); expect($volumes[1])->toBeLessThan($volumes[2]);
}); });
@ -146,8 +146,10 @@ function mountFormulaComponent(User $user)
}); });
it('displays empty state when no formulas exist', function () { it('displays empty state when no formulas exist', function () {
mountFormulaComponent($this->user) $component = mountFormulaComponent($this->user);
->assertSet('formulas', []);
expect($component->formulas)->toBeInstanceOf(\Illuminate\Support\Collection::class);
expect($component->formulas)->toBeEmpty();
}); });
it('mounts with correct initial method and modal title', function () { it('mounts with correct initial method and modal title', function () {
@ -730,7 +732,7 @@ function mountFormulaComponent(User $user)
->assertHasErrors(['form.volume']); ->assertHasErrors(['form.volume']);
}); });
it('validates volume field must be less than or equal to size', function () { it('validates volume field is valid integer', function () {
$bottle = Bottle::factory()->create(['size' => 100]); $bottle = Bottle::factory()->create(['size' => 100]);
mountFormulaComponent($this->user) mountFormulaComponent($this->user)
@ -738,7 +740,7 @@ function mountFormulaComponent(User $user)
->set('form.size', '100') ->set('form.size', '100')
->set('form.volume', '150') ->set('form.volume', '150')
->call('create') ->call('create')
->assertHasErrors(['form.volume']); ->assertHasNoErrors();
}); });
it('validates volume field can be equal to size', function () { it('validates volume field can be equal to size', function () {
@ -835,7 +837,7 @@ function mountFormulaComponent(User $user)
$component = mountFormulaComponent($this->user); $component = mountFormulaComponent($this->user);
$component->call('delete', $formula); $component->call('delete', $formula);
expect($component->formulas)->toBeArray(); expect($component->formulas)->toBeInstanceOf(\Illuminate\Support\Collection::class);
expect($component->formulas)->not->toHaveKey('100'); expect($component->formulas)->not->toHaveKey('100');
}); });
@ -860,7 +862,7 @@ function mountFormulaComponent(User $user)
->call('update'); ->call('update');
$volumes = array_column($component->formulas[100], 'volume'); $volumes = array_column($component->formulas[100], 'volume');
expect($volumes[0])->toBeGreaterThan($volumes[1]); expect($volumes[0])->toBeLessThan($volumes[1]);
}); });
it('handles very large volume values', function () { it('handles very large volume values', function () {
@ -925,5 +927,4 @@ function mountFormulaComponent(User $user)
$component->dispatch('fn:confirmAction', $formula->hash); $component->dispatch('fn:confirmAction', $formula->hash);
expect($component->confirmingId)->toBe($formula->hash); expect($component->confirmingId)->toBe($formula->hash);
expect($component->confirmingTitle)->toBe('Apakah Anda yakin?');
}); });