Compare commits
No commits in common. "07481f75cee94f4a76fc1b70db679175c424553f" and "87cab4cad5a34cd2241fd805e61b7882e1285020" have entirely different histories.
07481f75ce
...
87cab4cad5
@ -1,269 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Models\Producer;
|
||||
use App\Models\ProducerAlias;
|
||||
use App\Support\NameNormalizer;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Visszamenőleges alias-feltöltés a már lezajlott EV3-357 gyártó-összevonásokból.
|
||||
*
|
||||
* Két forrásból dolgozik:
|
||||
*
|
||||
* 1. Az archivált gyártók `note` mezője ("Összevonva ide: #<id> (...)") - ez MINDIG
|
||||
* a jelenlegi adatbázis saját, konzisztens ID-ire mutat, láncolást igényelhet
|
||||
* (egy 1. körös célrekord a 2. körben maga is beolvadhatott).
|
||||
* 2. A producers:dedupe --report kimeneteként keletkezett JSON jelentések (a döntési
|
||||
* lapok, EV3-357 ticket-mappa). FONTOS: ezekben az ID-k környezetenként (fejlesztői/
|
||||
* d2d/éles) eltérnek, ezért a feloldás NÉVALAPÚ - a jelentés `final_name` mezőjét
|
||||
* a jelenlegi adatbázis aktív gyártói között normalizált egyezéssel keressük meg.
|
||||
*/
|
||||
class ProducersAliasBackfill extends Command
|
||||
{
|
||||
protected $signature = 'producers:alias-backfill
|
||||
{reports?* : dedupe-jelentés JSON fájl(ok) útvonala (producers:dedupe --report kimenete)}
|
||||
{--skip-archives : az archivált gyártók note mezejének feldolgozásának kihagyása}
|
||||
{--apply : ténylegesen beszúrja az aliasokat (alapértelmezés: csak kimutatás)}';
|
||||
|
||||
protected $description = 'Alias rekordok visszamenőleges feltöltése a korábbi gyártó-összevonásokból';
|
||||
|
||||
public function handle(ProducerAliasResolver $resolver): int
|
||||
{
|
||||
$candidates = [];
|
||||
|
||||
if (! $this->option('skip-archives')) {
|
||||
$candidates = array_merge($candidates, $this->collectFromArchivedProducers());
|
||||
}
|
||||
|
||||
foreach ($this->argument('reports') as $path) {
|
||||
$candidates = array_merge($candidates, $this->collectFromReport($path));
|
||||
}
|
||||
|
||||
if ($candidates === []) {
|
||||
$this->info('Nincs feldolgozandó jelölt.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
[$toInsert, $alreadyExists, $conflicts] = $this->classify($resolver, $candidates);
|
||||
|
||||
$this->summarize($toInsert, $alreadyExists, $conflicts);
|
||||
|
||||
if (! $this->option('apply')) {
|
||||
$this->newLine();
|
||||
$this->info('Ez csak kimutatás volt. A végrehajtáshoz: --apply');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($toInsert) {
|
||||
foreach ($toInsert as $row) {
|
||||
ProducerAlias::create([
|
||||
'producer_id' => $row['producer_id'],
|
||||
'name' => $row['name'],
|
||||
'normalized_name' => NameNormalizer::normalize($row['name']),
|
||||
'source' => 'backfill',
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
$this->newLine();
|
||||
$this->info(count($toInsert) . ' alias létrehozva.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{producer_id: int, name: string, origin: string}>
|
||||
*/
|
||||
private function collectFromArchivedProducers(): array
|
||||
{
|
||||
$candidates = [];
|
||||
|
||||
$archived = Producer::query()->where('status', DbStatusFieldEnum::archive)->get(['id', 'name', 'note']);
|
||||
|
||||
foreach ($archived as $producer) {
|
||||
$visited = [];
|
||||
$keeperId = $this->resolveActiveKeeperId($producer->id, $visited);
|
||||
|
||||
if ($keeperId === null) {
|
||||
$this->warn(" ! #{$producer->id} (\"{$producer->name}\") note-ja nem oldható fel aktív gyártóra.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$candidates[] = [
|
||||
'producer_id' => $keeperId,
|
||||
'name' => (string) $producer->name,
|
||||
'origin' => "archív #{$producer->id}",
|
||||
];
|
||||
}
|
||||
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Egy archivált rekord note-jából kiolvassa a célrekordot, és ha az maga is
|
||||
* archivált (2. körben tovább olvadt), a láncot az aktuális aktív rekordig követi.
|
||||
*/
|
||||
private function resolveActiveKeeperId(int $id, array &$visited): ?int
|
||||
{
|
||||
if (isset($visited[$id])) {
|
||||
return null; // ciklusvédelem
|
||||
}
|
||||
$visited[$id] = true;
|
||||
|
||||
$producer = Producer::find($id);
|
||||
|
||||
if (! $producer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! in_array($producer->status, [DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted], true)) {
|
||||
return $producer->id;
|
||||
}
|
||||
|
||||
if (! preg_match('/Összevonva ide:\s*#(\d+)/u', (string) $producer->note, $matches)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->resolveActiveKeeperId((int) $matches[1], $visited);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{producer_id: int, name: string, origin: string}>
|
||||
*/
|
||||
private function collectFromReport(string $path): array
|
||||
{
|
||||
if (! is_file($path)) {
|
||||
$this->error("A jelentésfájl nem található: {$path}");
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$report = json_decode((string) file_get_contents($path), true);
|
||||
|
||||
if (! is_array($report) || ! isset($report['merges'])) {
|
||||
$this->error("A fájl nem érvényes producers:dedupe jelentés: {$path}");
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$activeByNormalized = $this->activeProducersByNormalizedName();
|
||||
$restoreProducers = $report['restore']['producers'] ?? [];
|
||||
$candidates = [];
|
||||
|
||||
foreach ($report['merges'] as $merge) {
|
||||
$finalName = (string) ($merge['final_name'] ?? '');
|
||||
$targetId = $activeByNormalized[NameNormalizer::normalize($finalName)] ?? null;
|
||||
|
||||
if ($targetId === null) {
|
||||
$this->warn(" ! \"{$finalName}\" ({$path}) nem található aktív gyártóként ebben a környezetben.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$names = array_column($merge['from'] ?? [], 'name');
|
||||
|
||||
// A jelentésben a keeper eredeti (átnevezés előtti) neve csak a
|
||||
// restore.producers pillanatképben maradt meg - a merges tömb nem
|
||||
// tartalmazza.
|
||||
$keeperOriginalName = $restoreProducers[$merge['keeper_id']]['name'] ?? null;
|
||||
if ($keeperOriginalName !== null) {
|
||||
$names[] = (string) $keeperOriginalName;
|
||||
}
|
||||
|
||||
foreach (array_unique($names) as $name) {
|
||||
if (NameNormalizer::normalize($name) === NameNormalizer::normalize($finalName)) {
|
||||
continue; // ugyanaz, mint az élő név - felesleges alias lenne
|
||||
}
|
||||
|
||||
$candidates[] = [
|
||||
'producer_id' => $targetId,
|
||||
'name' => $name,
|
||||
'origin' => basename($path),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
private function activeProducersByNormalizedName(): array
|
||||
{
|
||||
return Producer::query()
|
||||
->whereNotIn('status', [DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted])
|
||||
->get(['id', 'name'])
|
||||
->keyBy(fn ($p) => NameNormalizer::normalize($p->name))
|
||||
->map->id
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Szétválogatja a jelölteket: mit kell beszúrni, mi van már fent (idempotencia -
|
||||
* a parancs többször is lefuttatható ugyanazokkal a bemenetekkel), és mi ütközik.
|
||||
*
|
||||
* @return array{0: array, 1: array, 2: array}
|
||||
*/
|
||||
private function classify(ProducerAliasResolver $resolver, array $candidates): array
|
||||
{
|
||||
$toInsert = [];
|
||||
$alreadyExists = [];
|
||||
$conflicts = [];
|
||||
$seen = []; // normalized_name => true, hogy egy futáson belül ne duplázzunk
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
$normalized = NameNormalizer::normalize($candidate['name']);
|
||||
|
||||
if (isset($seen[$normalized])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$existing = ProducerAlias::where('normalized_name', $normalized)
|
||||
->where('producer_id', $candidate['producer_id'])
|
||||
->exists();
|
||||
|
||||
if ($existing) {
|
||||
$alreadyExists[] = $candidate;
|
||||
$seen[$normalized] = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$resolver->assertNameAvailable($candidate['name'], $candidate['producer_id']);
|
||||
$toInsert[] = $candidate;
|
||||
} catch (RuntimeException $e) {
|
||||
$conflicts[] = $candidate + ['reason' => $e->getMessage()];
|
||||
}
|
||||
|
||||
$seen[$normalized] = true;
|
||||
}
|
||||
|
||||
return [$toInsert, $alreadyExists, $conflicts];
|
||||
}
|
||||
|
||||
private function summarize(array $toInsert, array $alreadyExists, array $conflicts): void
|
||||
{
|
||||
if ($toInsert !== []) {
|
||||
$this->table(
|
||||
['Forrás', 'Név', 'Célrekord'],
|
||||
array_map(fn ($c) => [$c['origin'], $c['name'], '#' . $c['producer_id']], $toInsert)
|
||||
);
|
||||
}
|
||||
|
||||
$this->line('Beszúrandó: ' . count($toInsert)
|
||||
. ' | már megvan: ' . count($alreadyExists)
|
||||
. ' | ütközés: ' . count($conflicts));
|
||||
|
||||
foreach ($conflicts as $conflict) {
|
||||
$this->warn(" ! \"{$conflict['name']}\" ({$conflict['origin']}): {$conflict['reason']}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -64,18 +64,6 @@ public function handle(ProducerDeduplicator $deduplicator): int
|
||||
|
||||
$this->summarize($merges);
|
||||
|
||||
// A névütközés blokkoló: a végrehajtás duplikátumot állítana elő. A --force sem
|
||||
// kerüli meg - a lapot kell javítani.
|
||||
if (($plan['blocking'] ?? []) !== []) {
|
||||
$this->newLine();
|
||||
foreach ($plan['blocking'] as $blocking) {
|
||||
$this->error(' BLOKKOLÓ: ' . $blocking);
|
||||
}
|
||||
$this->error('A végrehajtás blokkolva, amíg a döntési lap nincs javítva.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! $this->option('apply')) {
|
||||
$this->newLine();
|
||||
$this->info('Ez csak kimutatás volt. A végrehajtáshoz: --apply');
|
||||
@ -100,10 +88,6 @@ public function handle(ProducerDeduplicator $deduplicator): int
|
||||
foreach ($report['totals'] as $table => $count) {
|
||||
$this->line(' ' . str_pad($table, 24) . number_format($count) . ' sor átírva');
|
||||
}
|
||||
$this->line(' ' . str_pad('alias', 24) . count($report['restore']['created_alias_ids'] ?? []) . ' létrehozva');
|
||||
foreach ($report['alias_warnings'] ?? [] as $warning) {
|
||||
$this->warn(' ! alias kihagyva: ' . $warning);
|
||||
}
|
||||
$this->line(' Jelentés: ' . $reportPath);
|
||||
$this->newLine();
|
||||
$this->comment('Visszagörgetés: php artisan producers:dedupe --rollback="' . $reportPath . '"');
|
||||
@ -219,7 +203,18 @@ private function summarize(array $merges): void
|
||||
|
||||
private function writeReport(array $report): string
|
||||
{
|
||||
return app(ProducerDeduplicator::class)->writeReport($report, $this->option('report') ?: null);
|
||||
$path = $this->option('report') ?: storage_path(
|
||||
'app/private/producers-dedupe-' . now()->format('Y-m-d_His') . '.json'
|
||||
);
|
||||
|
||||
$directory = dirname($path);
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0775, true);
|
||||
}
|
||||
|
||||
file_put_contents($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
private function rollback(ProducerDeduplicator $deduplicator, string $path): int
|
||||
|
||||
@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Pages;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Filament\Resources\Producers\ProducerResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateProducer extends CreateRecord
|
||||
{
|
||||
protected static string $resource = ProducerResource::class;
|
||||
|
||||
/**
|
||||
* Ugyanaz az alapállapot, mint amikor az árlista-feldolgozó hoz létre új gyártót
|
||||
* (PricelistFileProcessService::createMissingProducers()) - a kézi felvételnek nem
|
||||
* kell külön mezőt adni ehhez, mindig aktív és látható.
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$data['status'] = DbStatusFieldEnum::active;
|
||||
$data['canSee'] = 1;
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* A megtekintő oldalra irányít vissza, nem a listára - onnan tud rögtön aliast is
|
||||
* felvenni az újonnan létrehozott gyártóhoz.
|
||||
*/
|
||||
protected function getRedirectUrl(): string
|
||||
{
|
||||
return static::getResource()::getUrl('view', ['record' => $this->getRecord()]);
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Pages;
|
||||
|
||||
use App\Filament\Resources\Producers\ProducerResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListProducers extends ListRecords
|
||||
{
|
||||
protected static string $resource = ProducerResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,109 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Pages;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Filament\Resources\Producers\ProducerResource;
|
||||
use App\Models\Producer;
|
||||
use App\Models\Product;
|
||||
use App\Services\ProducerDeduplicator;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Placeholder;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ViewProducer extends ViewRecord
|
||||
{
|
||||
protected static string $resource = ProducerResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
$this->mergeProducerAction(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Két aktív gyártó összevonása felületről, Excel/CLI nélkül - EV3-473, 7. lépés.
|
||||
* Valódi tesztelés közben előkerült eset: az admin a felületen böngészve veszi
|
||||
* észre, hogy két aktív gyártó ugyanaz a cég, de az alias-felvétel elutasítja az
|
||||
* ütközést, és korábban nem volt mód a tényleges összevonásra máshogy, csak a
|
||||
* producers:dedupe-report -> Excel -> producers:dedupe --apply láncon, ami
|
||||
* fejlesztői hozzáférést igényel.
|
||||
*
|
||||
* A megtekintett gyártó MINDIG a keeper marad (nincs átnevezés) - ez a felhasználói
|
||||
* szándék, hiszen már ezen az oldalon áll. A ProducerDeduplicator::apply() egyetlen,
|
||||
* kézzel épített merge-bejegyzéssel hívva (buildPlan()/Excel nélkül) - ez már
|
||||
* automatikusan aliast is ír a beolvasztott névből (lásd 4. fázis).
|
||||
*/
|
||||
protected function mergeProducerAction(): Action
|
||||
{
|
||||
return Action::make('mergeProducer')
|
||||
->label('Gyártó összevonása')
|
||||
->icon('heroicon-o-arrows-pointing-in')
|
||||
->color('warning')
|
||||
->visible(fn (Producer $record) => $record->status === DbStatusFieldEnum::active)
|
||||
->schema([
|
||||
Select::make('loser_id')
|
||||
->label('Melyik aktív gyártót olvasszuk be ide?')
|
||||
->options(fn (Producer $record) => Producer::query()
|
||||
->whereNotIn('status', [DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted])
|
||||
->where('id', '!=', $record->id)
|
||||
->orderBy('name')
|
||||
->pluck('name', 'id'))
|
||||
->searchable()
|
||||
->required()
|
||||
->live(),
|
||||
Placeholder::make('impact')
|
||||
->label('Hatás')
|
||||
->content(function (Get $get) {
|
||||
$loserId = $get('loser_id');
|
||||
|
||||
if (blank($loserId)) {
|
||||
return 'Válassz gyártót a hatás megtekintéséhez.';
|
||||
}
|
||||
|
||||
$products = Product::where('producer_id', $loserId)->count();
|
||||
$orderItems = DB::table('order_archives_items')->where('producer_id', $loserId)->count();
|
||||
$pricelistLines = DB::table('pricelist_file_lines')->where('producer_id', $loserId)->count();
|
||||
|
||||
return "Átírandó: {$products} termék, {$orderItems} rendelési tétel, "
|
||||
. "{$pricelistLines} árlista-sor. A kiválasztott gyártó archiválódik, "
|
||||
. 'a neve automatikusan alias lesz a jelenlegi gyártó alatt.';
|
||||
}),
|
||||
])
|
||||
->modalHeading('Gyártó összevonása')
|
||||
->modalSubmitActionLabel('Összevonás')
|
||||
->requiresConfirmation()
|
||||
->action(function (array $data, Producer $record) {
|
||||
$loser = Producer::findOrFail($data['loser_id']);
|
||||
|
||||
$deduplicator = app(ProducerDeduplicator::class);
|
||||
$report = $deduplicator->apply([[
|
||||
'keeper_id' => $record->id,
|
||||
'keeper_name' => $record->name,
|
||||
'final_name' => $record->name,
|
||||
'rename' => false,
|
||||
'from' => [['id' => $loser->id, 'name' => $loser->name]],
|
||||
]]);
|
||||
$reportPath = $deduplicator->writeReport($report);
|
||||
|
||||
Notification::make()
|
||||
->title('Gyártók összevonva')
|
||||
->body(sprintf(
|
||||
'"%s" beolvadt "%s" alá. %d termék, %d rendelési tétel, %d árlista-sor átírva. Jelentés: %s',
|
||||
$loser->name,
|
||||
$record->name,
|
||||
$report['totals']['products'] ?? 0,
|
||||
$report['totals']['order_archives_items'] ?? 0,
|
||||
$report['totals']['pricelist_file_lines'] ?? 0,
|
||||
basename($reportPath),
|
||||
))
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1,68 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers;
|
||||
|
||||
use App\Filament\Resources\Producers\Pages\CreateProducer;
|
||||
use App\Filament\Resources\Producers\Pages\ListProducers;
|
||||
use App\Filament\Resources\Producers\Pages\ViewProducer;
|
||||
use App\Filament\Resources\Producers\RelationManagers\AliasesRelationManager;
|
||||
use App\Filament\Resources\Producers\Schemas\ProducerForm;
|
||||
use App\Filament\Resources\Producers\Schemas\ProducerInfolist;
|
||||
use App\Filament\Resources\Producers\Tables\ProducersTable;
|
||||
use App\Models\Producer;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
/**
|
||||
* Lista + megtekintés + kézi felvétel: gyártó eddig kizárólag árlista importból
|
||||
* keletkezett, EV3-473 8. lépése ad hozzá kézi létrehozást (pl. ha egy gyártót
|
||||
* előre fel akarnak venni, mielőtt bármelyik árlistán megjelenne). Szerkesztés/törlés
|
||||
* továbbra sincs - a név utólagos módosítása az árlista-alapú párosítást zavarná meg.
|
||||
*/
|
||||
class ProducerResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Producer::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-building-storefront';
|
||||
|
||||
protected static ?string $navigationLabel = 'Gyártók';
|
||||
|
||||
protected static ?string $modelLabel = 'Gyártó';
|
||||
|
||||
protected static ?string $pluralLabel = 'Gyártók';
|
||||
|
||||
protected static ?string $breadcrumb = 'Gyártók';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return ProducerForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function infolist(Schema $schema): Schema
|
||||
{
|
||||
return ProducerInfolist::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return ProducersTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
AliasesRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListProducers::route('/'),
|
||||
'create' => CreateProducer::route('/create'),
|
||||
'view' => ViewProducer::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,102 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\RelationManagers;
|
||||
|
||||
use App\Support\Exceptions\ActiveProducerNameCollisionException;
|
||||
use App\Support\NameNormalizer;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use Closure;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Teljes CRUD az aliasokon (nem a gyártó törzsén) - EV3-473. A gyártónak ma sincs
|
||||
* admin felülete, ez az első; a cél kizárólag az, hogy a régi gyártóneveket kézzel is
|
||||
* fel lehessen venni/törölni, ne csak a producers:dedupe és a backfill parancson át.
|
||||
*/
|
||||
class AliasesRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'aliases';
|
||||
|
||||
protected static ?string $title = 'Aliasok';
|
||||
|
||||
/**
|
||||
* A panel alapértelmezése szerint minden ViewRecord oldalra kerülő relation manager
|
||||
* csak olvasható (Panel::hasReadOnlyRelationManagersOnResourceViewPagesByDefault()).
|
||||
* A ProducerResource szándékosan csak View oldalt ad a gyártóhoz (nincs Edit), de az
|
||||
* aliasokon MUST legyen teljes CRUD - ezért ez a manager kivétel a globális alapérték
|
||||
* alól, nem a panel-szintű beállítást lazítjuk (ami minden más View-relation managert
|
||||
* is érintene).
|
||||
*/
|
||||
public function isReadOnly(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
TextInput::make('name')
|
||||
->label('Régi / alternatív gyártónév')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->rules([
|
||||
fn (): Closure => function (string $attribute, $value, Closure $fail) {
|
||||
try {
|
||||
app(ProducerAliasResolver::class)
|
||||
->assertNameAvailable($value, $this->getOwnerRecord()->id);
|
||||
} catch (ActiveProducerNameCollisionException $e) {
|
||||
// Ez nem feltétlenül hiba: lehet, hogy a két gyártó
|
||||
// valóban ugyanaz a cég. A "Gyártó összevonása" gomb
|
||||
// (ViewProducer fejléc) pont erre a helyzetre való.
|
||||
$fail($e->getMessage() . ' Ha ugyanaz a cég, használd a '
|
||||
. '"Gyártó összevonása" gombot az oldal tetején.');
|
||||
} catch (RuntimeException $e) {
|
||||
$fail($e->getMessage());
|
||||
}
|
||||
},
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('name')
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Név')
|
||||
->searchable(),
|
||||
TextColumn::make('source')
|
||||
->label('Forrás')
|
||||
->badge(),
|
||||
TextColumn::make('created_at')
|
||||
->label('Létrehozva')
|
||||
->dateTime('Y-m-d H:i'),
|
||||
])
|
||||
->defaultSort('created_at', 'desc')
|
||||
// A "Gyártó összevonása" gomb (ViewProducer fejléc) a producer_aliases táblát
|
||||
// egy MÁSIK Livewire-komponensből (page-szintű action) írja - a relation
|
||||
// manager erről magától nem értesül. Poll-lal frissül, ugyanaz a minta, mint
|
||||
// a PricelistFiles LinesRelationManager-jén (háttérfolyamat frissíti a sorokat).
|
||||
->poll('5s')
|
||||
->headerActions([
|
||||
CreateAction::make()
|
||||
->mutateDataUsing(function (array $data): array {
|
||||
$data['normalized_name'] = NameNormalizer::normalize($data['name']);
|
||||
$data['source'] = 'manual';
|
||||
|
||||
return $data;
|
||||
}),
|
||||
])
|
||||
->recordActions([
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Schemas;
|
||||
|
||||
use App\Support\Exceptions\ActiveProducerNameCollisionException;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use Closure;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Schema;
|
||||
use RuntimeException;
|
||||
|
||||
class ProducerForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
TextInput::make('name')
|
||||
->label('Név')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->rules([
|
||||
// Ugyanaz az ütközés-védelem, mint az alias-felvételnél: az új gyártó
|
||||
// neve se ütközhessen élő gyártóval vagy már létező aliasszal -
|
||||
// különben pont azt a duplikációt hoznánk létre kézzel, amit az
|
||||
// alias-rendszer megelőzni hivatott.
|
||||
fn (): Closure => function (string $attribute, $value, Closure $fail) {
|
||||
try {
|
||||
app(ProducerAliasResolver::class)->assertNameAvailable($value);
|
||||
} catch (ActiveProducerNameCollisionException $e) {
|
||||
$fail($e->getMessage() . ' Ha ugyanaz a cég, ne hozz létre új gyártót - '
|
||||
. 'vedd fel inkább aliasként a meglévőhöz.');
|
||||
} catch (RuntimeException $e) {
|
||||
$fail($e->getMessage());
|
||||
}
|
||||
},
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Schemas;
|
||||
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class ProducerInfolist
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make()
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextEntry::make('name')->label('Név'),
|
||||
TextEntry::make('status')->label('Státusz')->badge(),
|
||||
TextEntry::make('note')
|
||||
->label('Megjegyzés')
|
||||
->placeholder('—')
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Tables;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ProducersTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->modifyQueryUsing(fn ($query) => $query->withCount('aliases'))
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Név')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('status')
|
||||
->label('Státusz')
|
||||
->badge()
|
||||
->color(fn (string $state) => match ($state) {
|
||||
DbStatusFieldEnum::active => 'success',
|
||||
DbStatusFieldEnum::archive => 'gray',
|
||||
DbStatusFieldEnum::deleted => 'danger',
|
||||
default => 'gray',
|
||||
})
|
||||
->sortable(),
|
||||
TextColumn::make('aliases_count')
|
||||
->label('Aliasok')
|
||||
->sortable(),
|
||||
TextColumn::make('note')
|
||||
->label('Megjegyzés')
|
||||
->limit(40)
|
||||
->placeholder('—')
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->defaultSort('name')
|
||||
->filters([
|
||||
SelectFilter::make('status')
|
||||
->label('Státusz')
|
||||
->options(collect(DbStatusFieldEnum::getValues())->mapWithKeys(fn ($v) => [$v => $v])),
|
||||
])
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,11 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
@ -1,11 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
@ -1,140 +0,0 @@
|
||||
<?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}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
<?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(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,94 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
@ -2,10 +2,4 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
class Producer extends BaseAuditable
|
||||
{
|
||||
public function aliases()
|
||||
{
|
||||
return $this->hasMany(ProducerAlias::class);
|
||||
}
|
||||
}
|
||||
class Producer extends BaseAuditable {}
|
||||
|
||||
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
class ProducerAlias extends BaseAuditable
|
||||
{
|
||||
public function producer()
|
||||
{
|
||||
return $this->belongsTo(Producer::class);
|
||||
}
|
||||
}
|
||||
@ -4,12 +4,10 @@
|
||||
|
||||
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
|
||||
{
|
||||
@ -25,49 +23,6 @@ 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);
|
||||
|
||||
@ -8,7 +8,6 @@
|
||||
use App\Models\PriceList;
|
||||
use App\Models\PricelistFile;
|
||||
use App\Support\NameNormalizer;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use App\Enums\PricelistFileStatusEnum;
|
||||
use App\Models\PricelistFileLine;
|
||||
use App\Enums\PricelistFileLineStatusEnum;
|
||||
@ -66,23 +65,6 @@ class PricelistFileProcessService
|
||||
'header' => PriceListService::EXPECTED_HEADERS[18], // Hooreyca mennyiségi szorzó
|
||||
'type' => 'float'
|
||||
],
|
||||
// A Hooreyca-blokk (16-19) negyedik mezője. Korábban kimaradt innen, ezért a
|
||||
// változása némán átment: importáláskor beíródott, de a "Módosulások" között
|
||||
// nem jelent meg. Az Ügyvitel ezt az adatot folyamatosan javítja, és a Hooreyca
|
||||
// rendszerrel való eltérés náluk hibaként jelentkezik - a változást tehát MINDIG
|
||||
// jelezni kell (a hiányát a blokk kötelezőség-ellenőrzése fogja meg).
|
||||
'buyerProductName' => [
|
||||
'header' => PriceListService::EXPECTED_HEADERS[19], // Vevői megnevezés
|
||||
'type' => 'string'
|
||||
],
|
||||
'packing' => [
|
||||
'header' => PriceListService::EXPECTED_HEADERS[5], // Kiszerelés
|
||||
'type' => 'float'
|
||||
],
|
||||
'krel' => [
|
||||
'header' => PriceListService::EXPECTED_HEADERS[21], // KREL
|
||||
'type' => 'bool'
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
@ -872,20 +854,12 @@ protected function getProducerLookupMap(): array
|
||||
// Az összevont (archive) és a törölt gyártók kimaradnak: enélkül a
|
||||
// duplikáció-takarítás hatástalan lenne, mert a beolvasztott rekord
|
||||
// továbbra is visszakerülne a feloldásba.
|
||||
$producerMap = \App\Models\Producer::query()
|
||||
return \App\Models\Producer::query()
|
||||
->whereNotIn('status', [DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted])
|
||||
->get()
|
||||
->keyBy(fn($p) => $this->normalizeForComparison($p->name))
|
||||
->map->id
|
||||
->toArray();
|
||||
|
||||
// Az árlisták a beolvasztott, régi gyártóneveket is használják. A producer-térkép
|
||||
// áll a `+` operátor BAL oldalán, hogy egyezés esetén az ő bejegyzése nyerjen
|
||||
// (a `+` a bal oldali értéket tartja meg ütköző kulcsnál) - az alias sosem írhat
|
||||
// felül élő gyártónevet.
|
||||
$aliasMap = (new ProducerAliasResolver)->lookupMap();
|
||||
|
||||
return $producerMap + $aliasMap;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1056,10 +1030,8 @@ protected function validateProducer(array $payload, array $producerLookup): ?str
|
||||
{
|
||||
$producerName = $payload[PriceListService::EXPECTED_HEADERS[8]] ?? null;
|
||||
|
||||
// A gyártó nem kötelező (EV3-357): üres oszlop nem hiba, egyszerűen nincs
|
||||
// gyártó-adat erre a sorra.
|
||||
if (empty(trim((string)$producerName))) {
|
||||
return null;
|
||||
return "Hiányzó gyártó megnevezés.";
|
||||
}
|
||||
|
||||
$normalizedName = $this->normalizeForComparison((string)$producerName);
|
||||
@ -1097,9 +1069,7 @@ protected function runBusinessValidation(PricelistFile $pricelistFile, bool $has
|
||||
// 1. Kötelező mezők ellenőrzése (0-2, 4-12 és 14)
|
||||
// Megjegyzés: az "Alcsoport 2" (3. index) NEM kötelező, mivel vannak
|
||||
// olyan termékek, amelyek csak az "Alcsoport 1" szinthez vannak rendelve.
|
||||
// A "Gyártó/Forgalmazó" (8. index) sem kötelező: van beszállító (pl. piaci
|
||||
// zöldségnagyker), akinél nincs értelmes gyártó-adat minden sorhoz (EV3-357).
|
||||
$mandatoryIndexes = [0, 1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 14];
|
||||
$mandatoryIndexes = [0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14];
|
||||
foreach ($mandatoryIndexes as $mIndex) {
|
||||
$mLabel = PriceListService::EXPECTED_HEADERS[$mIndex];
|
||||
$mValue = $payload[$mLabel] ?? null;
|
||||
@ -1107,6 +1077,7 @@ protected function runBusinessValidation(PricelistFile $pricelistFile, bool $has
|
||||
// Megfelelő kulcsot választunk, hogy a specifikus validátorok felülírhassák
|
||||
$mKey = match($mIndex) {
|
||||
7 => 'product_unit',
|
||||
8 => 'producer',
|
||||
9 => 'seller_unit',
|
||||
11 => 'amount_unit',
|
||||
12 => 'vat',
|
||||
@ -1226,18 +1197,6 @@ protected function runBusinessValidation(PricelistFile $pricelistFile, bool $has
|
||||
'new_label' => $producerIdToName[(int)$producerId] ?? ($producerId > 0 ? "Ismeretlen gyártó ($producerId)" : 'N/A'),
|
||||
'label' => PriceListService::EXPECTED_HEADERS[8]
|
||||
];
|
||||
} elseif ($producerId === null && trim((string)$producerName) === '' && $oldProducerId > 0) {
|
||||
// A gyártó opcionális, de a terméknek eddig volt mentett gyártója, és az
|
||||
// árlista sora most üresen hagyja az oszlopot: ez törlésnek/módosulásnak
|
||||
// számít, végrehajtáskor a producer_id null-ra íródna felül (EV3-357).
|
||||
$isUpdated = true;
|
||||
$diff['producer_id'] = [
|
||||
'old' => $oldProducerId,
|
||||
'new' => null,
|
||||
'old_label' => $producerIdToName[$oldProducerId] ?? "Ismeretlen gyártó ($oldProducerId)",
|
||||
'new_label' => 'N/A',
|
||||
'label' => PriceListService::EXPECTED_HEADERS[8]
|
||||
];
|
||||
}
|
||||
|
||||
// 2. Termékcsoport módosulás
|
||||
@ -1276,35 +1235,14 @@ protected function runBusinessValidation(PricelistFile $pricelistFile, bool $has
|
||||
}
|
||||
|
||||
$currentValue = (float)$currentValue;
|
||||
} elseif ($config['type'] === 'bool') {
|
||||
// booleanCustom, ugyanaz a szabály, mint az importálásnál:
|
||||
// üres cella => nem, bármilyen érték (pl. "X") => igen.
|
||||
// Nyers összehasonlítással az üres cella és a 0 minden soron
|
||||
// eltérésnek látszana, mert PHP 8-ban '' == 0 már hamis.
|
||||
$excelValue = strlen(trim((string)$excelValue)) > 0;
|
||||
$currentValue = (bool)$currentValue;
|
||||
} else {
|
||||
// A tárolt érték körülvágva megy be (castExecutionValue), ezért
|
||||
// az összehasonlításnak is annak kell lennie - különben egy
|
||||
// fájlbeli záró szóköz ÖRÖK módosulást mutatna: az import
|
||||
// trimmelve írja ki, a következő fájl megint jelezné.
|
||||
$excelValue = $excelValue === null ? null : trim((string)$excelValue);
|
||||
$currentValue = $currentValue === null ? null : trim((string)$currentValue);
|
||||
}
|
||||
|
||||
if ($excelValue != $currentValue) {
|
||||
$entry = [
|
||||
$diff[$modelField] = [
|
||||
'old' => $currentValue,
|
||||
'new' => $excelValue,
|
||||
'label' => $config['header']
|
||||
];
|
||||
|
||||
if ($config['type'] === 'bool') {
|
||||
$entry['old_label'] = $currentValue ? 'Igen' : 'Nem';
|
||||
$entry['new_label'] = $excelValue ? 'Igen' : 'Nem';
|
||||
}
|
||||
|
||||
$diff[$modelField] = $entry;
|
||||
$isUpdated = true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,11 +3,8 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Models\ProducerAlias;
|
||||
use App\Support\NameNormalizer;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Duplikált gyártó törzsadat felderítése és összevonása.
|
||||
@ -46,8 +43,6 @@ class ProducerDeduplicator
|
||||
|
||||
public const DIFF_MIXED = 'vegyes';
|
||||
|
||||
public function __construct(private ProducerAliasResolver $aliasResolver = new ProducerAliasResolver) {}
|
||||
|
||||
/**
|
||||
* Duplikált névcsoportok, csoportonként a tagokkal és a hivatkozás-darabszámokkal.
|
||||
* A tagok rendezettek: az első a javasolt megtartandó (legtöbb termék).
|
||||
@ -377,78 +372,7 @@ public function buildPlan(array $decisions): array
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'merges' => $merges,
|
||||
'errors' => $errors,
|
||||
'skipped' => $skipped,
|
||||
'blocking' => $this->detectNameCollisions($merges),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Névütközés: két gyártó ugyanarra a névre kerülne a végrehajtás után.
|
||||
*
|
||||
* Ez akkor fordul elő, ha a megrendelő két KÜLÖN lap-csoportnak ugyanazt a végleges
|
||||
* nevet adja (a szándéka szerint egy cégről van szó), vagy ha a végleges név egy
|
||||
* olyan gyártó neve, amely nem vesz részt az összevonásban. Mindkét esetben két
|
||||
* azonos nevű aktív gyártó maradna - vagyis a takarítás maga állítana elő
|
||||
* duplikátumot. Ezért ez BLOKKOLÓ hiba: a végrehajtás csak a lap javítása (a
|
||||
* csoportok egybetétele) után indulhat, és a --force sem kerüli meg.
|
||||
*
|
||||
* @param array<int, array> $merges
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function detectNameCollisions(array $merges): array
|
||||
{
|
||||
$mergedAway = [];
|
||||
$keeperGroup = [];
|
||||
$keeperFinalName = [];
|
||||
|
||||
foreach ($merges as $merge) {
|
||||
$keeperGroup[$merge['keeper_id']] = $merge['group'];
|
||||
$keeperFinalName[$merge['keeper_id']] = $merge['final_name'];
|
||||
|
||||
foreach ($merge['from'] as $from) {
|
||||
$mergedAway[$from['id']] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// A végrehajtás UTÁNI aktív névállomány
|
||||
$resulting = [];
|
||||
foreach ($this->activeMembers() as $member) {
|
||||
$producer = $member['producer'];
|
||||
|
||||
if (isset($mergedAway[$producer->id])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = $keeperFinalName[$producer->id] ?? (string) $producer->name;
|
||||
$resulting[NameNormalizer::normalize($name)][] = [
|
||||
'id' => $producer->id,
|
||||
'name' => $name,
|
||||
'group' => $keeperGroup[$producer->id] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
$blocking = [];
|
||||
|
||||
foreach ($resulting as $entries) {
|
||||
// Csak azt jelezzük, amit EZ a terv okoz - a lapon kívüli, már meglévő
|
||||
// duplikátumokat nem (azok egy következő kör dolgai).
|
||||
if (count($entries) < 2 || array_filter(array_column($entries, 'group'), fn ($g) => $g !== null) === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts = array_map(fn ($e) => $e['group'] !== null
|
||||
? $e['group'] . '. csoport (#' . $e['id'] . ')'
|
||||
: 'a lapon kívüli #' . $e['id'] . ' gyártó', $entries);
|
||||
|
||||
$blocking[] = 'Névütközés: ' . implode(' és ', $parts) . ' ugyanarra a névre kerülne: "'
|
||||
. $entries[0]['name'] . '". Ha ugyanaz a cég, tedd őket egy csoportba (azonos '
|
||||
. 'csoportszám); ha nem, adj nekik eltérő végleges nevet.';
|
||||
}
|
||||
|
||||
return $blocking;
|
||||
return ['merges' => $merges, 'errors' => $errors, 'skipped' => $skipped];
|
||||
}
|
||||
|
||||
/**
|
||||
@ -521,7 +445,6 @@ public function apply(array $merges): array
|
||||
'merges' => [],
|
||||
'restore' => [],
|
||||
'totals' => array_fill_keys(array_keys(self::REFERENCING_TABLES), 0),
|
||||
'alias_warnings' => [],
|
||||
];
|
||||
|
||||
// producer_id leképezés: honnan => hova
|
||||
@ -558,18 +481,6 @@ public function apply(array $merges): array
|
||||
$report['totals'][$table] = $this->remap($table, $column, $map);
|
||||
}
|
||||
|
||||
$report['restore']['created_alias_ids'] = [];
|
||||
|
||||
// 2b. Ha egy vesztes gyártóhoz már volt alias (mert korábban ő volt egy MÁSIK
|
||||
// összevonás keepere), az árva maradna: a lookupMap csak aktív gyártóhoz
|
||||
// tartozó aliast ad vissza. Átpontozzuk az új keeperre.
|
||||
$existingAliases = ProducerAlias::whereIn('producer_id', array_keys($map))->get(['id', 'producer_id']);
|
||||
$report['restore']['repointed_aliases'] = $existingAliases->pluck('producer_id', 'id')->toArray();
|
||||
|
||||
foreach ($existingAliases->groupBy('producer_id') as $fromId => $aliases) {
|
||||
ProducerAlias::whereIn('id', $aliases->pluck('id'))->update(['producer_id' => $map[$fromId]]);
|
||||
}
|
||||
|
||||
// 3. A gyártó rekordok rendezése
|
||||
foreach ($merges as $merge) {
|
||||
if ($merge['rename']) {
|
||||
@ -590,15 +501,6 @@ public function apply(array $merges): array
|
||||
)),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// A régi név mostantól alias - az árlisták ezt még használhatják.
|
||||
$this->writeAlias($merge['keeper_id'], $from['name'], $merge['final_name'], $report);
|
||||
}
|
||||
|
||||
// Ha a keeper is átnevezésre került, a SAJÁT eredeti neve is elveszne -
|
||||
// ez a jelentésen kívül sehol nem marad meg, ezért ezt is aliasként mentjük.
|
||||
if ($merge['rename']) {
|
||||
$this->writeAlias($merge['keeper_id'], $merge['keeper_name'], $merge['final_name'], $report);
|
||||
}
|
||||
|
||||
$report['merges'][] = [
|
||||
@ -611,52 +513,6 @@ public function apply(array $merges): array
|
||||
return $report;
|
||||
}
|
||||
|
||||
/**
|
||||
* Egy régi név aliasként mentése a keeperhez. Ütközés esetén nem szakítja meg a
|
||||
* végrehajtást (a csoportosítás elvileg már ütközésmentes, ez csak védőháló) -
|
||||
* helyette figyelmeztetést gyűjt a jelentésbe.
|
||||
*/
|
||||
private function writeAlias(int $keeperId, string $candidateName, string $liveName, array &$report): void
|
||||
{
|
||||
$normalized = NameNormalizer::normalize($candidateName);
|
||||
|
||||
if ($normalized === NameNormalizer::normalize($liveName)) {
|
||||
return; // megegyezik az élő névvel, felesleges alias lenne
|
||||
}
|
||||
|
||||
// Előfordulhat, hogy a csoport két tagja (pl. a vesztes neve és a keeper
|
||||
// átnevezés előtti neve) normalizálva ugyanarra esik - ilyenkor a második írás
|
||||
// a DB unique indexbe ütközne. Explicit kezeljük, mert az assertNameAvailable
|
||||
// az ignoreProducerId miatt "sajátként" engedné át, holott ez már létezik.
|
||||
$existing = ProducerAlias::where('normalized_name', $normalized)->first();
|
||||
|
||||
if ($existing) {
|
||||
if ($existing->producer_id !== $keeperId) {
|
||||
$report['alias_warnings'][] = "A(z) \"{$candidateName}\" már alias a(z) #{$existing->producer_id} "
|
||||
. "gyártóhoz, nem írható át a(z) #{$keeperId} alá.";
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->aliasResolver->assertNameAvailable($candidateName, $keeperId);
|
||||
} catch (RuntimeException $e) {
|
||||
$report['alias_warnings'][] = $e->getMessage();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$alias = ProducerAlias::create([
|
||||
'producer_id' => $keeperId,
|
||||
'name' => $candidateName,
|
||||
'normalized_name' => NameNormalizer::normalize($candidateName),
|
||||
'source' => 'dedupe',
|
||||
]);
|
||||
|
||||
$report['restore']['created_alias_ids'][] = $alias->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Egyetlen UPDATE táblánként, CASE leképezéssel.
|
||||
*/
|
||||
@ -722,37 +578,6 @@ public function rollback(array $report): array
|
||||
]);
|
||||
}
|
||||
|
||||
// Alias visszagörgetés: az apply() által létrehozott aliasok törlése, az
|
||||
// időközben átpontozottak visszaállítása az eredeti (akkor még aktív) gyártóra.
|
||||
ProducerAlias::whereIn('id', (array) ($report['restore']['created_alias_ids'] ?? []))->delete();
|
||||
|
||||
foreach ((array) ($report['restore']['repointed_aliases'] ?? []) as $aliasId => $originalProducerId) {
|
||||
ProducerAlias::where('id', (int) $aliasId)->update(['producer_id' => (int) $originalProducerId]);
|
||||
}
|
||||
|
||||
return $restored;
|
||||
}
|
||||
|
||||
/**
|
||||
* A jelentés lemezre írása - ugyanabba a helyre és ugyanolyan formában, akár a CLI
|
||||
* `producers:dedupe --report`, akár a felületi gyártó-összevonás (EV3-473, 7. lépés)
|
||||
* hívja. Enélkül egy felületről indított összevonás nem lenne fejlesztői kézzel
|
||||
* visszagörgethető a meglévő `producers:dedupe --rollback`-kal.
|
||||
*/
|
||||
public function writeReport(array $report, ?string $path = null): string
|
||||
{
|
||||
// Mikroszekundum a névben: a felületi összevonás (EV3-473, 7. lépés) miatt már
|
||||
// reális, hogy egy másodpercen belül több jelentés is készül - a másodperc
|
||||
// pontosságú név csendben felülírta volna az előzőt.
|
||||
$path ??= storage_path('app/private/producers-dedupe-' . now()->format('Y-m-d_His_u') . '.json');
|
||||
|
||||
$directory = dirname($path);
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0775, true);
|
||||
}
|
||||
|
||||
file_put_contents($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,18 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Az alias-jelölt neve egy MÁSIK, aktív gyártóéval ütközik - ez a `RuntimeException`
|
||||
* egy megkülönböztetett alesete, hogy a felhasználói felület fel tudja ajánlani a
|
||||
* két gyártó összevonását (EV3-473, 7. lépés), ne csak elutasítsa a kérést.
|
||||
*/
|
||||
class ActiveProducerNameCollisionException extends RuntimeException
|
||||
{
|
||||
public function __construct(string $message, public readonly int $collidingProducerId)
|
||||
{
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
@ -1,70 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Models\Producer;
|
||||
use App\Models\ProducerAlias;
|
||||
use App\Support\Exceptions\ActiveProducerNameCollisionException;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Gyártó-alias feloldás és ütközés-védelem.
|
||||
*
|
||||
* Az alias sosem írhat felül élő gyártónevet: ezt a feloldási sorrend (pontos név ->
|
||||
* normalizált név -> alias) ÉS ez az osztály is önállóan biztosítja, hogy egy alias
|
||||
* írásakor se keletkezhessen ütközés.
|
||||
*/
|
||||
class ProducerAliasResolver
|
||||
{
|
||||
/**
|
||||
* normalized_name => producer_id, csak aktív (nem archive/deleted) gyártóhoz
|
||||
* tartozó aliasokra.
|
||||
*/
|
||||
public function lookupMap(): array
|
||||
{
|
||||
return ProducerAlias::query()
|
||||
->whereHas('producer', fn ($q) => $q->whereNotIn('status', [
|
||||
DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted,
|
||||
]))
|
||||
->pluck('producer_id', 'normalized_name')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dob, ha a név normalizált alakja ütközik egy aktív gyártó nevével vagy egy
|
||||
* másik alias-szal. $ignoreProducerId: az a gyártó, amelyikhez az alias éppen
|
||||
* készül - a saját neve nem számít ütközésnek.
|
||||
*/
|
||||
public function assertNameAvailable(string $name, ?int $ignoreProducerId = null): void
|
||||
{
|
||||
$normalized = NameNormalizer::normalize($name);
|
||||
|
||||
if ($normalized === '') {
|
||||
throw new RuntimeException('Az alias neve nem lehet üres.');
|
||||
}
|
||||
|
||||
$collidingProducer = Producer::query()
|
||||
->whereNotIn('status', [DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted])
|
||||
->when($ignoreProducerId, fn ($q) => $q->where('id', '!=', $ignoreProducerId))
|
||||
->get(['id', 'name'])
|
||||
->first(fn ($p) => NameNormalizer::normalize($p->name) === $normalized);
|
||||
|
||||
if ($collidingProducer) {
|
||||
throw new ActiveProducerNameCollisionException(
|
||||
"A(z) \"{$name}\" név ütközik a(z) #{$collidingProducer->id} ({$collidingProducer->name}) aktív gyártóval.",
|
||||
collidingProducerId: $collidingProducer->id,
|
||||
);
|
||||
}
|
||||
|
||||
$collidingAlias = ProducerAlias::where('normalized_name', $normalized)
|
||||
->when($ignoreProducerId, fn ($q) => $q->where('producer_id', '!=', $ignoreProducerId))
|
||||
->first();
|
||||
|
||||
if ($collidingAlias) {
|
||||
throw new RuntimeException(
|
||||
"A(z) \"{$name}\" név már alias a(z) #{$collidingAlias->producer_id} gyártóhoz."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,38 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('producer_aliases', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('producer_id')->constrained('producers')->cascadeOnDelete();
|
||||
$table->string('name');
|
||||
// utf8mb4_bin: a projekt alapértelmezett collationja (utf8mb4_unicode_ci)
|
||||
// ékezet-érzéketlen, tehát "KONIG" és "KÖNIG" ütközne az unique indexben,
|
||||
// holott a NameNormalizer szándékosan NEM old meg ékezeteket (ez a szigorú
|
||||
// automatikus párosítás; az ékezet-tűrés csak a laza javaslatoknál megy,
|
||||
// lásd ProducerDeduplicator::stripAccents()). A binary collation ezt az
|
||||
// eltérést zárja be a PHP- és DB-szintű egyediség-ellenőrzés között.
|
||||
$table->string('normalized_name')->collation('utf8mb4_bin')->unique();
|
||||
$table->string('source')->default('backfill');
|
||||
$table->timestamps();
|
||||
$table->userIdFields();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('producer_aliases');
|
||||
}
|
||||
};
|
||||
@ -634,26 +634,6 @@ CREATE TABLE `pricelist_files` (
|
||||
CONSTRAINT `pricelist_files_supplier_id_foreign` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`) ON DELETE SET NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
/*!40101 SET character_set_client = @saved_cs_client */;
|
||||
DROP TABLE IF EXISTS `producer_aliases`;
|
||||
/*!40101 SET @saved_cs_client = @@character_set_client */;
|
||||
/*!40101 SET character_set_client = utf8mb4 */;
|
||||
CREATE TABLE `producer_aliases` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`producer_id` bigint(20) unsigned NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`normalized_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
|
||||
`source` varchar(255) NOT NULL DEFAULT 'backfill',
|
||||
`created_at` timestamp NULL DEFAULT NULL,
|
||||
`updated_at` timestamp NULL DEFAULT NULL,
|
||||
`created_by` int(10) unsigned DEFAULT NULL,
|
||||
`updated_by` int(10) unsigned DEFAULT NULL,
|
||||
`deleted_by` int(10) unsigned DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `producer_aliases_normalized_name_unique` (`normalized_name`),
|
||||
KEY `producer_aliases_producer_id_foreign` (`producer_id`),
|
||||
CONSTRAINT `producer_aliases_producer_id_foreign` FOREIGN KEY (`producer_id`) REFERENCES `producers` (`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
/*!40101 SET character_set_client = @saved_cs_client */;
|
||||
DROP TABLE IF EXISTS `producers`;
|
||||
/*!40101 SET @saved_cs_client = @@character_set_client */;
|
||||
/*!40101 SET character_set_client = utf8mb4 */;
|
||||
@ -1200,5 +1180,4 @@ INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (888,'2026_08_10_09
|
||||
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (889,'2026_08_10_090100_add_execution_fields_to_pricelist_file_lines_table',28);
|
||||
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (890,'2026_08_16_090000_create_deployment_packages_table',29);
|
||||
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (892,'2026_08_24_172116_add_meter_unit_to_seller_and_amount_unit_columns',30);
|
||||
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (894,'2026_09_18_120000_create_producer_aliases_table',31);
|
||||
commit;
|
||||
|
||||
@ -47,18 +47,6 @@ 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'],
|
||||
[
|
||||
|
||||
@ -19,27 +19,17 @@
|
||||
['name' => 'productGroup', 'displayName' => 'Termékcsoportok', 'icon' => 'category', 'link' => route('legacy.show', ['path' => 'admin/productGroup']), 'roles' => ['root','developer','admin']],
|
||||
['name' => 'product', 'displayName' => 'Termék', 'icon' => 'raktar', 'link' => route('legacy.show', ['path' => 'admin/product']), 'roles' => ['root','developer','admin']],
|
||||
['name' => 'supplier', 'displayName' => 'Beszállító adatbázis', 'icon' => 'supplier', 'link' => route('legacy.show', ['path' => 'admin/supplier']), 'roles' => ['root','developer','admin','profit-center']],
|
||||
// A legacy "Webrendelős árlisták" (admin/priceList) szándékosan hiányzik innen:
|
||||
// EV3-473, a régi és az új árlista-import egyidejű elérhetőségét magas
|
||||
// kockázatúnak minősítettük, a megrendelő elfogadta a kivezetést a
|
||||
// prod-frissítéskor. Addig is csak az Árlista feldolgozó (új) érhető el.
|
||||
['name' => 'priceList', 'displayName' => 'Webrendelős árlisták', 'icon' => 'price_list2', 'link' => route('legacy.show', ['path' => 'admin/priceList']), 'roles' => ['root','developer','admin','profit-center']],
|
||||
['name' => 'priceListProfitCenter','displayName' => 'PC Árlista', 'icon' => 'price_list_user','link' => route('legacy.show', ['path' => 'admin/priceListProfitCenter']), 'roles' => ['root','developer','admin']],
|
||||
['name' => 'profitCenter', 'displayName' => 'Profitcenter', 'icon' => 'profitCenter', 'link' => route('legacy.show', ['path' => 'admin/profitCenter']), 'roles' => ['root','developer','admin']],
|
||||
['name' => 'fileBatchUpload', 'displayName' => 'Tömeges Feltöltés', 'icon' => 'upload', 'link' => route('legacy.show', ['path' => 'admin/fileBatchUpload']), 'roles' => ['root','developer','admin']],
|
||||
['name' => 'statistics', 'displayName' => 'Statisztikák', 'icon' => 'kimutatasok', 'link' => route('legacy.show', ['path' => 'admin/statistics']), 'roles' => ['root','developer','admin']],
|
||||
['name' => 'export', 'displayName' => 'Export', 'icon' => 'export', 'link' => route('legacy.show', ['path' => 'admin/export']), 'roles' => ['root','developer','admin']],
|
||||
['name' => 'priceListProcessor', 'displayName' => 'Árlista feldolgozó', 'icon' => 'price_list', 'link' => '/admin/pricelist-files', 'roles' => ['root','developer','admin']],
|
||||
['name' => 'producers', 'displayName' => 'Gyártók', 'icon' => 'supplier', 'link' => '/admin/producers', 'roles' => ['root','developer','admin']],
|
||||
['name' => 'delivery', 'displayName' => 'Szállítás', 'icon' => 'timetable3', 'roles' => ['root','admin','developer'], 'children' => $deliveryChildren],
|
||||
['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
|
||||
|
||||
@ -7,8 +7,10 @@
|
||||
'link'=>'?m=dashboard',
|
||||
];
|
||||
if(auth()->check() && auth()->user()->hasRole(['root','developer','admin'])){
|
||||
$priceListRoute=route('admin.priceList.index');
|
||||
$supplierRoute=route('admin.supplier.index');
|
||||
}else{
|
||||
$priceListRoute=route('priceList.index');
|
||||
$supplierRoute=route('supplier.index');
|
||||
};
|
||||
$deliveryChildren=[
|
||||
@ -77,9 +79,14 @@
|
||||
'roles'=>['root','developer','admin','profit-center']
|
||||
],
|
||||
|
||||
// A legacy "Webrendelős árlisták" (admin/priceList) szándékosan hiányzik innen:
|
||||
// EV3-473, lásd a filament/components/speed-button-nav-bar.blade.php azonos
|
||||
// megjegyzését.
|
||||
'priceList'=>[
|
||||
'name'=>'priceList',
|
||||
'DisplayName'=>'Webrendelős árlisták',
|
||||
'icon'=>'price_list2',
|
||||
'link'=>$priceListRoute,
|
||||
//'link'=>route('order.newOrderShow'),
|
||||
'roles'=>['root','developer','admin','profit-center']
|
||||
],
|
||||
|
||||
'priceListProfitCenter'=>[
|
||||
'name'=>'priceListUser',
|
||||
@ -129,14 +136,6 @@
|
||||
'noAjax' => true,
|
||||
'roles' => ['developer','admin'],
|
||||
],
|
||||
'producers' => [
|
||||
'name' => 'producers',
|
||||
'DisplayName' => 'Gyártók',
|
||||
'icon' => 'supplier',
|
||||
'link' => '/admin/producers',
|
||||
'noAjax' => true,
|
||||
'roles' => ['developer','admin'],
|
||||
],
|
||||
'delivery' => [
|
||||
'name' => 'delivery',
|
||||
'DisplayName' => 'Szállítás',
|
||||
@ -186,17 +185,6 @@
|
||||
'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));
|
||||
?>
|
||||
{{--
|
||||
|
||||
@ -27,17 +27,15 @@ public function test_developer_sees_correct_speedbuttons(): void
|
||||
->assertVisible('.iconholderModulproductGroup')
|
||||
->assertVisible('.iconholderModulproduct')
|
||||
->assertVisible('.iconholderModulsupplier')
|
||||
->assertVisible('.iconholderModulpriceList')
|
||||
->assertVisible('.iconholderModulpriceListUser')
|
||||
->assertVisible('.iconholderModulprofitCenter')
|
||||
->assertVisible('.iconholderModulfileBatchUpload')
|
||||
->assertVisible('.iconholderModulstatistics')
|
||||
->assertVisible('.iconholderModulexport')
|
||||
->assertVisible('.iconholderModulpriceListProcessor')
|
||||
->assertVisible('.iconholderModulproducers')
|
||||
// Buttons that should NOT be visible for 'developer' role
|
||||
->assertMissing('.iconholderModulorder')
|
||||
// EV3-473: a legacy árlista-import elérési pontja szándékosan eltűnt
|
||||
->assertMissing('.iconholderModulpriceList');
|
||||
->assertMissing('.iconholderModulorder');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,226 +0,0 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Enums\PricelistFileLineStatusEnum;
|
||||
use App\Enums\PricelistFileStatusEnum;
|
||||
use App\Models\PricelistFile;
|
||||
use App\Models\PricelistFileLine;
|
||||
use App\Models\Producer;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductGroup;
|
||||
use App\Models\Supplier;
|
||||
use App\Services\PriceListService;
|
||||
use App\Services\PricelistFileProcessService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
uses(TestCase::class, RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->supplier = Supplier::factory()->create();
|
||||
|
||||
// A termékcsoport-útvonalat a validálás a fából építi: technikai gyökér, majd
|
||||
// "Fő termékcsoport" és "Alcsoport 1". A gyökeret a feloldás eldobja, így az
|
||||
// árlistában szereplő "Főcsoport|Alcsoport 1" útvonal talál.
|
||||
$root = ProductGroup::create(['name' => 'Főcsoportok', 'type' => 'F',
|
||||
'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$main = ProductGroup::create(['name' => 'Főcsoport', 'type' => 'F',
|
||||
'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$main->appendToNode($root)->save();
|
||||
|
||||
$this->group = ProductGroup::create(['name' => 'Alcsoport 1', 'type' => 'F',
|
||||
'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$this->group->appendToNode($main->refresh())->save();
|
||||
$this->producer = Producer::create(['name' => 'Teszt Gyártó',
|
||||
'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
|
||||
$this->file = PricelistFile::create([
|
||||
'filename' => 'arlista.xlsx',
|
||||
'supplier_id' => $this->supplier->id,
|
||||
'available_date' => now()->addWeek()->toDateString(),
|
||||
'status' => PricelistFileStatusEnum::inprogress,
|
||||
]);
|
||||
});
|
||||
|
||||
/**
|
||||
* Meglévő termék + a hozzá tartozó árlista sor, majd az üzleti validálás lefuttatása.
|
||||
* A visszaadott sor a `diff` és `validation_messages` mezőket is tartalmazza, amit a
|
||||
* felület a "Módosulások" alatt, illetve hibaként mutat.
|
||||
*/
|
||||
function lineFor(array $productAttributes, array $payloadOverrides): PricelistFileLine
|
||||
{
|
||||
$test = test();
|
||||
$headers = PriceListService::EXPECTED_HEADERS;
|
||||
|
||||
$product = Product::create(array_merge([
|
||||
'name' => 'Teszt termék',
|
||||
'supplierProductNumber' => 'SKU-1',
|
||||
'supplier_id' => $test->supplier->id,
|
||||
'producer_id' => $test->producer->id,
|
||||
'product_group_id' => $test->group->id,
|
||||
'unitValue' => 1,
|
||||
'note' => '',
|
||||
// A Hooreyca-blokk (16-19) együtt kötelező: ha bármelyik ki van töltve, mind
|
||||
// a négynek lennie kell. A terméken is beállítjuk, hogy a vizsgált mezőn
|
||||
// kívül ne keletkezzen más módosulás.
|
||||
'buyerProductName' => 'ALAP MEGNEVEZÉS',
|
||||
'hooreycaId' => 'HERCE0000017872',
|
||||
'HooreycaUnit' => 'DB',
|
||||
'HooreycaMultiplier' => 5,
|
||||
'status' => DbStatusFieldEnum::active,
|
||||
'canSee' => 1,
|
||||
], $productAttributes));
|
||||
|
||||
$payload = array_merge([
|
||||
$headers[0] => 'SKU-1',
|
||||
$headers[1] => 'Főcsoport',
|
||||
$headers[2] => 'Alcsoport 1',
|
||||
$headers[4] => 'Teszt termék',
|
||||
$headers[5] => '1',
|
||||
$headers[6] => '1',
|
||||
$headers[7] => 'l',
|
||||
$headers[8] => 'Teszt Gyártó',
|
||||
$headers[9] => 'kart',
|
||||
$headers[10] => '1',
|
||||
$headers[11] => 'db',
|
||||
$headers[12] => '27',
|
||||
$headers[14] => '100',
|
||||
$headers[16] => 'HERCE0000017872',
|
||||
$headers[17] => 'DB',
|
||||
$headers[18] => '5',
|
||||
$headers[19] => 'ALAP MEGNEVEZÉS',
|
||||
$headers[20] => '',
|
||||
$headers[21] => '',
|
||||
], $payloadOverrides);
|
||||
|
||||
$line = PricelistFileLine::create([
|
||||
'pricelist_file_id' => $test->file->id,
|
||||
'row_number' => 5,
|
||||
'status' => PricelistFileLineStatusEnum::ok,
|
||||
'payload' => $payload,
|
||||
]);
|
||||
|
||||
$method = new ReflectionMethod(PricelistFileProcessService::class, 'runBusinessValidation');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke(app(PricelistFileProcessService::class), $test->file, false);
|
||||
|
||||
return $line->refresh();
|
||||
}
|
||||
|
||||
function diffFor(array $productAttributes, array $payloadOverrides): array
|
||||
{
|
||||
return lineFor($productAttributes, $payloadOverrides)->diff ?? [];
|
||||
}
|
||||
|
||||
test('a Vevői megnevezés változása megjelenik a módosulások között', function () {
|
||||
// A Hooreyca-blokk negyedik mezője. Korábban importáláskor beíródott, de a
|
||||
// változása nem jelent meg sehol - ezt jelezte a megrendelő (EV3-357).
|
||||
$headers = PriceListService::EXPECTED_HEADERS;
|
||||
|
||||
$diff = diffFor(
|
||||
['buyerProductName' => 'TEHÉNTÚRÓ CSOMAGOLT 18%'],
|
||||
[$headers[19] => 'TEHÉNTÚRÓ LÉDIG 18%'],
|
||||
);
|
||||
|
||||
expect($diff)->toHaveKey('buyerProductName')
|
||||
->and($diff['buyerProductName']['old'])->toBe('TEHÉNTÚRÓ CSOMAGOLT 18%')
|
||||
->and($diff['buyerProductName']['new'])->toBe('TEHÉNTÚRÓ LÉDIG 18%')
|
||||
->and($diff['buyerProductName']['label'])->toBe($headers[19]);
|
||||
});
|
||||
|
||||
test('az üresről kitöltöttre váltó Vevői megnevezés is módosulás', function () {
|
||||
// Pontosan ez volt a "pöttyös protein rudi" esete: a terméken nem volt érték,
|
||||
// az árlista viszont hozott egyet.
|
||||
$diff = diffFor(
|
||||
['buyerProductName' => null],
|
||||
[PriceListService::EXPECTED_HEADERS[19] => 'PÖTTYÖS TÚRÓ RUDI PROTEIN 18%'],
|
||||
);
|
||||
|
||||
expect($diff)->toHaveKey('buyerProductName')
|
||||
->and($diff['buyerProductName']['new'])->toBe('PÖTTYÖS TÚRÓ RUDI PROTEIN 18%');
|
||||
});
|
||||
|
||||
test('a változatlan Vevői megnevezés nem jelez módosulást', function () {
|
||||
$diff = diffFor(
|
||||
['buyerProductName' => 'KRÉMTÚRÓ 18%'],
|
||||
[PriceListService::EXPECTED_HEADERS[19] => 'KRÉMTÚRÓ 18%'],
|
||||
);
|
||||
|
||||
expect($diff)->not->toHaveKey('buyerProductName');
|
||||
});
|
||||
|
||||
test('a fájlbeli záró szóköz nem számít módosulásnak', function () {
|
||||
// A tárolt érték körülvágva megy be, ezért az összehasonlításnak is annak kell
|
||||
// lennie - különben ez ÖRÖK módosulást mutatna: az import trimmelve írja ki,
|
||||
// a következő fájl megint jelezné.
|
||||
$diff = diffFor(
|
||||
['buyerProductName' => 'KRÉMTÚRÓ 18%'],
|
||||
[PriceListService::EXPECTED_HEADERS[19] => 'KRÉMTÚRÓ 18% '],
|
||||
);
|
||||
|
||||
expect($diff)->not->toHaveKey('buyerProductName');
|
||||
});
|
||||
|
||||
test('a Kiszerelés változása megjelenik, a számformátum eltérése nem', function () {
|
||||
$headers = PriceListService::EXPECTED_HEADERS;
|
||||
|
||||
expect(diffFor(['packing' => 1], [$headers[5] => '8']))->toHaveKey('packing');
|
||||
|
||||
// "8" és 8 ugyanaz az érték - ez nem módosulás
|
||||
expect(diffFor(['packing' => 8], [$headers[5] => '8']))->not->toHaveKey('packing');
|
||||
});
|
||||
|
||||
test('a KREL bekapcsolása módosulás, olvasható címkékkel', function () {
|
||||
$diff = diffFor(['krel' => 0], [PriceListService::EXPECTED_HEADERS[21] => 'X']);
|
||||
|
||||
expect($diff)->toHaveKey('krel')
|
||||
->and($diff['krel']['old_label'])->toBe('Nem')
|
||||
->and($diff['krel']['new_label'])->toBe('Igen');
|
||||
});
|
||||
|
||||
test('az üres KREL cella nem jelez módosulást a nem KREL-es terméken', function () {
|
||||
// Ez a csapda: nyers összehasonlítással az üres cella és a 0 minden soron
|
||||
// eltérésnek látszana, mert PHP 8-ban '' == 0 már hamis.
|
||||
$diff = diffFor(['krel' => 0], [PriceListService::EXPECTED_HEADERS[21] => '']);
|
||||
|
||||
expect($diff)->not->toHaveKey('krel');
|
||||
});
|
||||
|
||||
test('a KREL kikapcsolása is módosulás', function () {
|
||||
$diff = diffFor(['krel' => 1], [PriceListService::EXPECTED_HEADERS[21] => '']);
|
||||
|
||||
expect($diff)->toHaveKey('krel')
|
||||
->and($diff['krel']['old_label'])->toBe('Igen')
|
||||
->and($diff['krel']['new_label'])->toBe('Nem');
|
||||
});
|
||||
|
||||
test('az üres Gyártó oszlop nem hiba, ha a terméknek eddig sem volt gyártója', function () {
|
||||
// EV3-357: van beszállító (pl. piaci zöldségnagyker), akinél nincs értelmes
|
||||
// gyártó-adat minden sorhoz - ez nem lehet kötelező mező.
|
||||
$line = lineFor(
|
||||
['producer_id' => null],
|
||||
[PriceListService::EXPECTED_HEADERS[8] => ''],
|
||||
);
|
||||
|
||||
expect($line->status)->not->toBe(PricelistFileLineStatusEnum::error)
|
||||
->and($line->validation_messages)->not->toHaveKey('producer')
|
||||
->and($line->diff ?? [])->not->toHaveKey('producer_id');
|
||||
});
|
||||
|
||||
test('a gyártó törlése (korábban volt, most üres az oszlop) módosulásnak számít', function () {
|
||||
// A gyártó opcionális lett, DE ha a terméknek eddig volt mentett gyártója, és az
|
||||
// árlista most üresen hozza az oszlopot, azt jelezni kell: végrehajtáskor a
|
||||
// producer_id null-ra íródna felül, ez nem mehet át csendben (EV3-357).
|
||||
$line = lineFor(
|
||||
[], // marad az alapértelmezett producer_id => $this->producer->id
|
||||
[PriceListService::EXPECTED_HEADERS[8] => ''],
|
||||
);
|
||||
|
||||
expect($line->validation_messages)->not->toHaveKey('producer')
|
||||
->and($line->diff)->toHaveKey('producer_id')
|
||||
->and($line->diff['producer_id']['old'])->toBe($this->producer->id)
|
||||
->and($line->diff['producer_id']['new'])->toBeNull()
|
||||
->and($line->diff['producer_id']['old_label'])->toBe('Teszt Gyártó')
|
||||
->and($line->diff['producer_id']['new_label'])->toBe('N/A')
|
||||
->and($line->status)->toBe(PricelistFileLineStatusEnum::updated);
|
||||
});
|
||||
@ -1,264 +0,0 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Filament\Resources\Producers\Pages\CreateProducer;
|
||||
use App\Filament\Resources\Producers\Pages\ListProducers;
|
||||
use App\Filament\Resources\Producers\Pages\ViewProducer;
|
||||
use App\Filament\Resources\Producers\ProducerResource;
|
||||
use App\Filament\Resources\Producers\RelationManagers\AliasesRelationManager;
|
||||
use App\Models\Producer;
|
||||
use App\Models\ProducerAlias;
|
||||
use App\Models\Product;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
uses(TestCase::class, RefreshDatabase::class);
|
||||
|
||||
function actAsDeveloperForProducers(): User
|
||||
{
|
||||
$devRole = Role::firstOrCreate(['name' => 'developer'], ['display_name' => 'Developer']);
|
||||
$developer = User::factory()->create();
|
||||
$developer->addRole($devRole);
|
||||
|
||||
return $developer;
|
||||
}
|
||||
|
||||
test('a gyártó lista oldal renderel', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
|
||||
Livewire::test(ListProducers::class)->assertSuccessful();
|
||||
});
|
||||
|
||||
test('a gyártó megtekintő oldal az alias relation managerrel együtt renderel', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
$producer = Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
ProducerAlias::create([
|
||||
'producer_id' => $producer->id,
|
||||
'name' => 'Danone ',
|
||||
'normalized_name' => 'DANONE',
|
||||
'source' => 'backfill',
|
||||
]);
|
||||
|
||||
Livewire::test(ViewProducer::class, ['record' => $producer->getRouteKey()])
|
||||
->assertSuccessful()
|
||||
->assertSee('Danone ');
|
||||
});
|
||||
|
||||
test('a relation manageren keresztül felvett alias ütközését a form visszautasítja', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
Producer::create(['name' => 'Bonduelle', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$producer = Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
|
||||
Livewire::test(AliasesRelationManager::class, [
|
||||
'ownerRecord' => $producer,
|
||||
'pageClass' => ViewProducer::class,
|
||||
])
|
||||
->callTableAction(CreateAction::class, data: ['name' => 'Bonduelle'])
|
||||
->assertHasTableActionErrors(['name']);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(0);
|
||||
});
|
||||
|
||||
test('a relation manageren keresztül felvett alias létrejön és a normalizált név is elmentődik', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
$producer = Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
|
||||
Livewire::test(AliasesRelationManager::class, [
|
||||
'ownerRecord' => $producer,
|
||||
'pageClass' => ViewProducer::class,
|
||||
])->callTableAction(CreateAction::class, data: ['name' => 'Danone Kft']);
|
||||
|
||||
$alias = ProducerAlias::where('producer_id', $producer->id)->sole();
|
||||
|
||||
expect($alias->name)->toBe('Danone Kft')
|
||||
->and($alias->normalized_name)->toBe('DANONE KFT')
|
||||
->and($alias->source)->toBe('manual');
|
||||
});
|
||||
|
||||
test('a relation managerben az alias törölhető', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
$producer = Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$alias = ProducerAlias::create([
|
||||
'producer_id' => $producer->id,
|
||||
'name' => 'Danone Kft',
|
||||
'normalized_name' => 'DANONE KFT',
|
||||
'source' => 'backfill',
|
||||
]);
|
||||
|
||||
Livewire::test(AliasesRelationManager::class, [
|
||||
'ownerRecord' => $producer,
|
||||
'pageClass' => ViewProducer::class,
|
||||
])->callTableAction(DeleteAction::class, record: $alias);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(0);
|
||||
});
|
||||
|
||||
test('a Gyártó összevonása gomb csak aktív gyártónál látszik', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
$active = Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$archived = Producer::create(['name' => 'Danone Kft', 'status' => DbStatusFieldEnum::archive, 'canSee' => 0]);
|
||||
|
||||
Livewire::test(ViewProducer::class, ['record' => $active->getRouteKey()])
|
||||
->assertActionVisible('mergeProducer');
|
||||
|
||||
Livewire::test(ViewProducer::class, ['record' => $archived->getRouteKey()])
|
||||
->assertActionHidden('mergeProducer');
|
||||
});
|
||||
|
||||
test('a Gyártó összevonása gomb ténylegesen összevonja a két aktív gyártót', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
$reportsBefore = collect(glob(storage_path('app/private/producers-dedupe-*.json')));
|
||||
|
||||
$keeper = Producer::create(['name' => 'Szarvasi', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$loser = Producer::create(['name' => 'Szarvas', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$product = Product::create([
|
||||
'name' => 'Teszt termék',
|
||||
'supplierProductNumber' => 'SKU1',
|
||||
'producer_id' => $loser->id,
|
||||
'unitValue' => 1,
|
||||
'note' => '',
|
||||
'status' => DbStatusFieldEnum::active,
|
||||
'canSee' => 1,
|
||||
]);
|
||||
|
||||
Livewire::test(ViewProducer::class, ['record' => $keeper->getRouteKey()])
|
||||
->callAction('mergeProducer', data: ['loser_id' => $loser->id]);
|
||||
|
||||
expect($loser->refresh()->status)->toBe(DbStatusFieldEnum::archive)
|
||||
->and($loser->note)->toContain('Összevonva ide: #' . $keeper->id)
|
||||
->and($keeper->refresh()->name)->toBe('Szarvasi') // nincs átnevezés
|
||||
->and($product->refresh()->producer_id)->toBe($keeper->id);
|
||||
|
||||
$alias = ProducerAlias::where('producer_id', $keeper->id)->sole();
|
||||
expect($alias->name)->toBe('Szarvas');
|
||||
|
||||
collect(glob(storage_path('app/private/producers-dedupe-*.json')))
|
||||
->diff($reportsBefore)
|
||||
->each(fn ($path) => @unlink($path));
|
||||
});
|
||||
|
||||
test('a felületi összevonás jelentés-fájlt ír, ami CLI-vel visszagörgethető', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
$keeper = Producer::create(['name' => 'Szarvasi', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$loser = Producer::create(['name' => 'Szarvas', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
|
||||
$before = collect(glob(storage_path('app/private/producers-dedupe-*.json')));
|
||||
|
||||
Livewire::test(ViewProducer::class, ['record' => $keeper->getRouteKey()])
|
||||
->callAction('mergeProducer', data: ['loser_id' => $loser->id]);
|
||||
|
||||
$after = collect(glob(storage_path('app/private/producers-dedupe-*.json')));
|
||||
$newFiles = $after->diff($before);
|
||||
|
||||
expect($newFiles)->toHaveCount(1);
|
||||
|
||||
$report = json_decode(file_get_contents($newFiles->first()), true);
|
||||
expect($report['merges'][0]['keeper_id'])->toBe($keeper->id);
|
||||
|
||||
app(\App\Services\ProducerDeduplicator::class)->rollback($report);
|
||||
|
||||
expect($loser->refresh()->status)->toBe(DbStatusFieldEnum::active);
|
||||
|
||||
@unlink($newFiles->first());
|
||||
});
|
||||
|
||||
test('a relation manager elutasítja az aktív gyártóval ütköző alias-t', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
Producer::create(['name' => 'Szarvas', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$producer = Producer::create(['name' => 'Szarvasi', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
|
||||
Livewire::test(AliasesRelationManager::class, [
|
||||
'ownerRecord' => $producer,
|
||||
'pageClass' => ViewProducer::class,
|
||||
])
|
||||
->callTableAction(CreateAction::class, data: ['name' => 'Szarvas'])
|
||||
->assertHasTableActionErrors(['name']);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(0);
|
||||
});
|
||||
|
||||
test('új gyártó kézzel felvehető, és a megtekintő oldalra irányít vissza', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
Livewire::test(CreateProducer::class)
|
||||
->fillForm(['name' => 'Kiss Tej Kft'])
|
||||
->call('create')
|
||||
->assertHasNoFormErrors();
|
||||
|
||||
$producer = Producer::where('name', 'Kiss Tej Kft')->sole();
|
||||
|
||||
expect($producer->status)->toBe(DbStatusFieldEnum::active)
|
||||
->and((bool) $producer->canSee)->toBeTrue();
|
||||
});
|
||||
|
||||
test('a kézi felvétel elutasítja az aktív gyártóval ütköző nevet', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
Producer::create(['name' => 'Kiss Tej Kft', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
|
||||
Livewire::test(CreateProducer::class)
|
||||
->fillForm(['name' => 'kiss tej kft'])
|
||||
->call('create')
|
||||
->assertHasFormErrors(['name']);
|
||||
|
||||
expect(Producer::count())->toBe(1);
|
||||
});
|
||||
|
||||
test('a kézi felvétel elutasítja a már létező aliassal ütköző nevet', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
$existing = Producer::create(['name' => 'Kiss Tej Kft', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
ProducerAlias::create([
|
||||
'producer_id' => $existing->id,
|
||||
'name' => 'Kiss Tejecske Kft',
|
||||
'normalized_name' => 'KISS TEJECSKE KFT',
|
||||
'source' => 'manual',
|
||||
]);
|
||||
|
||||
Livewire::test(CreateProducer::class)
|
||||
->fillForm(['name' => 'Kiss Tejecske Kft'])
|
||||
->call('create')
|
||||
->assertHasFormErrors(['name']);
|
||||
|
||||
expect(Producer::count())->toBe(1);
|
||||
});
|
||||
|
||||
test('újonnan felvett gyártóhoz rögtön felvehető alias', function () {
|
||||
$this->actingAs(actAsDeveloperForProducers());
|
||||
|
||||
Livewire::test(CreateProducer::class)
|
||||
->fillForm(['name' => 'Kiss Tej Kft'])
|
||||
->call('create')
|
||||
->assertHasNoFormErrors();
|
||||
|
||||
$producer = Producer::where('name', 'Kiss Tej Kft')->sole();
|
||||
|
||||
Livewire::test(AliasesRelationManager::class, [
|
||||
'ownerRecord' => $producer,
|
||||
'pageClass' => ViewProducer::class,
|
||||
])->callTableAction(CreateAction::class, data: ['name' => 'Kiss Tejecske Kft']);
|
||||
|
||||
expect(ProducerAlias::where('producer_id', $producer->id)->sole()->name)->toBe('Kiss Tejecske Kft');
|
||||
});
|
||||
|
||||
test('csak azoknak a szerepköröknek látszik a menüpont, akik elérik az admin felületet', function () {
|
||||
$developer = actAsDeveloperForProducers();
|
||||
|
||||
$this->actingAs($developer);
|
||||
$this->get(ProducerResource::getUrl())->assertOk();
|
||||
});
|
||||
@ -1,161 +0,0 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Models\Producer;
|
||||
use App\Models\ProducerAlias;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
uses(TestCase::class, RefreshDatabase::class);
|
||||
|
||||
/**
|
||||
* @return array<int, array{name: string, origin: string}>
|
||||
*/
|
||||
function writeDedupeReportFixture(string $path, int $keeperId, string $finalName, array $fromNames, ?string $keeperOriginalName = null): void
|
||||
{
|
||||
$report = [
|
||||
'created_at' => now()->toDateTimeString(),
|
||||
'database' => 'fixture',
|
||||
'merges' => [[
|
||||
'keeper_id' => $keeperId,
|
||||
'final_name' => $finalName,
|
||||
'from' => array_map(fn ($n, $i) => ['id' => 1000 + $i, 'name' => $n], $fromNames, array_keys($fromNames)),
|
||||
]],
|
||||
'restore' => [
|
||||
'producers' => $keeperOriginalName !== null
|
||||
? [$keeperId => ['id' => $keeperId, 'name' => $keeperOriginalName]]
|
||||
: [],
|
||||
],
|
||||
];
|
||||
|
||||
file_put_contents($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
test('az archivált gyártó note-jából aliast hoz létre a célrekordhoz --apply mellett', function () {
|
||||
$keeper = Producer::create(['name' => 'Kőröstej Kft.', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
Producer::create([
|
||||
'name' => 'Kőröstej',
|
||||
'status' => DbStatusFieldEnum::archive,
|
||||
'canSee' => 0,
|
||||
'note' => "Összevonva ide: #{$keeper->id} (Kőröstej Kft.) – 2026-09-15 producers:dedupe",
|
||||
]);
|
||||
|
||||
$this->artisan('producers:alias-backfill', ['--apply' => true])->assertExitCode(0);
|
||||
|
||||
expect(ProducerAlias::where('producer_id', $keeper->id)->pluck('name')->all())->toBe(['Kőröstej']);
|
||||
});
|
||||
|
||||
test('--apply nélkül csak kimutat, nem ír adatbázist', function () {
|
||||
$keeper = Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
Producer::create([
|
||||
'name' => 'Danone ',
|
||||
'status' => DbStatusFieldEnum::archive,
|
||||
'canSee' => 0,
|
||||
'note' => "Összevonva ide: #{$keeper->id} (Danone) – 2026-09-15 producers:dedupe",
|
||||
]);
|
||||
|
||||
$this->artisan('producers:alias-backfill')->assertExitCode(0);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(0);
|
||||
});
|
||||
|
||||
test('a láncolt archiválást a jelenlegi aktív rekordig követi', function () {
|
||||
// 1. kör: "Régi A" -> #B, de #B maga is beolvad a 2. körben #C-be.
|
||||
$c = Producer::create(['name' => 'Végleges C', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$b = Producer::create([
|
||||
'name' => 'Köztes B',
|
||||
'status' => DbStatusFieldEnum::archive,
|
||||
'canSee' => 0,
|
||||
'note' => "Összevonva ide: #{$c->id} (Végleges C) – 2026-09-16 producers:dedupe",
|
||||
]);
|
||||
Producer::create([
|
||||
'name' => 'Régi A',
|
||||
'status' => DbStatusFieldEnum::archive,
|
||||
'canSee' => 0,
|
||||
'note' => "Összevonva ide: #{$b->id} (Köztes B) – 2026-09-15 producers:dedupe",
|
||||
]);
|
||||
|
||||
$this->artisan('producers:alias-backfill', ['--apply' => true])->assertExitCode(0);
|
||||
|
||||
expect(ProducerAlias::where('producer_id', $c->id)->pluck('name')->sort()->values()->all())
|
||||
->toBe(['Köztes B', 'Régi A']);
|
||||
});
|
||||
|
||||
test('a feloldhatatlan note-ot kihagyja, nem szakítja meg a futást', function () {
|
||||
Producer::create([
|
||||
'name' => 'Árva Rekord',
|
||||
'status' => DbStatusFieldEnum::archive,
|
||||
'canSee' => 0,
|
||||
'note' => 'Nincs értelmezhető formátum',
|
||||
]);
|
||||
|
||||
$this->artisan('producers:alias-backfill', ['--apply' => true])->assertExitCode(0);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(0);
|
||||
});
|
||||
|
||||
test('a jelentésfájlból névalapon oldja fel a célrekordot', function () {
|
||||
$keeper = Producer::create(['name' => 'Voyagex', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$path = storage_path('app/private/teszt_alias_backfill_report.json');
|
||||
// A "VOYAGEX" szándékosan hiányzik a várt eredményből: normalizálva megegyezik az
|
||||
// élő "Voyagex" névvel, tehát a parancsnak redundánsként ki kell hagynia.
|
||||
writeDedupeReportFixture($path, keeperId: 999, finalName: 'Voyagex', fromNames: ['Voyagex Kft', 'VOYAGEX']);
|
||||
|
||||
$this->artisan('producers:alias-backfill', ['reports' => [$path], '--skip-archives' => true, '--apply' => true])
|
||||
->assertExitCode(0);
|
||||
|
||||
expect(ProducerAlias::where('producer_id', $keeper->id)->pluck('name')->sort()->values()->all())
|
||||
->toBe(['Voyagex Kft']);
|
||||
|
||||
@unlink($path);
|
||||
});
|
||||
|
||||
test('a jelentésben az átnevezett keeper eredeti neve is aliassá válik', function () {
|
||||
$keeper = Producer::create(['name' => 'Végleges Név Kft', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$path = storage_path('app/private/teszt_alias_backfill_rename.json');
|
||||
writeDedupeReportFixture(
|
||||
$path,
|
||||
keeperId: 999,
|
||||
finalName: 'Végleges Név Kft',
|
||||
fromNames: ['Elavult Név'],
|
||||
keeperOriginalName: 'Régi Saját Név'
|
||||
);
|
||||
|
||||
$this->artisan('producers:alias-backfill', ['reports' => [$path], '--skip-archives' => true, '--apply' => true])
|
||||
->assertExitCode(0);
|
||||
|
||||
expect(ProducerAlias::where('producer_id', $keeper->id)->pluck('name')->sort()->values()->all())
|
||||
->toBe(['Elavult Név', 'Régi Saját Név']);
|
||||
|
||||
@unlink($path);
|
||||
});
|
||||
|
||||
test('ütköző jelöltet nem szúr be, csak jelenti', function () {
|
||||
Producer::create(['name' => 'Bonduelle', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
$keeper = Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
Producer::create([
|
||||
'name' => 'Bonduelle', // ugyanaz a név, mint egy MÁSIK élő gyártóé - ütközik
|
||||
'status' => DbStatusFieldEnum::archive,
|
||||
'canSee' => 0,
|
||||
'note' => "Összevonva ide: #{$keeper->id} (Danone) – 2026-09-15 producers:dedupe",
|
||||
]);
|
||||
|
||||
$this->artisan('producers:alias-backfill', ['--apply' => true])->assertExitCode(0);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(0);
|
||||
});
|
||||
|
||||
test('kétszeri futtatás nem hoz létre duplikált aliast (idempotens)', function () {
|
||||
$keeper = Producer::create(['name' => 'Danone', 'status' => DbStatusFieldEnum::active, 'canSee' => 1]);
|
||||
Producer::create([
|
||||
'name' => 'Danone ',
|
||||
'status' => DbStatusFieldEnum::archive,
|
||||
'canSee' => 0,
|
||||
'note' => "Összevonva ide: #{$keeper->id} (Danone) – 2026-09-15 producers:dedupe",
|
||||
]);
|
||||
|
||||
$this->artisan('producers:alias-backfill', ['--apply' => true])->assertExitCode(0);
|
||||
$this->artisan('producers:alias-backfill', ['--apply' => true])->assertExitCode(0);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(1);
|
||||
});
|
||||
@ -3,7 +3,6 @@
|
||||
use App\Console\Commands\ProducersDedupeReport;
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Models\Producer;
|
||||
use App\Models\ProducerAlias;
|
||||
use App\Models\Product;
|
||||
use App\Services\ProducerDeduplicator;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
@ -276,120 +275,6 @@ function decisionsFor(array $rows): array
|
||||
->and($loser->note)->toBeNull();
|
||||
});
|
||||
|
||||
test('az összevonás aliast ír a beolvasztott gyártó nevéből', function () {
|
||||
$keeper = producer('Danone');
|
||||
$loser = producer('Danone Kft');
|
||||
|
||||
$plan = $this->deduplicator->buildPlan(decisionsFor([
|
||||
['id' => $keeper->id, 'final_name' => 'Danone'],
|
||||
['id' => $loser->id, 'final_name' => null],
|
||||
]));
|
||||
|
||||
$this->deduplicator->apply($plan['merges']);
|
||||
|
||||
expect(ProducerAlias::where('producer_id', $keeper->id)->pluck('name')->all())->toBe(['Danone Kft']);
|
||||
});
|
||||
|
||||
test('átnevezésnél a keeper eredeti neve is aliassá válik', function () {
|
||||
$keeper = producer('Danone');
|
||||
$loser = producer('Danone Kft');
|
||||
|
||||
$plan = $this->deduplicator->buildPlan(decisionsFor([
|
||||
['id' => $keeper->id, 'final_name' => 'Danone Magyarország'],
|
||||
['id' => $loser->id, 'final_name' => null],
|
||||
]));
|
||||
|
||||
$this->deduplicator->apply($plan['merges']);
|
||||
|
||||
expect(ProducerAlias::where('producer_id', $keeper->id)->pluck('name')->sort()->values()->all())
|
||||
->toBe(['Danone', 'Danone Kft']);
|
||||
});
|
||||
|
||||
test('ha a vesztes és a keeper eredeti neve normalizálva egyezik, csak egy aliast ír', function () {
|
||||
// "danone" és "Danone " normalizálva ugyanaz - a második írás a DB unique
|
||||
// indexébe ütközne, ha nem lenne explicit kezelve.
|
||||
$keeper = producer('danone');
|
||||
$loser = producer('Danone ');
|
||||
|
||||
$plan = $this->deduplicator->buildPlan(decisionsFor([
|
||||
['id' => $keeper->id, 'final_name' => 'Danone Magyarország'],
|
||||
['id' => $loser->id, 'final_name' => null],
|
||||
]));
|
||||
|
||||
$this->deduplicator->apply($plan['merges']);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(1);
|
||||
});
|
||||
|
||||
test('a korábban keeperként szolgáló, most vesztes gyártó aliasai átpontozódnak', function () {
|
||||
$originalKeeper = producer('Danone');
|
||||
$originalLoser = producer('Danone Kft');
|
||||
|
||||
$firstPlan = $this->deduplicator->buildPlan(decisionsFor([
|
||||
['id' => $originalKeeper->id, 'final_name' => 'Danone'],
|
||||
['id' => $originalLoser->id, 'final_name' => null],
|
||||
]));
|
||||
$this->deduplicator->apply($firstPlan['merges']);
|
||||
|
||||
$alias = ProducerAlias::where('producer_id', $originalKeeper->id)->sole();
|
||||
expect($alias->name)->toBe('Danone Kft');
|
||||
|
||||
// A korábbi keeper most maga is beolvad egy újabb, nagyobb gyártóba. A
|
||||
// sortByKeeperPriority a legtöbb termékkel rendelkezőt választja keepernek -
|
||||
// termék nélkül a régebbi (kisebb ID-jű) rekord nyerne, ezért kell a termék ide.
|
||||
$newKeeper = producer('Danone Csoport');
|
||||
productFor($newKeeper, 'X1');
|
||||
$secondPlan = $this->deduplicator->buildPlan(decisionsFor([
|
||||
['id' => $newKeeper->id, 'final_name' => 'Danone Csoport'],
|
||||
['id' => $originalKeeper->id, 'final_name' => null],
|
||||
]));
|
||||
$this->deduplicator->apply($secondPlan['merges']);
|
||||
|
||||
// Az alias nem árválódhat el: követnie kell a láncot az új keeperig.
|
||||
expect($alias->refresh()->producer_id)->toBe($newKeeper->id);
|
||||
});
|
||||
|
||||
test('ütköző alias-jelöltet nem ír be, csak figyelmeztetést gyűjt a jelentésbe', function () {
|
||||
// Közvetlenül az apply()-t hívjuk, buildPlan() nélkül, mert a lap-validáció
|
||||
// (validateGrouping) blokkolná ezt a mesterséges elrendezést, mielőtt elérnénk
|
||||
// az apply() saját, védőhálóként szolgáló ütközés-ellenőrzését.
|
||||
producer('Bonduelle');
|
||||
$keeper = producer('Danone');
|
||||
$loser = producer('Régi Danone Név');
|
||||
|
||||
$report = $this->deduplicator->apply([[
|
||||
'keeper_id' => $keeper->id,
|
||||
'keeper_name' => $keeper->name,
|
||||
'final_name' => $keeper->name,
|
||||
'rename' => false,
|
||||
'from' => [['id' => $loser->id, 'name' => 'Bonduelle']], // szándékos ütközés
|
||||
]]);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(0)
|
||||
->and($report['alias_warnings'])->toHaveCount(1)
|
||||
->and($report['alias_warnings'][0])->toContain('Bonduelle');
|
||||
|
||||
// A gyártó-archiválás maga nem marad el az alias-ütközés miatt.
|
||||
expect($loser->refresh()->status)->toBe(DbStatusFieldEnum::archive);
|
||||
});
|
||||
|
||||
test('a visszagörgetés törli a létrehozott és visszaállítja az átpontozott aliasokat', function () {
|
||||
$keeper = producer('Danone');
|
||||
$loser = producer('Danone Kft');
|
||||
|
||||
$plan = $this->deduplicator->buildPlan(decisionsFor([
|
||||
['id' => $keeper->id, 'final_name' => 'Danone'],
|
||||
['id' => $loser->id, 'final_name' => null],
|
||||
]));
|
||||
$report = $this->deduplicator->apply($plan['merges']);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(1);
|
||||
|
||||
$this->deduplicator->rollback($report);
|
||||
|
||||
expect(ProducerAlias::count())->toBe(0);
|
||||
});
|
||||
|
||||
test('a döntési lap legenerálható és visszaolvasható', function () {
|
||||
$keeper = producer('Danone');
|
||||
$loser = producer('Danone ');
|
||||
@ -438,100 +323,3 @@ function decisionsFor(array $rows): array
|
||||
|
||||
@unlink($path);
|
||||
});
|
||||
|
||||
/**
|
||||
* Kitöltött döntési lap írása a parancs számára (a fejlécnév alapján olvassa vissza).
|
||||
*
|
||||
* @param array<int, array{group: int, id: int, final_name: ?string}> $rows
|
||||
*/
|
||||
function writeDecisionSheet(string $path, array $rows): void
|
||||
{
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
$sheet->setCellValue('A1', ProducersDedupeReport::COLUMN_GROUP);
|
||||
$sheet->setCellValue('B1', ProducersDedupeReport::COLUMN_ID);
|
||||
$sheet->setCellValue('C1', ProducersDedupeReport::COLUMN_FINAL_NAME);
|
||||
|
||||
foreach ($rows as $i => $row) {
|
||||
$sheet->setCellValue('A' . ($i + 2), $row['group']);
|
||||
$sheet->setCellValue('B' . ($i + 2), $row['id']);
|
||||
$sheet->setCellValue('C' . ($i + 2), $row['final_name'] ?? '');
|
||||
}
|
||||
|
||||
(new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet))->save($path);
|
||||
}
|
||||
|
||||
test('két csoport azonos végleges névvel blokkoló névütközés', function () {
|
||||
// A megrendelő két külön csoportnak ugyanazt a nevet adta (egy cégről van szó).
|
||||
// Végrehajtva két azonos nevű gyártó maradna - a takarítás maga gyártana duplikátumot.
|
||||
$a1 = producer('MARS MAGYARORSZÁG ÉRTÉKESÍTŐ BT');
|
||||
$a2 = producer('MARS MAGYARORSZÁG ÉRTÉKESÍTO BT');
|
||||
$b1 = producer('MARS MO ÉRTÉKESÍTŐ BT (WRIGLEY)');
|
||||
$b2 = producer('MARS MO ÉRTÉKESÍTO BT (WRIGLEY)');
|
||||
|
||||
$plan = $this->deduplicator->buildPlan([
|
||||
['group' => 27, 'id' => $a1->id, 'final_name' => 'MARS MAGYARORSZÁG ÉRTÉKESÍTŐ BT'],
|
||||
['group' => 27, 'id' => $a2->id, 'final_name' => null],
|
||||
['group' => 28, 'id' => $b1->id, 'final_name' => 'MARS MAGYARORSZÁG ÉRTÉKESÍTŐ BT'],
|
||||
['group' => 28, 'id' => $b2->id, 'final_name' => null],
|
||||
]);
|
||||
|
||||
expect($plan['blocking'])->toHaveCount(1)
|
||||
->and($plan['blocking'][0])->toContain('27. csoport')->toContain('28. csoport');
|
||||
});
|
||||
|
||||
test('egy csoportba téve ugyanaz a döntés már nem ütközik', function () {
|
||||
$a1 = producer('MARS MAGYARORSZÁG ÉRTÉKESÍTŐ BT');
|
||||
$a2 = producer('MARS MAGYARORSZÁG ÉRTÉKESÍTO BT');
|
||||
$b1 = producer('MARS MO ÉRTÉKESÍTŐ BT (WRIGLEY)');
|
||||
$b2 = producer('MARS MO ÉRTÉKESÍTO BT (WRIGLEY)');
|
||||
|
||||
$plan = $this->deduplicator->buildPlan([
|
||||
['group' => 27, 'id' => $a1->id, 'final_name' => 'MARS MAGYARORSZÁG ÉRTÉKESÍTŐ BT'],
|
||||
['group' => 27, 'id' => $a2->id, 'final_name' => null],
|
||||
['group' => 27, 'id' => $b1->id, 'final_name' => 'MARS MAGYARORSZÁG ÉRTÉKESÍTŐ BT'],
|
||||
['group' => 27, 'id' => $b2->id, 'final_name' => null],
|
||||
]);
|
||||
|
||||
expect($plan['blocking'])->toBe([])
|
||||
->and($plan['merges'])->toHaveCount(1)
|
||||
->and($plan['merges'][0]['from'])->toHaveCount(3);
|
||||
});
|
||||
|
||||
test('a lapon kívüli, meglévő gyártó nevére nevezés is blokkoló', function () {
|
||||
$outside = producer('Biopont Kft.');
|
||||
$a = producer('Biopont');
|
||||
$b = producer('BIOPONT ');
|
||||
|
||||
$plan = $this->deduplicator->buildPlan([
|
||||
['group' => 1, 'id' => $a->id, 'final_name' => 'Biopont Kft.'],
|
||||
['group' => 1, 'id' => $b->id, 'final_name' => null],
|
||||
]);
|
||||
|
||||
expect($plan['blocking'])->toHaveCount(1)
|
||||
->and($plan['blocking'][0])->toContain('lapon kívüli #' . $outside->id);
|
||||
});
|
||||
|
||||
test('a parancs névütközésnél --force mellett sem hajt végre semmit', function () {
|
||||
$a1 = producer('Danone');
|
||||
$a2 = producer('Danone ');
|
||||
$b1 = producer('Danone Kft');
|
||||
$b2 = producer('DANONE KFT');
|
||||
$moved = productFor($a2, 'X1');
|
||||
|
||||
$path = storage_path('app/private/teszt_nevutkozes.xlsx');
|
||||
writeDecisionSheet($path, [
|
||||
['group' => 1, 'id' => $a1->id, 'final_name' => 'Danone Kft'],
|
||||
['group' => 1, 'id' => $a2->id, 'final_name' => null],
|
||||
['group' => 2, 'id' => $b1->id, 'final_name' => 'Danone Kft'],
|
||||
['group' => 2, 'id' => $b2->id, 'final_name' => null],
|
||||
]);
|
||||
|
||||
$this->artisan('producers:dedupe', ['file' => $path, '--apply' => true, '--force' => true])
|
||||
->assertExitCode(1);
|
||||
|
||||
expect($moved->refresh()->producer_id)->toBe($a2->id)
|
||||
->and(DB::table('producers')->where('status', DbStatusFieldEnum::archive)->count())->toBe(0);
|
||||
|
||||
@unlink($path);
|
||||
});
|
||||
|
||||
@ -2,11 +2,9 @@
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Models\Producer;
|
||||
use App\Models\ProducerAlias;
|
||||
use App\Services\PriceListService;
|
||||
use App\Services\PricelistFileProcessService;
|
||||
use App\Support\NameNormalizer;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
@ -113,103 +111,3 @@ function makeProducer(string $name, string $status = DbStatusFieldEnum::active):
|
||||
expect($lookup['DANONE'] ?? null)->toBe($active->id)
|
||||
->and(in_array($merged->id, $lookup, true))->toBeFalse();
|
||||
});
|
||||
|
||||
function makeAlias(Producer $producer, string $name, string $source = 'backfill'): ProducerAlias
|
||||
{
|
||||
return ProducerAlias::create([
|
||||
'producer_id' => $producer->id,
|
||||
'name' => $name,
|
||||
'normalized_name' => NameNormalizer::normalize($name),
|
||||
'source' => $source,
|
||||
]);
|
||||
}
|
||||
|
||||
test('az árlista feldolgozó az alias-t is feloldja a gyártó lookup térképében', function () {
|
||||
$active = makeProducer('Kőröstej Kft.');
|
||||
makeAlias($active, 'Kőröstej');
|
||||
|
||||
$lookup = callPrivate(app(PricelistFileProcessService::class), 'getProducerLookupMap');
|
||||
|
||||
expect($lookup[NameNormalizer::normalize('Kőröstej')] ?? null)->toBe($active->id);
|
||||
});
|
||||
|
||||
test('az alias sosem írja felül élő gyártó nevét a lookup térképben', function () {
|
||||
$winner = makeProducer('Danone');
|
||||
$other = makeProducer('Bonduelle');
|
||||
// Direkt ütköztetett alias-t szúrunk be a resolver megkerülésével, hogy a
|
||||
// térképépítés defenzív viselkedését - nem csak az író oldali guardot -
|
||||
// ellenőrizzük.
|
||||
makeAlias($other, 'Danone');
|
||||
|
||||
$lookup = callPrivate(app(PricelistFileProcessService::class), 'getProducerLookupMap');
|
||||
|
||||
expect($lookup[NameNormalizer::normalize('Danone')])->toBe($winner->id);
|
||||
});
|
||||
|
||||
test('az archivált gyártóhoz tartozó alias kimarad a feloldásból', function () {
|
||||
$archived = makeProducer('Régi Név', DbStatusFieldEnum::archive);
|
||||
makeAlias($archived, 'Régi Név');
|
||||
|
||||
$lookup = callPrivate(app(PricelistFileProcessService::class), 'getProducerLookupMap');
|
||||
|
||||
expect($lookup[NameNormalizer::normalize('Régi Név')] ?? null)->toBeNull();
|
||||
});
|
||||
|
||||
test('az assertNameAvailable dob, ha a név élő gyártóval ütközik', function () {
|
||||
makeProducer('Danone');
|
||||
|
||||
expect(fn () => (new ProducerAliasResolver)->assertNameAvailable('danone '))
|
||||
->toThrow(RuntimeException::class);
|
||||
});
|
||||
|
||||
test('az aktív gyártóval ütköző assertNameAvailable dedikált exception-t dob, ami az összevonásra utal', function () {
|
||||
// EV3-473, 7. lépés: a felület ezt az exception-típust ismeri fel, hogy a
|
||||
// "Gyártó összevonása" gombra tudjon utalni a hibaüzenetben.
|
||||
makeProducer('Szarvas');
|
||||
|
||||
try {
|
||||
(new ProducerAliasResolver)->assertNameAvailable('Szarvas');
|
||||
$this->fail('Az assertNameAvailable-nek dobnia kellett volna.');
|
||||
} catch (\App\Support\Exceptions\ActiveProducerNameCollisionException $e) {
|
||||
expect($e->collidingProducerId)->toBeInt();
|
||||
}
|
||||
});
|
||||
|
||||
test('az assertNameAvailable dob, ha a név egy másik alias-szal ütközik', function () {
|
||||
$producer = makeProducer('Kőröstej Kft.');
|
||||
$other = makeProducer('Bonduelle');
|
||||
makeAlias($producer, 'Kőröstej');
|
||||
|
||||
expect(fn () => (new ProducerAliasResolver)->assertNameAvailable('Kőröstej', $other->id))
|
||||
->toThrow(RuntimeException::class);
|
||||
});
|
||||
|
||||
test('az assertNameAvailable nem tekinti ütközésnek a gyártó saját nevét', function () {
|
||||
$producer = makeProducer('Danone');
|
||||
|
||||
(new ProducerAliasResolver)->assertNameAvailable('Danone', $producer->id);
|
||||
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
|
||||
test('az assertNameAvailable nem dob valódi új névre', function () {
|
||||
makeProducer('Danone');
|
||||
|
||||
(new ProducerAliasResolver)->assertNameAvailable('Bonduelle');
|
||||
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
|
||||
test('ékezetben eltérő, de a NameNormalizer szerint különböző alias-ok egyszerre tárolhatók', function () {
|
||||
// Valódi eset (EV3-473 backfill, "König-Units Kft" csoport): a MySQL alapértelmezett
|
||||
// utf8mb4_unicode_ci collationja ékezet-érzéketlen, tehát "KONIG..." és "KÖNIG..."
|
||||
// ütközne egy sima unique indexben, holott a NameNormalizer::normalize() szándékosan
|
||||
// NEM old meg ékezeteket. A producer_aliases.normalized_name oszlopnak ezért
|
||||
// utf8mb4_bin collationt kell használnia, különben ez a teszt DB-hibával bukna.
|
||||
$producer = makeProducer('König-Units Kft');
|
||||
|
||||
makeAlias($producer, 'KONIG-UNITS KFT');
|
||||
makeAlias($producer, 'König-Units');
|
||||
|
||||
expect(ProducerAlias::where('producer_id', $producer->id)->count())->toBe(2);
|
||||
});
|
||||
|
||||
@ -1,222 +0,0 @@
|
||||
<?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();
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user