feat: Refactor egg collection management by consolidating pages and updating form structure

This commit is contained in:
Yoga Pangestu 2026-02-25 22:35:26 +07:00
parent 156efedc2e
commit 75712c4f2a
14 changed files with 132 additions and 524 deletions

View File

@ -2,16 +2,26 @@
namespace App\Filament\Resources\Manage\EggCollections;
use App\Filament\Resources\Manage\EggCollections\Pages\CreateEggCollection;
use App\Filament\Resources\Manage\EggCollections\Pages\EditEggCollection;
use App\Filament\Resources\Manage\EggCollections\Pages\ListEggCollections;
use App\Filament\Resources\Manage\EggCollections\Schemas\EggCollectionForm;
use App\Filament\Resources\Manage\EggCollections\Tables\EggCollectionsTable;
use App\Enums\RoleEnum;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use App\Filament\Resources\Manage\EggCollections\Pages\ManageEggCollections;
use App\Models\EggCollection;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use UnitEnum;
@ -33,20 +43,97 @@ class EggCollectionResource extends Resource
public static function form(Schema $schema): Schema
{
return EggCollectionForm::configure($schema);
return $schema
->components([
Hidden::make('production_date')
->default(now()),
TextInput::make('total_eggs')
->label('Jumlah Telur')
->placeholder('0')
->autocomplete(false)
->required()
->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
->dehydrateStateUsing(fn ($state) => (int) str()->replace(',', '', (string) ($state ?? 0))),
TextInput::make('total_broken_eggs')
->label('Jumlah Telur Pecah')
->placeholder('0')
->autocomplete(false)
->required()
->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
->dehydrateStateUsing(fn ($state) => (int) str()->replace(',', '', (string) ($state ?? 0))),
Textarea::make('notes')
->label('Catatan')
->placeholder('...')
->columnSpanFull(),
])
->columns(1);
}
public static function table(Table $table): Table
{
return EggCollectionsTable::configure($table);
return $table
->columns([
TextColumn::make('production_date')
->label('Tanggal Produksi')
->dateTime('l, d F Y H:i')
->searchable()
->sortable(),
TextColumn::make('total_eggs')
->label('Total Telur')
->numeric()
->searchable()
->sortable(),
TextColumn::make('total_broken_eggs')
->label('Total Telur Pecah')
->numeric()
->searchable()
->sortable(),
TextColumn::make('notes')
->label('Catatan')
->searchable()
->wrap()
->toggleable(),
...TimestampColumns::make(),
])
->filters([
TrashedFilter::make()
->native(false)
->visible(fn (): bool => auth()->user()->hasRole(RoleEnum::DEVELOPER)),
])
->recordActions([
EditAction::make()
->label('Ubah')
->modalWidth(Width::Large)
->modalHeading(fn (EggCollection $record): string => 'Ubah '.$record->production_date->translatedFormat('l, d F Y H:i')),
DeleteAction::make(),
ForceDeleteAction::make(),
RestoreAction::make(),
])
->toolbarActions([
BulkActionGroup::make([
...DefaultBulkActions::make('Produksi Telur'),
]),
])
->emptyStateIcon(Heroicon::RectangleGroup)
->emptyStateDescription('Setelah Anda membuat data pertama, maka akan muncul disini.')
->defaultSort('created_at', 'desc')
->deferFilters(false);
}
public static function getPages(): array
{
return [
'index' => ListEggCollections::route('/'),
'create' => CreateEggCollection::route('/create'),
'edit' => EditEggCollection::route('/{record}/edit'),
'index' => ManageEggCollections::route('/'),
];
}
}

View File

