netgescon-day0/app/Console/Commands/NetgesconBackfillInvoicePaymentDataCommand.php

71 lines
2.5 KiB
PHP
Executable File

<?php
namespace App\Console\Commands;
use App\Models\FatturaElettronica;
use App\Services\FattureElettroniche\FatturaElettronicaImporter;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
class NetgesconBackfillInvoicePaymentDataCommand extends Command
{
protected $signature = 'netgescon:fe-payment-backfill
{--stabile-id= : Limita a uno stabile}
{--only-missing : Processa solo FE con campi pagamento mancanti}
{--limit=0 : Limite massimo di FE da rileggere (0 = tutte)}';
protected $description = 'Rilegge i PDF allegati delle fatture elettroniche e salva CBILL, codice avviso e SIA nelle colonne strutturate.';
public function handle(FatturaElettronicaImporter $importer): int
{
$stabileId = max(0, (int) ($this->option('stabile-id') ?: 0));
$onlyMissing = (bool) $this->option('only-missing');
$limit = max(0, (int) ($this->option('limit') ?: 0));
$query = FatturaElettronica::query()
->whereNotNull('allegato_pdf_path')
->where('allegato_pdf_path', '<>', '')
->when($stabileId > 0, fn(Builder $builder): Builder => $builder->where('stabile_id', $stabileId))
->when($onlyMissing, function (Builder $builder): Builder {
return $builder->where(function (Builder $nested): void {
$nested->whereNull('pagamento_cbill')
->orWhere('pagamento_cbill', '')
->orWhereNull('pagamento_codice_avviso')
->orWhere('pagamento_codice_avviso', '')
->orWhereNull('pagamento_codice_sia')
->orWhere('pagamento_codice_sia', '');
});
})
->orderBy('id');
if ($limit > 0) {
$query->limit($limit);
}
$stats = [
'processed' => 0,
'updated' => 0,
'missing' => 0,
];
$query->each(function (FatturaElettronica $fattura) use ($importer, &$stats): void {
$stats['processed']++;
if ($importer->refreshPaymentDataFromStoredPdf($fattura)) {
$stats['updated']++;
return;
}
$stats['missing']++;
});
$this->info(sprintf(
'Backfill pagamenti completato. FE processate: %d, aggiornate: %d, senza nuovi dati: %d.',
$stats['processed'],
$stats['updated'],
$stats['missing'],
));
return self::SUCCESS;
}
}