Revisione blocchi 2 e 3: file protetti, ripristino atomico, import sicuri
Blocco 2 - Esiti delle azioni Livewire come avvisi (trait Avvisa) invece di flash che comparivano alla pagina dopo. - PDF, miniature e versioni dei territori non più serviti da nginx su /storage: TerritorioFileController con login, permessi e cache privata. - Ripristino tutto o niente: verifica dell'archivio, una transazione con import, piantine, blocco account e scambio dei file annullabile. - Backup formato 2 con piantine, storico PDF e area KML. - Posto unico preso in un passo (Cache::lock) e rispettato anche da import XML e PDF. - Import PDF da cartella: abbinamento corretto (1-A, 12 B, ambigui), caricamento a lotti, file non PDF ignorati, PDF sostituito nello storico. - L'import XML elimina i file dei territori che non usa più; comando territori:file-orfani per quelli accumulati prima. Blocco 3 - Password attuale richiesta al cambio volontario; AuthenticateSession chiude le sessioni aperte altrove. - Niente nomi dei proclamatori in chiaro nel registro attività. - Export XML senza remember_token; chi riceve l'hash dal file deve cambiare password. - Campagne: ultimo giorno incluso, percentuale sui territori distinti. - Coda: retry_after 960 s, stop_grace_period 16m, Redis volatile-lru, impostazioni rilette a ogni job. - Azzeramento che cancella anche piantine, area KML e anteprime. - Pulsanti profilo e menu che non si nascondevano; icona del sito. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,8 @@ namespace App\Jobs;
|
||||
|
||||
use App\Models\Territorio;
|
||||
use App\Models\User;
|
||||
use App\Services\BackupOperationState;
|
||||
use App\Services\Piantine\PiantinaPdfService;
|
||||
use App\Services\TerritorioPdfImportState;
|
||||
use App\Services\TerritorioThumbnailService;
|
||||
use Illuminate\Bus\Queueable;
|
||||
@@ -35,14 +37,21 @@ class ImportTerritoryPdfFolder implements ShouldQueue
|
||||
) {
|
||||
}
|
||||
|
||||
public function handle(TerritorioPdfImportState $stateService, TerritorioThumbnailService $thumbnailService): void
|
||||
public function handle(TerritorioPdfImportState $stateService, TerritorioThumbnailService $thumbnailService, BackupOperationState $postoUnico, PiantinaPdfService $pdfService): void
|
||||
{
|
||||
$stateService->markRunning($this->importId);
|
||||
$postoUnico->markRunning($this->importId);
|
||||
$stateService->appendLog($this->importId, 'Worker avviato. Inizio elaborazione dei PDF.');
|
||||
|
||||
// Una chiave puo' raccogliere piu' territori ("12B" e "12 B"): non si
|
||||
// tiene l'ultimo arrivato, si tengono tutti, cosi' l'abbinamento li vede
|
||||
// e scarta il file come ambiguo invece di sceglierne uno a caso.
|
||||
$territoriMap = [];
|
||||
foreach (Territorio::withTrashed()->get() as $territorio) {
|
||||
$territoriMap[$this->normalizeTerritoryNumber($territorio->numero)] = $territorio;
|
||||
$chiave = $this->chiaveTerritorio((string) $territorio->numero);
|
||||
if ($chiave !== '') {
|
||||
$territoriMap[$chiave][] = $territorio;
|
||||
}
|
||||
}
|
||||
|
||||
$actor = User::find($this->actorId);
|
||||
@@ -78,9 +87,26 @@ class ImportTerritoryPdfFolder implements ShouldQueue
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalizedNumber = $territoryMatch['normalized_number'];
|
||||
if (($territoryMatch['type'] ?? 'single') === 'unknown-suffix') {
|
||||
$codici = implode(', ', $territoryMatch['codes']);
|
||||
$esistenti = implode(', ', $territoryMatch['matched_numbers']);
|
||||
$stateService->increment($this->importId, 'skipped');
|
||||
$stateService->appendLog($this->importId, '[SKIP] ' . $originalName . ' - il nome indica il territorio ' . $codici . ', che non esiste (esiste ' . $esistenti . '): file non associato, per non sostituire il PDF di un altro territorio.');
|
||||
$stateService->addIssue($this->importId, [
|
||||
'file' => $originalName,
|
||||
'type' => 'unknown-suffix',
|
||||
'message' => 'Il nome indica il territorio ' . $codici . ', che non esiste: non associato a ' . $esistenti . '.',
|
||||
'matched_numbers' => $territoryMatch['matched_numbers'],
|
||||
]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$matchedNumber = $territoryMatch['matched_number'];
|
||||
$territorio = $territoryMatch['territorio'];
|
||||
// Per id, non per numero: due file che nominano lo stesso
|
||||
// territorio scritto in due modi ("12B.pdf", "12 B.pdf") sono
|
||||
// comunque un doppione.
|
||||
$normalizedNumber = $territorio->id;
|
||||
|
||||
if (isset($seenNumbers[$normalizedNumber])) {
|
||||
$stateService->increment($this->importId, 'skipped');
|
||||
@@ -111,24 +137,27 @@ class ImportTerritoryPdfFolder implements ShouldQueue
|
||||
}
|
||||
|
||||
try {
|
||||
if ($territorio->pdf_path) {
|
||||
Storage::disk('public')->delete($territorio->pdf_path);
|
||||
}
|
||||
|
||||
if ($territorio->thumbnail_path) {
|
||||
$thumbnailService->delete($territorio->thumbnail_path);
|
||||
}
|
||||
|
||||
// The territory id is part of the filename because the slug
|
||||
// alone is not unique: "1 A" and "1-A" are distinct
|
||||
// territory numbers that both slug to "territorio-1-a".
|
||||
// Without it the second import overwrites the first's PDF
|
||||
// and both rows point at one file — then removing the PDF
|
||||
// from either territory breaks the other.
|
||||
//
|
||||
// Il nuovo file si scrive per primo, con un nome che non
|
||||
// coincide con quello in vigore; solo dopo il vecchio va
|
||||
// nello storico, come per le piantine. Prima si cancellava
|
||||
// il vecchio e poi si scriveva: con una scrittura fallita il
|
||||
// territorio restava senza PDF, e un import sbagliato non si
|
||||
// poteva annullare.
|
||||
$storedFilename = Str::slug('territorio-' . $territorio->numero)
|
||||
. '-' . $territorio->id . '.pdf';
|
||||
. '-' . $territorio->id . '-' . now()->format('YmdHis') . '.pdf';
|
||||
$publicPath = 'territori-pdf/' . $storedFilename;
|
||||
Storage::disk('public')->put($publicPath, file_get_contents($sourcePath));
|
||||
if (! Storage::disk('public')->put($publicPath, file_get_contents($sourcePath))) {
|
||||
throw new \RuntimeException('impossibile scrivere il file sul disco: il PDF in vigore non è stato toccato.');
|
||||
}
|
||||
|
||||
$pdfService->archiviaCorrente($territorio, 'import');
|
||||
$thumbnailPath = $thumbnailService->generate($publicPath);
|
||||
|
||||
$territorio->update([
|
||||
@@ -166,10 +195,12 @@ class ImportTerritoryPdfFolder implements ShouldQueue
|
||||
|
||||
$stateService->appendLog($this->importId, 'Import completato.');
|
||||
$stateService->markCompleted($this->importId);
|
||||
$postoUnico->markCompleted($this->importId);
|
||||
} catch (\Throwable $exception) {
|
||||
$stateService->increment($this->importId, 'errors');
|
||||
$stateService->appendLog($this->importId, '[ERR] Errore fatale del job: ' . $exception->getMessage());
|
||||
$stateService->markFailed($this->importId);
|
||||
$postoUnico->markFailed($this->importId, $exception->getMessage());
|
||||
|
||||
throw $exception;
|
||||
} finally {
|
||||
@@ -183,6 +214,10 @@ class ImportTerritoryPdfFolder implements ShouldQueue
|
||||
* Without this the import state is stranded in "running" — the UI polls it
|
||||
* until the 24h cache entry expires — and the uploaded temp directory is
|
||||
* never reclaimed, since handle()'s finally never executes.
|
||||
*
|
||||
* Libera anche il posto unico: senza, un import ucciso dal timeout
|
||||
* lascerebbe backup, ripristino e azzeramento bloccati per l'ora intera
|
||||
* del TTL, con un'operazione che non avanza piu'.
|
||||
*/
|
||||
public function failed(?\Throwable $exception): void
|
||||
{
|
||||
@@ -193,79 +228,128 @@ class ImportTerritoryPdfFolder implements ShouldQueue
|
||||
'[ERR] Job terminato senza completare: ' . ($exception?->getMessage() ?? 'timeout')
|
||||
);
|
||||
$stateService->markFailed($this->importId);
|
||||
app(BackupOperationState::class)->markFailed(
|
||||
$this->importId,
|
||||
'Import PDF terminato senza completare: ' . ($exception?->getMessage() ?? 'timeout')
|
||||
);
|
||||
|
||||
Storage::disk('local')->deleteDirectory('bulk-territori-imports/' . $this->importId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Abbina il nome di un file al territorio, oppure spiega perche' non lo fa.
|
||||
*
|
||||
* La regola: nel nome si cercano i "numeri di territorio", cioe' cifre
|
||||
* seguite al massimo da UNA lettera, attaccata o separata da uno spazio, un
|
||||
* trattino, un trattino basso o un punto ("12", "012", "12B", "12 B",
|
||||
* "12-b"). Le forme scritte in modo diverso dello stesso numero sono lo
|
||||
* stesso numero: "12 B", "12B" e "12-B" sono tutte 12B, mai 12. Il numero
|
||||
* deve stare da solo — "T12" o "12AB" non contano — e quelli che non
|
||||
* corrispondono a nessun territorio (un anno, un CAP) vengono ignorati.
|
||||
*
|
||||
* Prima bastava che il numero di un territorio *comparisse* nel nome: "1-A"
|
||||
* conteneva "1", e in assenza di un territorio 1A il PDF finiva sul
|
||||
* territorio 1, sostituendone la mappa senza avvisare. Adesso una lettera
|
||||
* dopo il numero fa parte del numero, e se quel territorio non esiste il
|
||||
* file si scarta: si nomina il territorio 1 nel messaggio, ma non lo si
|
||||
* tocca.
|
||||
*
|
||||
* Il file si scarta anche quando l'abbinamento non e' univoco: due numeri
|
||||
* di territori esistenti nello stesso nome, o due territori che si
|
||||
* scrivono diversi ma sono lo stesso numero ("12B" e "12 B"). Sostituire
|
||||
* la mappa sbagliata e' peggio che non sostituirne nessuna: un file
|
||||
* scartato si ricarica, un PDF sovrascritto non torna.
|
||||
*
|
||||
* I territori con numeri di altra forma (lettere davanti, piu' lettere in
|
||||
* fondo) non si abbinano da nome file: il PDF va caricato dalla loro
|
||||
* scheda.
|
||||
*/
|
||||
protected function resolveTerritoryFromFilename(string $filename, array $territoriMap): ?array
|
||||
{
|
||||
if ($territoriMap === []) {
|
||||
return null;
|
||||
}
|
||||
$trovati = [];
|
||||
$suffissiSconosciuti = [];
|
||||
|
||||
$basename = pathinfo($filename, PATHINFO_FILENAME);
|
||||
$normalizedBasename = mb_strtoupper($basename);
|
||||
$normalizedBasename = preg_replace('/[^A-Z0-9]+/u', ' ', $normalizedBasename);
|
||||
$normalizedBasename = trim(preg_replace('/\s+/', ' ', $normalizedBasename));
|
||||
foreach ($this->numeriNelNomeFile($filename) as $codice) {
|
||||
if (isset($territoriMap[$codice])) {
|
||||
foreach ($territoriMap[$codice] as $territorio) {
|
||||
$trovati[$territorio->id] = $territorio;
|
||||
}
|
||||
|
||||
$territoryKeys = array_keys($territoriMap);
|
||||
usort($territoryKeys, function (string $left, string $right) {
|
||||
$lengthComparison = mb_strlen($right) <=> mb_strlen($left);
|
||||
|
||||
if ($lengthComparison !== 0) {
|
||||
return $lengthComparison;
|
||||
}
|
||||
|
||||
return strnatcasecmp($left, $right);
|
||||
});
|
||||
|
||||
$matches = [];
|
||||
|
||||
foreach ($territoryKeys as $normalizedNumber) {
|
||||
if (! $this->filenameContainsTerritoryNumber($normalizedBasename, $normalizedNumber)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$matches[] = [
|
||||
'normalized_number' => $normalizedNumber,
|
||||
'matched_number' => $territoriMap[$normalizedNumber]->numero,
|
||||
'territorio' => $territoriMap[$normalizedNumber],
|
||||
// "1A" che non esiste, mentre 1 si': e' il caso che prima
|
||||
// sovrascriveva il territorio 1. Lo si annota per spiegarlo.
|
||||
$base = preg_replace('/\p{L}$/u', '', $codice);
|
||||
if ($base !== $codice && isset($territoriMap[$base])) {
|
||||
$suffissiSconosciuti[$codice] = $territoriMap[$base];
|
||||
}
|
||||
}
|
||||
|
||||
$numeri = fn (array $territori) => array_values(array_unique(array_map(fn (Territorio $t) => $t->numero, $territori)));
|
||||
|
||||
if (count($trovati) > 1 || ($trovati !== [] && $suffissiSconosciuti !== [])) {
|
||||
return [
|
||||
'type' => 'ambiguous',
|
||||
'matched_numbers' => $numeri(array_merge(array_values($trovati), ...array_values($suffissiSconosciuti))),
|
||||
];
|
||||
}
|
||||
|
||||
if ($matches === []) {
|
||||
if ($trovati === [] && $suffissiSconosciuti !== []) {
|
||||
return [
|
||||
'type' => 'unknown-suffix',
|
||||
'codes' => array_keys($suffissiSconosciuti),
|
||||
'matched_numbers' => $numeri(array_merge(...array_values($suffissiSconosciuti))),
|
||||
];
|
||||
}
|
||||
|
||||
if ($trovati === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (count($matches) > 1) {
|
||||
return [
|
||||
'type' => 'ambiguous',
|
||||
'matched_numbers' => array_values(array_map(fn(array $match) => $match['matched_number'], $matches)),
|
||||
];
|
||||
}
|
||||
$territorio = reset($trovati);
|
||||
|
||||
return $matches[0];
|
||||
return [
|
||||
'type' => 'single',
|
||||
'normalized_number' => $this->chiaveTerritorio($territorio->numero),
|
||||
'matched_number' => $territorio->numero,
|
||||
'territorio' => $territorio,
|
||||
];
|
||||
}
|
||||
|
||||
protected function filenameContainsTerritoryNumber(string $normalizedBasename, string $normalizedNumber): bool
|
||||
/**
|
||||
* I numeri di territorio presenti nel nome del file, gia' nella forma di
|
||||
* chiaveTerritorio(). Vedi la regola in resolveTerritoryFromFilename().
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
protected function numeriNelNomeFile(string $filename): array
|
||||
{
|
||||
$escapedNumber = preg_quote($normalizedNumber, '/');
|
||||
$nome = mb_strtoupper(pathinfo($filename, PATHINFO_FILENAME));
|
||||
|
||||
if (preg_match('/^\d+$/', $normalizedNumber)) {
|
||||
$escapedNumber = '0*' . preg_quote(ltrim($normalizedNumber, '0') ?: '0', '/');
|
||||
// Il lookahead finale e' quello che separa "12 B" (numero 12B) da
|
||||
// "12 Via Roma" (numero 12): la lettera vale come parte del numero solo
|
||||
// se dopo di lei la parola finisce.
|
||||
preg_match_all('/(?<![\p{L}\p{N}])(\d+)(?:[ _.\-]?(\p{L}))?(?![\p{L}\p{N}])/u', $nome, $trovati, PREG_SET_ORDER);
|
||||
|
||||
$codici = [];
|
||||
foreach ($trovati as $trovato) {
|
||||
$codici[] = (ltrim($trovato[1], '0') ?: '0') . ($trovato[2] ?? '');
|
||||
}
|
||||
|
||||
return (bool) preg_match('/(^| )' . $escapedNumber . '(?= |$)/', $normalizedBasename);
|
||||
return array_values(array_unique($codici));
|
||||
}
|
||||
|
||||
protected function normalizeTerritoryNumber(string $number): string
|
||||
/**
|
||||
* Forma di confronto di un numero di territorio: maiuscolo, senza
|
||||
* separatori, senza zeri iniziali. "12 B", "12-b" e "012B" diventano tutti
|
||||
* "12B"; due territori con la stessa chiave rendono ambiguo ogni file che
|
||||
* la nomina.
|
||||
*/
|
||||
protected function chiaveTerritorio(string $numero): string
|
||||
{
|
||||
$normalized = preg_replace('/\s+/', ' ', trim(mb_strtoupper($number)));
|
||||
$chiave = preg_replace('/[^\p{L}\p{N}]+/u', '', mb_strtoupper($numero));
|
||||
|
||||
if ($normalized !== '' && preg_match('/^\d+$/', $normalized)) {
|
||||
return ltrim($normalized, '0') ?: '0';
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
return preg_replace('/(?<!\d)0+(?=\d)/', '', $chiave);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user