d2d.emegrendeles.hu/app/Console/Commands/ProducersAliasBackfill.php
E98Developer 5347ac5518 ADD EV3-473 producers:alias-backfill - visszamenőleges alias-feltöltés
Két forrásból dolgozik: az archivált gyártók note mezőjéből (láncolást is
követve, ha a célrekord maga is tovább olvadt), illetve a producers:dedupe
--report JSON jelentéseiből, névalapú feloldással - a jelentésekben szereplő
ID-k környezetenként eltérnek. Ütközés esetén kihagyja és jelenti a jelöltet,
kétszeri futtatás nem hoz létre duplikált aliast.
2026-09-18 17:56:50 +02:00

270 lines
9.1 KiB
PHP

<?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']}");
}
}
}