feat: Implement EggCollection management with resource, pages, and models for egg production tracking

This commit is contained in:
Yoga Pangestu 2026-02-18 22:26:04 +07:00
parent 6d77a94806
commit d8038b59b9
15 changed files with 635 additions and 0 deletions

View File

@ -0,0 +1,52 @@
<?php
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\Models\EggCollection;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
class EggCollectionResource extends Resource
{
protected static ?string $model = EggCollection::class;
protected static string|UnitEnum|null $navigationGroup = 'Kelola';
protected static string|BackedEnum|null $navigationIcon = Heroicon::RectangleGroup;
protected static ?string $navigationLabel = 'Produksi Telur';
protected static ?int $navigationSort = 2;
protected static ?string $recordTitleAttribute = 'production_date';
protected static ?string $slug = 'manage/egg-collections';
public static function form(Schema $schema): Schema
{
return EggCollectionForm::configure($schema);
}
public static function table(Table $table): Table
{
return EggCollectionsTable::configure($table);
}
public static function getPages(): array
{
return [
'index' => ListEggCollections::route('/'),
'create' => CreateEggCollection::route('/create'),
'edit' => EditEggCollection::route('/{record}/edit'),
];
}
}

View File

@ -0,0 +1,58 @@
<?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\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 = [];
}
}

View File

@ -0,0 +1,67 @@
<?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\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,
]);
}
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Pages;
use App\Filament\Resources\Manage\EggCollections\EggCollectionResource;
use Filament\Actions\CreateAction;
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,63 @@
<?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

@ -0,0 +1,105 @@
<?php
namespace App\Filament\Resources\Manage\EggCollections\Tables;
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 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')
->sortable(),
TextColumn::make('total_eggs')
->label('Total Telur')
->numeric()
->sortable(),
TextColumn::make('notes')
->label('Catatan')
->wrap()
->toggleable(),
TextColumn::make('created_at')
->label('Dibuat')
->dateTime('d/m/Y H:i')
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
TrashedFilter::make()
->native(false),
])
->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

@ -0,0 +1,46 @@
<?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

@ -0,0 +1,28 @@
<?php
namespace App\Models;
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
{
use HasFactory, SoftDeletes;
protected $guarded = ['id'];
protected function casts(): array
{
return [
'production_date' => 'datetime',
'total_eggs' => 'integer',
];
}
public function items(): HasMany
{
return $this->hasMany(EggCollectionItem::class);
}
}

View File

@ -0,0 +1,31 @@
<?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

@ -0,0 +1,64 @@
<?php
namespace Database\Factories;
use App\Models\Chicken;
use App\Models\EggCollection;
use App\Models\EggCollectionItem;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\EggCollection>
*/
class EggCollectionFactory extends Factory
{
protected $model = EggCollection::class;
public function definition(): array
{
$dateTime = $this->faker->dateTimeBetween('-1 month', 'now');
return [
'production_date' => $dateTime,
'total_eggs' => 0,
'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

@ -0,0 +1,26 @@
<?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_collections', function (Blueprint $table) {
$table->id();
$table->dateTime('production_date');
$table->unsignedInteger('total_eggs')->default(0);
$table->text('notes')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable()->useCurrentOnUpdate();
$table->softDeletes();
});
}
public function down(): void
{
Schema::dropIfExists('egg_collections');
}
};

View File

@ -0,0 +1,26 @@
<?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

@ -21,6 +21,7 @@ public function run(): void
ChickenSeeder::class,
FeedSeeder::class,
FeedPurchaseSeeder::class,
EggCollectionSeeder::class,
]);
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace Database\Seeders;
use App\Models\EggCollection;
use Illuminate\Database\Seeder;
class EggCollectionSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
EggCollection::factory()->count(30)->create();
}
}

View File

@ -0,0 +1,29 @@
<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>