@ -1,67 +0,0 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Pages;
use App\Filament\Actions\BackAction;
use App\Filament\Resources\Manage\EggCollections\EggCollectionResource;
use App\Filament\Resources\Manage\EggCollections\Traits\HasEggs;
use App\Models\EggCollectionItem;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
class CreateEggCollection extends CreateRecord
{
use HasEggs;
protected static string $resource = EggCollectionResource::class;
protected ?string $heading = 'Tambah Produksi Telur';
protected static ?string $title = 'Tambah Produksi Telur';
protected function getHeaderActions(): array
{
return [
BackAction::make()
->url(ListEggCollections::getUrl()),
];
}
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('index');
}
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['total_eggs'] = array_sum($this->eggs ?? []);
$data['production_date'] = now();
return $data;
}
protected function afterCreate(): void
{
foreach ($this->eggs as $chickenId => $eggsCount) {
if ($eggsCount <= 0) {
continue;
}
EggCollectionItem::create([
'egg_collection_id' => $this->record->id,
'chicken_id' => $chickenId,
'eggs_count' => $eggsCount,
]);
}
$this->eggs = [];
}
protected function getCreatedNotification(): ?Notification
{
return Notification::make()
->title('Data Berhasil Disimpan')
->body('Data baru telah berhasil ditambahkan dan disimpan oleh sistem.')
->success();
}
}

View File

@ -1,76 +0,0 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Pages;
use App\Filament\Actions\BackAction;
use App\Filament\Resources\Manage\EggCollections\EggCollectionResource;
use App\Filament\Resources\Manage\EggCollections\Traits\HasEggs;
use App\Models\EggCollectionItem;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
class EditEggCollection extends EditRecord
{
use HasEggs;
protected static string $resource = EggCollectionResource::class;
protected ?string $heading = 'Ubah Produksi Telur';
protected static ?string $title = 'Ubah Produksi Telur';
public function mount($record): void
{
parent::mount($record);
$this->eggs = $this->record->items()
->pluck('eggs_count', 'chicken_id')
->map(fn ($count) => (int) $count)
->toArray();
}
protected function getHeaderActions(): array
{
return [
BackAction::make()
->url(ListEggCollections::getUrl()),
];
}
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('index');
}
protected function mutateFormDataBeforeSave(array $data): array
{
$data['total_eggs'] = array_sum($this->eggs ?? []);
return $data;
}
protected function afterSave(): void
{
EggCollectionItem::where('egg_collection_id', $this->record->id)->delete();
foreach ($this->eggs as $chickenId => $eggsCount) {
if ($eggsCount <= 0) {
continue;
}
EggCollectionItem::create([
'egg_collection_id' => $this->record->id,
'chicken_id' => $chickenId,
'eggs_count' => $eggsCount,
]);
}
}
protected function getSavedNotification(): ?Notification
{
return Notification::make()
->title('Perubahan Berhasil Disimpan')
->body('Perubahan pada data telah berhasil disimpan dan diperbarui di sistem.')
->success();
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Pages;
use App\Filament\Actions\Cheerful\CreateAction;
use App\Filament\Resources\Manage\EggCollections\EggCollectionResource;
use Filament\Resources\Pages\ListRecords;
class ListEggCollections extends ListRecords
{
protected static string $resource = EggCollectionResource::class;
protected static ?string $title = 'Produksi Telur';
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->label('Tambah'),
];
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Pages;
use App\Filament\Actions\Cheerful\CreateAction;
use App\Filament\Resources\Manage\EggCollections\EggCollectionResource;
use Filament\Resources\Pages\ManageRecords;
use Filament\Support\Enums\Width;
class ManageEggCollections extends ManageRecords
{
protected static string $resource = EggCollectionResource::class;
protected static ?string $title = 'Produksi Telur';
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->label('Tambah')
->modalHeading('Tambah Produksi Telur')
->modalSubmitActionLabel('Simpan')
->modalCancelActionLabel('Batal')
->extraModalFooterActions(fn (CreateAction $action): array => [
$action->makeModalSubmitAction('createAnother', arguments: ['another' => true])
->label('Simpan dan Tambah Lagi'),
])
->modalWidth(Width::Large),
];
}
}

View File

