From 07481f75cee94f4a76fc1b70db679175c424553f Mon Sep 17 00:00:00 2001 From: E98Developer Date: Mon, 19 Oct 2026 21:06:51 +0200 Subject: [PATCH] =?UTF-8?q?ADD=20EV3-464=20profitcenter=20egyszer=C5=B1s?= =?UTF-8?q?=C3=ADtett,=20csak=20olvashat=C3=B3=20term=C3=A9kkeres=C5=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Filament ProductResource (/admin/products): lista keresővel és szűrőkkel, csak olvasható adatlap. Profitcenternél szerver oldalon csak a saját, rendelhető beszállítók termékei látszanak; mindenkinél csak a beszállító jelenleg érvényes árlistáján szereplők (Product::scopeInActivePriceList). ProfitCenterProductSearch feature flag mögött, menüpont mindkét nav barban. Co-Authored-By: Claude Sonnet 5.5 --- .../Resources/Products/Pages/ListProducts.php | 11 + .../Resources/Products/Pages/ViewProduct.php | 11 + .../Resources/Products/ProductResource.php | 140 +++++++++++ .../Products/Schemas/ProductInfolist.php | 50 ++++ .../Products/Tables/ProductsTable.php | 94 ++++++++ app/Models/Product.php | 45 ++++ database/seeders/FeatureFlagSeeder.php | 12 + .../components/speed-button-nav-bar.blade.php | 6 + .../views/layout/speedButtonNavBar.blade.php | 11 + .../Feature/ProfitCenterProductSearchTest.php | 222 ++++++++++++++++++ 10 files changed, 602 insertions(+) create mode 100644 app/Filament/Resources/Products/Pages/ListProducts.php create mode 100644 app/Filament/Resources/Products/Pages/ViewProduct.php create mode 100644 app/Filament/Resources/Products/ProductResource.php create mode 100644 app/Filament/Resources/Products/Schemas/ProductInfolist.php create mode 100644 app/Filament/Resources/Products/Tables/ProductsTable.php create mode 100644 tests/Feature/ProfitCenterProductSearchTest.php diff --git a/app/Filament/Resources/Products/Pages/ListProducts.php b/app/Filament/Resources/Products/Pages/ListProducts.php new file mode 100644 index 0000000..3ff94e1 --- /dev/null +++ b/app/Filament/Resources/Products/Pages/ListProducts.php @@ -0,0 +1,11 @@ +user(); + + return $user + && $user->hasRole(['profit-center', 'root', 'developer']) + && Feature::for($user)->active(self::FEATURE); + } + + /** + * A Product modellre a Laravel automatikusan a ProductPolicy-t köti, az viszont a + * (beszállítói/admin) szerkesztésre készült és a profit-center szerepkört nem ismeri. + * A rekord-szintű szűrést a getEloquentQuery() végzi (idegen termék 404), ezért itt + * a resource-szintű jogosultság dönt. + */ + public static function canView($record): bool + { + return static::canViewAny(); + } + + public static function canCreate(): bool + { + return false; + } + + public static function canEdit($record): bool + { + return false; + } + + public static function canDelete($record): bool + { + return false; + } + + public static function canDeleteAny(): bool + { + return false; + } + + public static function getEloquentQuery(): Builder + { + $query = parent::getEloquentQuery() + ->with(['Supplier', 'Producer', 'ProductGroup']) + ->inActivePriceList() + ->withActivePrice(); + + /** @var User|null $user */ + $user = auth()->user(); + if ($user?->hasRole('profit-center')) { + $query->whereIn('products.supplier_id', static::profitCenterSupplierIds($user)); + } + + return $query; + } + + /** + * A profitcenter beszállítói: a felhasználó első profitcentere (1:1 használat), csak + * a rendelésnél is látható beszállítók. Profitcenter nélküli felhasználó nem lát semmit. + * + * @return array + */ + public static function profitCenterSupplierIds(User $user): array + { + return $user->profitCenters()->first() + ?->suppliers() + ->where('suppliers.canSeeInOrder', 1) + ->pluck('suppliers.id') + ->all() ?? []; + } + + public static function infolist(Schema $schema): Schema + { + return ProductInfolist::configure($schema); + } + + public static function table(Table $table): Table + { + return ProductsTable::configure($table); + } + + public static function getPages(): array + { + return [ + 'index' => ListProducts::route('/'), + 'view' => ViewProduct::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Products/Schemas/ProductInfolist.php b/app/Filament/Resources/Products/Schemas/ProductInfolist.php new file mode 100644 index 0000000..5df7bd7 --- /dev/null +++ b/app/Filament/Resources/Products/Schemas/ProductInfolist.php @@ -0,0 +1,50 @@ +components([ + Section::make('Termék') + ->columns(2) + ->schema([ + TextEntry::make('name')->label('Megnevezés'), + TextEntry::make('buyerProductName')->label('Horeca megnevezés')->placeholder('—'), + TextEntry::make('Supplier.name')->label('Beszállító'), + TextEntry::make('Producer.name')->label('Gyártó')->placeholder('—'), + TextEntry::make('ProductGroup.name')->label('Termékcsoport')->placeholder('—'), + TextEntry::make('supplierProductNumber')->label('Beszállítói cikkszám')->placeholder('—'), + ]), + Section::make('Kiszerelés és ár') + ->columns(2) + ->schema([ + TextEntry::make('current_price') + ->label('Aktuális ár') + ->formatStateUsing(fn ($state) => $state === null ? '—' : number_format((float) $state, 2, ',', ' ').' Ft'), + TextEntry::make('vat')->label('ÁFA (%)')->placeholder('—'), + TextEntry::make('packing')->label('Kiszerelés (db)')->placeholder('—'), + TextEntry::make('unitValue') + ->label('Egységérték') + ->formatStateUsing(fn ($state, $record) => trim($state.' '.$record->productUnit)), + TextEntry::make('sellerUnit')->label('Eladási egység')->placeholder('—'), + TextEntry::make('unitMultiplier') + ->label('Mennyiségi szorzó') + ->formatStateUsing(fn ($state, $record) => trim($state.' '.$record->amountUnit)), + IconEntry::make('krel')->label('KREL')->boolean(), + IconEntry::make('specialOffer')->label('Akciós')->boolean(), + ]), + Section::make('Megjegyzés') + ->schema([ + TextEntry::make('note')->hiddenLabel()->placeholder('—')->columnSpanFull(), + ]), + ]); + } +} diff --git a/app/Filament/Resources/Products/Tables/ProductsTable.php b/app/Filament/Resources/Products/Tables/ProductsTable.php new file mode 100644 index 0000000..9bfd5ce --- /dev/null +++ b/app/Filament/Resources/Products/Tables/ProductsTable.php @@ -0,0 +1,94 @@ +columns([ + TextColumn::make('name') + ->label('Termék') + ->searchable() + ->sortable(), + TextColumn::make('Supplier.name') + ->label('Beszállító') + ->searchable() + ->sortable(), + TextColumn::make('Producer.name') + ->label('Gyártó') + ->placeholder('—') + ->searchable(), + TextColumn::make('ProductGroup.name') + ->label('Termékcsoport') + ->placeholder('—'), + TextColumn::make('packing') + ->label('Kiszerelés') + ->formatStateUsing(fn ($record) => trim( + ($record->packing ? $record->packing.' × ' : '').$record->unitValue.' '.$record->productUnit + )), + TextColumn::make('current_price') + ->label('Ár') + ->formatStateUsing(fn ($state) => $state === null ? '—' : number_format((float) $state, 2, ',', ' ').' Ft') + ->alignEnd() + ->sortable(), + IconColumn::make('specialOffer') + ->label('Akciós') + ->boolean() + ->trueColor('warning') + ->falseIcon('') + ->toggleable(), + TextColumn::make('buyerProductName') + ->label('Horeca megnevezés') + ->searchable() + ->toggleable(isToggledHiddenByDefault: true), + TextColumn::make('supplierProductNumber') + ->label('Beszállítói cikkszám') + ->searchable() + ->toggleable(isToggledHiddenByDefault: true), + ]) + ->defaultSort('name') + ->filters([ + SelectFilter::make('supplier_id') + ->label('Beszállító') + ->multiple() + ->options(function () { + // Ugyanaz a keret, mint a találati listáé: profitcenternek csak a saját beszállítói. + $ids = ProductResource::getEloquentQuery()->reorder()->select('products.supplier_id')->distinct(); + + return Supplier::query()->whereIn('id', $ids)->orderBy('name')->pluck('name', 'id'); + }), + SelectFilter::make('product_group_id') + ->label('Termékcsoport') + ->multiple() + ->searchable() + ->options(fn () => ProductGroup::query()->orderBy('name')->pluck('name', 'id')), + SelectFilter::make('producer_id') + ->label('Gyártó') + ->multiple() + ->searchable() + ->options(fn () => Producer::query()->orderBy('name')->pluck('name', 'id')), + TernaryFilter::make('specialOffer') + ->label('Akciós'), + ]) + ->recordActions([ + ViewAction::make(), + ]) + ->recordUrl(fn ($record) => ProductResource::getUrl('view', ['record' => $record])) + ->searchPlaceholder('Keresés: termék, beszállító, gyártó…') + ->paginated([25, 50, 100]) + ->defaultPaginationPageOption(25); + } +} diff --git a/app/Models/Product.php b/app/Models/Product.php index b502a46..85da658 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -4,10 +4,12 @@ use App\Enums\StockStatusEnum; use Carbon\Carbon; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\MorphOne; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Support\Facades\DB; class Product extends BaseAuditable { @@ -23,6 +25,49 @@ protected function casts(): array ]; } + /** + * Beszállítónként az érvényes árlista: a legfrissebb, a megadott napig már hatályos + * (available <= dátum), törlés nélküli lista; azonos dátumnál a kisebb id - ugyanaz a + * sorrend, mint a Price()-ban. A termék akkor "érvényes árlistás", ha ebben szerepel. + */ + public function scopeInActivePriceList(Builder $query, ?string $date = null): Builder + { + $date ??= Carbon::today()->format('Y-m-d'); + + return $query->whereExists(function ($sub) use ($date) { + $sub->from('price_list_prices as plp') + ->join('price_lists as pl', 'pl.id', '=', 'plp.price_list_id') + ->whereColumn('plp.product_id', 'products.id') + ->whereRaw('pl.id = ('.self::activePriceListIdSql().')', [$date]) + ->select(DB::raw(1)); + }); + } + + /** + * Hozzáadja a current_price oszlopot: a termék ára az érvényes árlistán + * (lásd scopeInActivePriceList), NULL ha nem szerepel rajta. + */ + public function scopeWithActivePrice(Builder $query, ?string $date = null): Builder + { + $date ??= Carbon::today()->format('Y-m-d'); + + return $query->addSelect([ + 'products.*', + 'current_price' => DB::table('price_list_prices as plp') + ->join('price_lists as pl', 'pl.id', '=', 'plp.price_list_id') + ->whereColumn('plp.product_id', 'products.id') + ->whereRaw('pl.id = ('.self::activePriceListIdSql().')', [$date]) + ->select('plp.price') + ->limit(1), + ]); + } + + private static function activePriceListIdSql(): string + { + return 'select pl2.id from price_lists pl2 where pl2.supplier_id = pl.supplier_id ' + .'and pl2.deleted_at is null and pl2.available <= ? order by pl2.available desc, pl2.id asc limit 1'; + } + public function ProductGroup(): BelongsTo { return $this->belongsTo(ProductGroup::class); diff --git a/database/seeders/FeatureFlagSeeder.php b/database/seeders/FeatureFlagSeeder.php index f16a036..d5b3dcc 100644 --- a/database/seeders/FeatureFlagSeeder.php +++ b/database/seeders/FeatureFlagSeeder.php @@ -47,6 +47,18 @@ public function run(): void ], ); + FeatureFlag::updateOrCreate( + ['name' => 'ProfitCenterProductSearch'], + [ + 'label' => 'Profitcenter termékkereső (EV3-464)', + 'description' => 'Az egyszerűsített, csak olvasható termékkereső (/admin/products) elérését szabályozza a profitcenter számára a rollout alatt. Átmeneti kapcsoló: élesítéskor a profit-center szerepkört is hozzá kell venni a flag roles listájához (vagy a roles-t üresre venni), a funkció véglegesítése után eltávolítható.', + // A PricelistExecution mintáját követi: enabled=true + roles=['developer']. + 'enabled' => true, + 'stages' => null, + 'roles' => ['developer'], + ], + ); + FeatureFlag::updateOrCreate( ['name' => 'PricelistExecution'], [ diff --git a/resources/views/filament/components/speed-button-nav-bar.blade.php b/resources/views/filament/components/speed-button-nav-bar.blade.php index 25678f8..0686c7b 100644 --- a/resources/views/filament/components/speed-button-nav-bar.blade.php +++ b/resources/views/filament/components/speed-button-nav-bar.blade.php @@ -34,6 +34,12 @@ ['name' => 'calendarTest', 'displayName' => 'Naptár Teszt', 'icon' => 'idopontok', 'link' => \App\Filament\Pages\CalendarTest::getUrl(), 'roles' => ['root','developer','admin']], ]; + // EV3-464: profitcenter termékkereső. A szerepkör + ProfitCenterProductSearch flag + // ellenőrzést maga a resource végzi (canViewAny), a menü csak ezt tükrözi. + if (\App\Filament\Resources\Products\ProductResource::canViewAny()) { + $modules[] = ['name' => 'productSearch', 'displayName' => 'Termékkereső', 'icon' => 'raktar', 'link' => \App\Filament\Resources\Products\ProductResource::getUrl(), 'roles' => ['root','developer','profit-center']]; + } + // A feature flag admin felület megjelenítését nem statikus role-listával, // hanem a FeatureFlagResource jogosultság-ellenőrzésével (FeatureFlagPolicy, // ami a "FeatureFlagAdmin" flaget nézi) döntjük el - így a hozzáférés diff --git a/resources/views/layout/speedButtonNavBar.blade.php b/resources/views/layout/speedButtonNavBar.blade.php index f1d67d7..38efc62 100644 --- a/resources/views/layout/speedButtonNavBar.blade.php +++ b/resources/views/layout/speedButtonNavBar.blade.php @@ -186,6 +186,17 @@ 'roles' => ['root', 'developer'], ]; } +// EV3-464: profitcenter termékkereső - ugyanaz a canViewAny() (szerepkör + flag), mint a modern nav barban. +if (\App\Filament\Resources\Products\ProductResource::canViewAny()) { + $Modules['productSearch'] = [ + 'name' => 'productSearch', + 'DisplayName' => 'Termékkereső', + 'icon' => 'raktar', + 'link' => \App\Filament\Resources\Products\ProductResource::getUrl(), + 'noAjax' => true, + 'roles' => ['root', 'developer', 'profit-center'], + ]; +} $Modules=json_decode(json_encode($Modules)); ?> {{-- diff --git a/tests/Feature/ProfitCenterProductSearchTest.php b/tests/Feature/ProfitCenterProductSearchTest.php new file mode 100644 index 0000000..4508ea1 --- /dev/null +++ b/tests/Feature/ProfitCenterProductSearchTest.php @@ -0,0 +1,222 @@ + ProductResource::FEATURE, + 'label' => 'Profitcenter termékkereső', + 'enabled' => true, + 'stages' => null, + 'roles' => null, + ]); + + app(FeatureFlagRegistrar::class)->registerAll(); +} + +function userWithRole(string $role): User +{ + $user = User::factory()->create(); + $user->addRole(Role::firstOrCreate(['name' => $role], ['display_name' => $role])); + + return $user; +} + +/** + * Profitcenter-felhasználó a megadott (rendelhető) beszállítókkal. + * + * @param array $suppliers + */ +function profitCenterUserWith(array $suppliers): User +{ + $user = userWithRole('profit-center'); + $profitCenter = ProfitCenter::factory()->create(); + $profitCenter->users()->attach($user); + $profitCenter->suppliers()->attach(collect($suppliers)->pluck('id')->all()); + + return $user; +} + +function priceListWith(Supplier $supplier, string $available, array $prices): PriceList +{ + $priceList = PriceList::create(['supplier_id' => $supplier->id, 'available' => $available, 'status' => 'active']); + + foreach ($prices as $productId => $price) { + DB::table('price_list_prices')->insert([ + 'price_list_id' => $priceList->id, + 'product_id' => $productId, + 'price' => $price, + ]); + } + + return $priceList; +} + +function product(Supplier $supplier, string $name): Product +{ + return Product::create(['name' => $name, 'supplier_id' => $supplier->id, 'status' => 'active']); +} + +test('a termékkereső csak a flag mellett, profitcenter/root/developer szerepkörnek érhető el', function () { + $profitCenter = userWithRole('profit-center'); + $admin = userWithRole('admin'); + + $this->actingAs($profitCenter); + expect(ProductResource::canViewAny())->toBeFalse(); // flag még nincs + + enableProductSearchFlag(); + + expect(ProductResource::canViewAny())->toBeTrue(); + expect(ProductResource::canCreate())->toBeFalse(); + + $this->actingAs($admin); + expect(ProductResource::canViewAny())->toBeFalse(); // admin később kapja meg + + $this->actingAs(userWithRole('developer')); + expect(ProductResource::canViewAny())->toBeTrue(); +}); + +test('a profitcenter csak a saját, rendelhető beszállítóinak termékeit látja', function () { + enableProductSearchFlag(); + + $own = Supplier::factory()->create(); + $notOrderable = Supplier::factory()->create(['canSeeInOrder' => 0]); + $foreign = Supplier::factory()->create(); + + $ownProduct = product($own, 'Saját termék'); + $hiddenProduct = product($notOrderable, 'Nem rendelhető beszállító termék'); + $foreignProduct = product($foreign, 'Idegen termék'); + + foreach ([$own, $notOrderable, $foreign] as $supplier) { + priceListWith($supplier, Carbon::yesterday()->toDateString(), [ + Product::where('supplier_id', $supplier->id)->first()->id => 100, + ]); + } + + $this->actingAs(profitCenterUserWith([$own, $notOrderable])); + + Livewire::test(ListProducts::class) + ->assertCanSeeTableRecords([$ownProduct]) + ->assertCanNotSeeTableRecords([$hiddenProduct, $foreignProduct]); +}); + +test('csak a beszállító jelenleg érvényes árlistáján szereplő termék látszik, az árral együtt', function () { + enableProductSearchFlag(); + + $supplier = Supplier::factory()->create(); + $onlyOld = product($supplier, 'Csak régi árlistán'); + $current = product($supplier, 'Érvényes árlistán'); + $onlyFuture = product($supplier, 'Csak jövőbeli árlistán'); + $unlisted = product($supplier, 'Árlista nélkül'); + + priceListWith($supplier, Carbon::today()->subDays(30)->toDateString(), [$onlyOld->id => 10, $current->id => 20]); + priceListWith($supplier, Carbon::today()->toDateString(), [$current->id => 25]); + priceListWith($supplier, Carbon::today()->addDays(7)->toDateString(), [$onlyFuture->id => 30]); + + $this->actingAs(profitCenterUserWith([$supplier])); + + Livewire::test(ListProducts::class) + ->assertCanSeeTableRecords([$current]) + ->assertCanNotSeeTableRecords([$onlyOld, $onlyFuture, $unlisted]); + + expect(ProductResource::getEloquentQuery()->findOrFail($current->id)->current_price)->toEqual(25); +}); + +test('a törölt árlista nem számít érvényesnek', function () { + enableProductSearchFlag(); + + $supplier = Supplier::factory()->create(); + $fallback = product($supplier, 'Korábbi listán'); + $deleted = product($supplier, 'Törölt listán'); + + priceListWith($supplier, Carbon::today()->subDays(10)->toDateString(), [$fallback->id => 10]); + $deletedList = priceListWith($supplier, Carbon::yesterday()->toDateString(), [$deleted->id => 20]); + DB::table('price_lists')->where('id', $deletedList->id)->update(['deleted_at' => now()]); + + $this->actingAs(profitCenterUserWith([$supplier])); + + Livewire::test(ListProducts::class) + ->assertCanSeeTableRecords([$fallback]) + ->assertCanNotSeeTableRecords([$deleted]); +}); + +test('a szóközzel tagolt keresés minden szóra illeszt', function () { + enableProductSearchFlag(); + + $supplier = Supplier::factory()->create(); + $match = product($supplier, 'Csemege szalámi 1 kg'); + $other = product($supplier, 'Téliszalámi'); + priceListWith($supplier, Carbon::yesterday()->toDateString(), [$match->id => 100, $other->id => 100]); + + $this->actingAs(profitCenterUserWith([$supplier])); + + Livewire::test(ListProducts::class) + ->searchTable('csemege szalámi') + ->assertCanSeeTableRecords([$match]) + ->assertCanNotSeeTableRecords([$other]); +}); + +test('profitcenter nélküli felhasználó nem lát terméket', function () { + enableProductSearchFlag(); + + $supplier = Supplier::factory()->create(); + $product = product($supplier, 'Valami'); + priceListWith($supplier, Carbon::yesterday()->toDateString(), [$product->id => 100]); + + $this->actingAs(userWithRole('profit-center')); + + Livewire::test(ListProducts::class)->assertCanNotSeeTableRecords([$product]); +}); + +test('az adatlap renderel, idegen termék adatlapja nem érhető el, szerkesztő oldal nincs', function () { + enableProductSearchFlag(); + + $own = Supplier::factory()->create(); + $foreign = Supplier::factory()->create(); + $ownProduct = product($own, 'Saját termék'); + $foreignProduct = product($foreign, 'Idegen termék'); + priceListWith($own, Carbon::yesterday()->toDateString(), [$ownProduct->id => 1234.5]); + priceListWith($foreign, Carbon::yesterday()->toDateString(), [$foreignProduct->id => 10]); + + $this->actingAs(profitCenterUserWith([$own])); + + Livewire::test(ViewProduct::class, ['record' => $ownProduct->getRouteKey()]) + ->assertSuccessful() + ->assertSee('Saját termék') + ->assertSee('1 234,50 Ft'); + + expect(fn () => Livewire::test(ViewProduct::class, ['record' => $foreignProduct->getRouteKey()])) + ->toThrow(ModelNotFoundException::class); + + expect(array_keys(ProductResource::getPages()))->toBe(['index', 'view']); +}); + +test('flag nélkül a lista oldal tiltott', function () { + $supplier = Supplier::factory()->create(); + + $this->actingAs(profitCenterUserWith([$supplier])); + + $this->get(ProductResource::getUrl())->assertForbidden(); +});