Files
SpiceManagementSystem/app/Filament/User/Resources/ProductResource.php
T
Malek TellissiandClaude Sonnet 4.6 a12502418b
Deploy / deploy (push) Successful in 14s
Display product images in grid layout with 200px preview height
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-09-12 05:20:40 +02:00

251 lines
11 KiB
PHP

<?php
namespace App\Filament\User\Resources;
use App\Filament\User\Resources\ProductResource\Pages;
use App\Filament\User\Resources\ProductResource\RelationManagers;
use App\Models\Product;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;
use App\Models\Packing;
use App\Models\Recipe;
use Picqer\Barcode\BarcodeGeneratorSVG;
class ProductResource extends Resource {
protected static ?string $model = Product::class;
protected static ?string $navigationIcon = 'heroicon-o-inbox';
protected static ?string $navigationLabel = 'Produkte';
protected static ?string $modelLabel = 'Produkt';
protected static ?string $slug = 'produkt';
protected static ?string $navigationGroup = 'Produkte';
protected static ?int $navigationSort = 1;
public static function form(Form $form): Form {
return $form
->schema([
Forms\Components\TextInput::make('title')
->label('Name')
->required(),
FileUpload::make('images')
->label('Bilder')
->multiple()
->image()
->maxFiles(15)
->directory('product-images')
->panelLayout('grid')
->imagePreviewHeight('200')
->columnSpanFull(),
Forms\Components\Textarea::make('description')
->label('Beschreibung'),
Forms\Components\Select::make('recipes_id')
->label('Rezept')
->native(false)
->searchable()
->live()
->relationship('recipe', 'name')
->getOptionLabelFromRecordUsing(fn (Recipe $r) => "{$r->name} (v{$r->version})")
->required()
->createOptionForm(fn () => [
Forms\Components\TextInput::make('name')
->label('Name')
->required()
->default(fn ($livewire) => $livewire->data['title'] ?? ''),
Forms\Components\Textarea::make('description')
->label('Beschreibung'),
])
->createOptionUsing(function (array $data, $livewire) {
$productId = $livewire->record?->id;
$nextVersion = Recipe::where('product_id', $productId)->max('version') + 1;
return Recipe::create([
'name' => $data['name'],
'description' => $data['description'] ?? null,
'product_id' => $productId,
'version' => $nextVersion,
])->getKey();
})
->editOptionForm([
Forms\Components\TextInput::make('name')
->label('Name')
->required(),
Forms\Components\Textarea::make('description')
->label('Beschreibung'),
]),
Placeholder::make('recipe_summary')
->label('Rezept-Inhalt')
->content(function (Forms\Get $get, $record): HtmlString {
$recipeId = $get('recipes_id');
$recipe = $recipeId ? Recipe::with('spices')->find($recipeId) : $record?->recipe?->load('spices');
if (! $recipe || $recipe->spices->isEmpty()) {
return new HtmlString('<span class="text-sm text-gray-400">Keine Zutaten hinterlegt</span>');
}
$items = $recipe->spices->map(fn ($s) => "<li>{$s->name} ({$s->pivot->amount_in_percent}%)</li>")->implode('');
$meta = "v{$recipe->version} · erstellt " . $recipe->created_at->format('d.m.Y');
return new HtmlString("<p class='text-xs text-gray-400 mb-1'>{$meta}</p><ul class='list-disc list-inside text-sm'>{$items}</ul>");
})
->columnSpanFull()
->visible(fn (Forms\Get $get, $record) => filled($get('recipes_id')) || $record?->recipes_id),
Repeater::make('sizes')
->schema([
Select::make('packing_id')
->label('Verpackung')
->options(function () {
return Packing::all()->mapWithKeys(function ($packing) {
return [$packing->id => $packing->name . ' (' . $packing->size . ')'];
});
})
->searchable()
->required(),
TextInput::make('price')
->label('Preis (in EUR)')
->numeric()
->required(),
TextInput::make('sku')
->label('SKU'),
Placeholder::make('barcode_preview')
->label('Barcode')
->content(function (Get $get): HtmlString {
$gtin = preg_replace('/\D/', '', (string) $get('gtin'));
if (strlen($gtin) < 8) {
return new HtmlString('');
}
$type = match (strlen($gtin)) {
8 => BarcodeGeneratorSVG::TYPE_EAN_8,
13 => BarcodeGeneratorSVG::TYPE_EAN_13,
12 => BarcodeGeneratorSVG::TYPE_UPC_A,
14 => BarcodeGeneratorSVG::TYPE_CODABAR,
default => BarcodeGeneratorSVG::TYPE_CODE_128,
};
try {
$svg = (new BarcodeGeneratorSVG())->getBarcode($gtin, $type, 2, 60);
return new HtmlString($svg);
} catch (\Throwable) {
return new HtmlString('');
}
})
->columnSpanFull()
->visible(fn (Get $get) => strlen(preg_replace('/\D/', '', (string) $get('gtin'))) >= 8),
TextInput::make('gtin')
->label('GTIN')
->mask('9 999999 999999')
->dehydrateStateUsing(fn ($state) => preg_replace('/\D/', '', (string) $state))
->live(debounce: 500),
])
->label('Größen & Preise')
->columns(2)
->addActionLabel('Option hinzufügen')
->afterStateHydrated(function ($state, $set, $record) {
if ($record) {
$record->load('sizes');
$sizesData = $record->sizes->map(function ($size) {
return [
'packing_id' => $size->id,
'price' => $size->pivot->price,
'description' => $size->pivot->description,
'sku' => $size->pivot->sku,
'gtin' => $size->pivot->gtin,
];
})->toArray();
$set('sizes', $sizesData);
}
return $state;
}),
]);
}
public static function table(Table $table): Table {
return $table
->columns([
Tables\Columns\ImageColumn::make('images')
->label('Bild')
->disk('public')
->limit(1),
Tables\Columns\TextColumn::make('title')
->label('Name')
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('recipe.name')
->label('Rezept'),
]);
}
public static function getRelations(): array {
return [
RelationManagers\BatchesRelationManager::class,
];
}
public static function getPages(): array {
return [
'index' => Pages\ListProducts::route('/'),
'create' => Pages\CreateProduct::route('/create'),
'edit' => Pages\EditProduct::route('/{record}/edit'),
];
}
public static function getPluralLabel(): string {
return 'Produkte';
}
protected function mutateFormDataBeforeCreate(array $data): array {
if (isset($data['images'])) {
$data['images'] = json_encode($data['images']);
}
return $data;
}
protected function mutateFormDataBeforeUpdate(array $data): array {
if (isset($data['images'])) {
$data['images'] = json_encode($data['images']);
}
return $data;
}
public static function getRecord($id) {
return Product::with('sizes')->findOrFail($id); // Eager load spices relationship
}
public static function getTableRecordTitle() {
return function ($record) {
$images = json_decode($record->images, true);
return implode(', ', $images);
};
}
public static function getActions(): array {
return [
Actions\DeleteAction::make(),
Action::make('deleteImage')
->action(function ($record, $data) {
$images = json_decode($record->images, true);
$index = array_search($data['image'], $images);
if ($index !== false) {
unset($images[$index]);
$record->update(['images' => array_values($images)]);
}
})
->form([
Forms\Components\Select::make('image')
->options(function ($record) {
return array_combine($record->images, $record->images);
})
->required(),
]),
];
}
}