@ -1,63 +0,0 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Schemas;
use App\Enums\ChickenStatus;
use App\Models\Chicken;
use Filament\Forms\Components\Textarea;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\View;
use Filament\Schemas\Schema;
use Illuminate\Support\Facades\Cache;
class EggCollectionForm
{
public static function configure(Schema $schema): Schema
{
$chickens = Cache::store('redis')->remember(
'active_chickens_for_egg_collection_form',
now()->addMinutes(10),
function () {
return Chicken::query()
->where('status', ChickenStatus::ACTIVE)
->orderBy('tag_code')
->get();
}
);
return $schema
->components([
Section::make('Informasi Produksi')
->schema([
Grid::make(3)
->schema([
Textarea::make('notes')
->label('Catatan')
->placeholder('...')
->columnSpanFull(),
]),
])
->collapsible(),
Grid::make([
'default' => 1,
'lg' => 3,
])
->schema([
Section::make('Daftar Ayam')
->schema([
View::make('filament.resources.manage.egg-collections.chicken-eggs-grid')
->viewData([
'chickens' => $chickens,
]),
])
->columnSpan([
'default' => 1,
'lg' => 3,
]),
]),
])
->columns(1);
}
}

View File

@ -1,108 +0,0 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Tables;
use App\Enums\RoleEnum;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\ViewAction;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Section;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
class EggCollectionsTable
{
public static function configure(Table $table): Table
{
return $table
->columns([
TextColumn::make('production_date')
->label('Tanggal Produksi')
->dateTime('l, d F Y H:i')
->searchable()
->sortable(),
TextColumn::make('total_eggs')
->label('Total Telur')
->numeric()
->searchable()
->sortable(),
TextColumn::make('notes')
->label('Catatan')
->searchable()
->wrap()
->toggleable(),
...TimestampColumns::make(),
])
->filters([
TrashedFilter::make()
->native(false)
->visible(fn (): bool => auth()->user()->hasRole(RoleEnum::DEVELOPER)),
])
->recordActions([
EditAction::make()
->label('Ubah'),
ViewAction::make()
->label('Detail')
->color('gray')
->modalHeading('Detail Produksi Telur')
->modalWidth(Width::Large)
->schema([
Section::make('Ringkasan')
->schema([
TextEntry::make('production_date')
->label('Waktu Produksi')
->dateTime('l, d F Y H:i'),
TextEntry::make('total_eggs')
->label('Total Telur'),
TextEntry::make('notes')
->label('Catatan')
->placeholder('-')
->columnSpanFull(),
RepeatableEntry::make('items')
->label('Daftar Ayam')
->schema([
TextEntry::make('chicken.tag_code')
->label('Kode Ayam')
->placeholder('-'),
TextEntry::make('eggs_count')
->label('Jumlah Telur'),
])
->columns(2),
]),
]),
DeleteAction::make(),
ForceDeleteAction::make(),
RestoreAction::make(),
])
->toolbarActions([
BulkActionGroup::make([
...DefaultBulkActions::make('Produksi Telur'),
]),
])
->emptyStateIcon(Heroicon::RectangleGroup)
->emptyStateDescription('Setelah Anda membuat data pertama, maka akan muncul disini.')
->defaultSort('created_at', 'desc')
->deferFilters(false);
}
}

View File

@ -1,46 +0,0 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Traits;
trait HasEggs
{
/**
* [chicken_id => eggs_count]
*/
public array $eggs = [];
public function addEgg(int $chickenId): void
{
$current = $this->eggs[$chickenId] ?? 0;
$this->eggs[$chickenId] = $current + 1;
$this->syncTotalEggsFromState();
}
public function decreaseEgg(int $chickenId): void
{
$current = $this->eggs[$chickenId] ?? 0;
if ($current <= 0) {
return;
}
$new = $current - 1;
if ($new > 0) {
$this->eggs[$chickenId] = $new;
} else {
unset($this->eggs[$chickenId]);
}
$this->syncTotalEggsFromState();
}
protected function syncTotalEggsFromState(): void
{
$total = array_sum($this->eggs);
$this->form->fill([
...$this->form->getState(),
'total_eggs' => $total,
]);
}
}

