ADD EV3-464 profitcenter egyszerűsített, csak olvasható termékkereső

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 <noreply@anthropic.com>
This commit is contained in:
E98Developer 2026-10-19 21:06:51 +02:00
parent 1d6e94174d
commit 07481f75ce
10 changed files with 602 additions and 0 deletions

View File

@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Products\Pages;
use App\Filament\Resources\Products\ProductResource;
use Filament\Resources\Pages\ListRecords;
class ListProducts extends ListRecords
{
protected static string $resource = ProductResource::class;
}

View File

@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Products\Pages;
use App\Filament\Resources\Products\ProductResource;
use Filament\Resources\Pages\ViewRecord;
class ViewProduct extends ViewRecord
{
protected static string $resource = ProductResource::class;
}

View File

@ -0,0 +1,140 @@
<?php
namespace App\Filament\Resources\Products;
use App\Filament\Resources\Products\Pages\ListProducts;
use App\Filament\Resources\Products\Pages\ViewProduct;
use App\Filament\Resources\Products\Schemas\ProductInfolist;
use App\Filament\Resources\Products\Tables\ProductsTable;
use App\Models\Product;
use App\Models\User;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Laravel\Pennant\Feature;
/**
* EV3-464: egyszerűsített, csak olvasható termékkereső a profitcenternek ("melyik
* beszállítónál kapható a csemege szalámi?"). Szándékosan nincs create/edit oldal.
*
* A láthatóság szerver oldalon szűkül (getEloquentQuery), nem csak a menüből:
* - profitcenter szerepkörnél csak a saját profitcenter beszállítóinak termékei, akiktől
* rendelni is lehet (suppliers.canSeeInOrder, mint az új rendelés beszállító-listáján);
* - mindenkinél csak a beszállító jelenleg érvényes árlistáján szereplő termékek (fix).
*
* Az admin használat később jön; addig a ProfitCenterProductSearch flag + a szerepkör-lista
* (root/developer a rollout-teszteléshez) szabja meg, ki éri el.
*/
class ProductResource extends Resource
{
public const FEATURE = 'ProfitCenterProductSearch';
protected static ?string $model = Product::class;
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-magnifying-glass';
protected static ?string $navigationLabel = 'Termékkereső';
protected static ?string $modelLabel = 'Termék';
protected static ?string $pluralLabel = 'Termékkereső';
protected static ?string $breadcrumb = 'Termékkereső';
public static function canAccess(): bool
{
return static::canViewAny();
}
public static function canViewAny(): bool
{
/** @var User|null $user */
$user = auth()->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<int, int>
*/
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}'),
];
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Filament\Resources\Products\Schemas;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
class ProductInfolist
{
public static function configure(Schema $schema): Schema
{
return $schema
->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(),
]),
]);
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace App\Filament\Resources\Products\Tables;
use App\Filament\Resources\Products\ProductResource;
use App\Models\Producer;
use App\Models\ProductGroup;
use App\Models\Supplier;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
class ProductsTable
{
public static function configure(Table $table): Table
{
return $table
->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);
}
}

View File

@ -4,10 +4,12 @@
use App\Enums\StockStatusEnum; use App\Enums\StockStatusEnum;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphOne; use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
class Product extends BaseAuditable 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 public function ProductGroup(): BelongsTo
{ {
return $this->belongsTo(ProductGroup::class); return $this->belongsTo(ProductGroup::class);

View File

@ -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( FeatureFlag::updateOrCreate(
['name' => 'PricelistExecution'], ['name' => 'PricelistExecution'],
[ [

View File

@ -34,6 +34,12 @@
['name' => 'calendarTest', 'displayName' => 'Naptár Teszt', 'icon' => 'idopontok', 'link' => \App\Filament\Pages\CalendarTest::getUrl(), 'roles' => ['root','developer','admin']], ['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, // 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, // 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 // ami a "FeatureFlagAdmin" flaget nézi) döntjük el - így a hozzáférés

View File

@ -186,6 +186,17 @@
'roles' => ['root', 'developer'], '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)); $Modules=json_decode(json_encode($Modules));
?> ?>
{{-- {{--

View File

@ -0,0 +1,222 @@
<?php
use App\Filament\Resources\Products\Pages\ListProducts;
use App\Filament\Resources\Products\Pages\ViewProduct;
use App\Filament\Resources\Products\ProductResource;
use App\Models\FeatureFlag;
use App\Models\PriceList;
use App\Models\ProfitCenter;
use App\Models\Product;
use App\Models\Role;
use App\Models\Supplier;
use App\Models\User;
use App\Services\FeatureFlagRegistrar;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Livewire;
use Tests\TestCase;
uses(TestCase::class, RefreshDatabase::class);
/**
* EV3-464: csak olvasható termékkereső a profitcenternek.
*/
function enableProductSearchFlag(): void
{
FeatureFlag::create([
'name' => 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<int, Supplier> $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();
});