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

83 lines
2.9 KiB
PHP
Executable File

<?php
namespace App\Console\Commands;
use App\Models\Stabile;
use App\Services\Support\GmailTicketImportService;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
class GmailImportStabileTicketsCommand extends Command
{
protected $signature = 'gmail:import-stabile-tickets
{--stabile-id= : ID dello stabile da elaborare}
{--stabile= : Codice stabile alternativo}
{--casella= : Etichetta o email della casella da importare}
{--max=10 : Numero massimo di messaggi da importare per casella}';
protected $description = 'Importa email Gmail/PEC configurate su uno stabile e crea ticket con EML e allegati.';
public function handle(GmailTicketImportService $service): int
{
$stabile = $this->resolveStabile();
if (! $stabile instanceof Stabile) {
$this->error('Stabile non trovato. Usa --stabile-id oppure --stabile.');
return self::FAILURE;
}
$posta = (array) Arr::get($stabile->configurazione_avanzata ?? [], 'posta', []);
$caselle = array_values(array_filter((array) Arr::get($posta, 'caselle', []), function ($mailbox): bool {
return is_array($mailbox)
&& (bool) ($mailbox['enabled'] ?? false)
&& strtolower(trim((string) ($mailbox['tipo'] ?? ''))) === 'gmail';
}));
$filter = trim((string) $this->option('casella'));
if ($filter !== '') {
$caselle = array_values(array_filter($caselle, static function (array $mailbox) use ($filter): bool {
return strcasecmp((string) ($mailbox['label'] ?? ''), $filter) === 0
|| strcasecmp((string) ($mailbox['email'] ?? ''), $filter) === 0;
}));
}
if ($caselle === []) {
$this->warn('Nessuna casella Gmail attiva trovata per questo stabile.');
return self::SUCCESS;
}
$max = max(1, min((int) $this->option('max'), 50));
foreach ($caselle as $mailbox) {
$this->line('Casella: ' . (string) ($mailbox['label'] ?? $mailbox['email'] ?? 'gmail'));
try {
$result = $service->importMailbox($stabile, $mailbox, $max);
$this->info('Importati ' . $result['imported'] . ' messaggi, saltati ' . $result['skipped'] . ', allegati salvati ' . $result['attachments'] . '.');
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
}
return self::SUCCESS;
}
private function resolveStabile(): ?Stabile
{
$stabileId = (int) $this->option('stabile-id');
if ($stabileId > 0) {
return Stabile::query()->find($stabileId);
}
$codice = trim((string) $this->option('stabile'));
if ($codice !== '') {
return Stabile::query()
->where('codice_stabile', $codice)
->orWhere('codice_interno', $codice)
->first();
}
return null;
}
}