View File

@ -4,7 +4,6 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class EggCollection extends Model
@ -18,11 +17,7 @@ protected function casts(): array
return [
'production_date' => 'datetime',
'total_eggs' => 'integer',
'total_broken_eggs' => 'integer',
];
}
public function items(): HasMany
{
return $this->hasMany(EggCollectionItem::class);
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
class EggCollectionItem extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
protected function casts(): array
{
return [
'eggs_count' => 'integer',
];
}
public function collection(): BelongsTo
{
return $this->belongsTo(EggCollection::class, 'egg_collection_id');
}
public function chicken(): BelongsTo
{
return $this->belongsTo(Chicken::class);
}
}

View File

@ -2,9 +2,7 @@
namespace Database\Factories;
use App\Models\Chicken;
use App\Models\EggCollection;
use App\Models\EggCollectionItem;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
@ -20,45 +18,9 @@ public function definition(): array
return [
'production_date' => $dateTime,
'total_eggs' => 0,
'total_eggs' => fake()->numberBetween(500, 1500),
'total_broken_eggs' => fake()->numberBetween(0, 100),
'notes' => $this->faker->optional(0.4)->sentence(),
];
}
public function configure()
{
return $this->afterCreating(function (EggCollection $collection) {
$chickens = Chicken::where('status', 'ACTIVE')
->inRandomOrder()
->take(20)
->get();
if ($chickens->isEmpty()) {
$chickens = Chicken::factory()->count(20)->create();
}
$itemCount = $this->faker->numberBetween(5, min(20, $chickens->count()));
$selectedChickens = $chickens->shuffle()->take($itemCount);
$totalEggs = 0;
foreach ($selectedChickens as $chicken) {
$eggsCount = $this->faker->numberBetween(0, 2);
if ($eggsCount <= 0) {
continue;
}
EggCollectionItem::create([
'egg_collection_id' => $collection->id,
'chicken_id' => $chicken->id,
'eggs_count' => $eggsCount,
]);
$totalEggs += $eggsCount;
}
$collection->update(['total_eggs' => $totalEggs]);
});
}
}

View File

@ -12,6 +12,7 @@ public function up(): void
$table->id();
$table->dateTime('production_date');
$table->unsignedInteger('total_eggs')->default(0);
$table->unsignedInteger('total_broken_eggs')->default(0);
$table->text('notes')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable()->useCurrentOnUpdate();

View File

@ -1,26 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('egg_collection_items', function (Blueprint $table) {
$table->id();
$table->foreignId('egg_collection_id')->constrained()->cascadeOnDelete();
$table->foreignId('chicken_id')->constrained()->cascadeOnDelete();
$table->unsignedInteger('eggs_count');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable()->useCurrentOnUpdate();
$table->softDeletes();
});
}
public function down(): void
{
Schema::dropIfExists('egg_collection_items');
}
};

View File

@ -1,29 +0,0 @@
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-5">
@foreach ($chickens as $chicken)
<div class="border rounded-xl bg-white shadow-sm hover:shadow-md transition overflow-hidden">
<div class="p-4 flex items-center justify-between gap-4">
<div class="font-semibold">
{{ $chicken->tag_code }}
</div>
<div class="flex items-center justify-end gap-3">
<a href="javascript:void(0)" wire:click="decreaseEgg({{ $chicken->id }})"
class="w-8 h-8 rounded-full border border-gray-200 flex items-center justify-center text-lg hover:bg-gray-50 transition-colors">
-
</a>
<span class="text-sm font-bold w-6 text-center">
{{ $this->eggs[$chicken->id] ?? 0 }}
</span>
<a href="javascript:void(0)" wire:click="addEgg({{ $chicken->id }})"
class="w-8 h-8 rounded-full flex items-center justify-center text-white text-lg transition-colors bg-teal-500 hover:bg-teal-600">
+
</a>
</div>
</div>
</div>
@endforeach
</div>