}> */ protected array $periodoRateMap = []; protected static ?bool $supportsWindowFunctions = null; protected static ?string $navigationLabel = 'Movimenti banca'; protected static ?string $title = 'Movimenti banca'; protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-banknotes'; protected static UnitEnum|string|null $navigationGroup = 'Contabilità'; protected static ?int $navigationSort = 11; protected static ?string $slug = 'contabilita/casse-banche/movimenti'; protected string $view = 'filament.pages.contabilita.casse-banche-movimenti'; public static function canAccess(): bool { $user = Auth::user(); if (! $user instanceof User) { return false; } if ($user->hasAnyRole(['super-admin', 'admin'])) { return true; } return $user->can('contabilita.casse-banche'); } public function mount(): void { $today = now(); $this->periodoAnno = (int) $today->year; $this->periodoValore = (int) $today->month; $this->hubTab = $this->normalizeHubTabValue($this->hubTab); $this->contoId = is_numeric(request()->query('conto_id')) ? (int) request()->query('conto_id') : null; $this->contoId = $this->contoId && $this->contoId > 0 ? $this->contoId : null; $this->iban = is_string(request()->query('iban')) ? trim((string) request()->query('iban')) : null; $this->iban = $this->iban !== '' ? $this->iban : null; $this->mountInteractsWithTable(); // Risolvi conto selezionato: preferisci conto_id, altrimenti iban->conto_id. $user = Auth::user(); if ($user instanceof User) { $stabileId = StabileContext::resolveActiveStabileId($user); if ($stabileId) { if ($this->contoId) { $conto = DatiBancari::query() ->where('stabile_id', $stabileId) ->where('id', $this->contoId) ->first(['id', 'iban']); if (! $conto) { $this->contoId = null; } else { $iban = is_string($conto->iban) ? trim((string) $conto->iban) : ''; $this->iban = $iban !== '' ? $iban : null; } } if (! $this->contoId && $this->iban) { $conto = DatiBancari::query() ->where('stabile_id', $stabileId) ->where('iban', $this->iban) ->orderBy('id') ->first(['id']); if ($conto) { $this->contoId = (int) $conto->id; } } } } // Default: primo conto con IBAN (mantiene comportamento "movimenti banca" predefinito). if ($this->contoId === null && $this->iban === null) { $first = $this->getDefaultIban(); $this->iban = $first !== '' ? $first : null; if ($user instanceof User) { $stabileId = StabileContext::resolveActiveStabileId($user); if ($stabileId && $this->iban) { $conto = DatiBancari::query() ->where('stabile_id', $stabileId) ->where('iban', $this->iban) ->orderBy('id') ->first(['id']); if ($conto) { $this->contoId = (int) $conto->id; } } } } if ($this->contoId !== null) { $this->syncSelectedContoFromId($this->contoId); } } public function updatedHubTab(): void { $this->hubTab = $this->normalizeHubTabValue($this->hubTab); } public function updatedContoId(mixed $value): void { $contoId = is_numeric($value) ? (int) $value : null; $this->syncSelectedContoFromId($contoId); $this->resetContoDependentState(); } public function goToHubTab(string $tab): void { $this->hubTab = $this->normalizeHubTabValue($tab); } public function selectContoAndTab(int $contoId, string $tab = 'movimenti'): void { $this->syncSelectedContoFromId($contoId); $this->resetContoDependentState(); $this->hubTab = $this->normalizeHubTabValue($tab); } public function clearMovimentiFocus(): void { $this->movimentiFocusFrom = null; $this->movimentiFocusTo = null; $this->resetTable(); } public function openSaldoPeriodo(int $saldoId): void { $stabileId = $this->getActiveStabileId(); if (! $stabileId || ! DB::getSchemaBuilder()->hasTable('contabilita_saldi_conti')) { return; } $saldo = SaldoConto::query() ->where('stabile_id', $stabileId) ->whereKey($saldoId) ->first(['id', 'conto_id', 'iban', 'data_saldo', 'periodo_da', 'periodo_a']); if (! $saldo) { return; } if (is_numeric($saldo->conto_id)) { $this->syncSelectedContoFromId((int) $saldo->conto_id); } else { $this->contoId = null; $this->iban = $this->normalizeIbanValue($saldo->iban); } $from = $saldo->periodo_da?->toDateString(); $to = $saldo->periodo_a?->toDateString(); if (! $from && $saldo->data_saldo) { $from = $saldo->data_saldo->copy()->startOfMonth()->toDateString(); } if (! $to && $saldo->data_saldo) { $to = $saldo->data_saldo->copy()->endOfMonth()->toDateString(); } $this->movimentiFocusFrom = $from; $this->movimentiFocusTo = $to; $this->applyPeriodoStateFromFocusRange(); $this->hubTab = 'movimenti'; $this->resetTable(); } public function getPeriodoTotaliProperty(): array { $user = Auth::user(); if (! $user instanceof User) { return ['entrate' => 0, 'uscite' => 0, 'saldo' => 0, 'count' => 0, 'label' => '']; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return ['entrate' => 0, 'uscite' => 0, 'saldo' => 0, 'count' => 0, 'label' => '']; } $anno = (int) ($this->periodoAnno ?: now()->year); $val = (int) ($this->periodoValore ?: now()->month); $start = null; $end = null; $label = ''; if ($this->periodoTipo === 'trimestre') { $q = max(1, min(4, $val)); $start = Carbon::create($anno, (($q - 1) * 3) + 1, 1)->startOfDay(); $end = (clone $start)->addMonths(3)->subDay()->endOfDay(); $label = 'Trimestre ' . $q . '/' . $anno; } else { $m = max(1, min(12, $val)); $start = Carbon::create($anno, $m, 1)->startOfDay(); $end = (clone $start)->endOfMonth()->endOfDay(); $label = $start->format('m/Y'); } $query = MovimentoBanca::query() ->where('stabile_id', $stabileId) ->when($this->contoId !== null, fn(Builder $q): Builder => $q->where('conto_id', $this->contoId)) ->when($this->contoId === null && $this->iban !== null, fn(Builder $q): Builder => $q->where('iban', $this->iban)) ->whereDate('data', '>=', $start->toDateString()) ->whereDate('data', '<=', $end->toDateString()); $entrate = (float) $query->sum(DB::raw('CASE WHEN importo > 0 THEN importo ELSE 0 END')); $uscite = (float) $query->sum(DB::raw('CASE WHEN importo < 0 THEN ABS(importo) ELSE 0 END')); $count = (int) $query->count(); return [ 'entrate' => $entrate, 'uscite' => $uscite, 'saldo' => $entrate - $uscite, 'count' => $count, 'label' => $label, ]; } public function getPeriodoOptionsProperty(): array { $months = []; for ($m = 1; $m <= 12; $m++) { $months[$m] = str_pad((string) $m, 2, '0', STR_PAD_LEFT); } return [ 'mese' => $months, 'trimestre' => [1 => 'T1', 2 => 'T2', 3 => 'T3', 4 => 'T4'], ]; } public function getPeriodoRateOptionsProperty(): array { $loaded = $this->loadPeriodoRateOptions(); $options = $loaded['options']; if ($this->periodoRate === null && ! empty($options)) { $this->periodoRate = array_key_first($options); } return $options; } public function getPeriodoRateTotaliProperty(): array { $user = Auth::user(); if (! $user instanceof User) { return ['entrate' => 0, 'uscite' => 0, 'saldo' => 0, 'count' => 0, 'label' => '']; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return ['entrate' => 0, 'uscite' => 0, 'saldo' => 0, 'count' => 0, 'label' => '']; } $loaded = $this->loadPeriodoRateOptions(); $options = $loaded['options']; $map = $loaded['map']; $selected = $this->periodoRate; if (! $selected || ! isset($map[$selected])) { return ['entrate' => 0, 'uscite' => 0, 'saldo' => 0, 'count' => 0, 'label' => '']; } $rawValues = $map[$selected]['raw'] ?? []; if (empty($rawValues)) { return ['entrate' => 0, 'uscite' => 0, 'saldo' => 0, 'count' => 0, 'label' => (string) ($map[$selected]['label'] ?? $selected)]; } $query = MovimentoBanca::query() ->where('stabile_id', $stabileId) ->when($this->contoId !== null, fn(Builder $q): Builder => $q->where('conto_id', $this->contoId)) ->when($this->contoId === null && $this->iban !== null, fn(Builder $q): Builder => $q->where('iban', $this->iban)) ->whereRaw("JSON_UNQUOTE(JSON_EXTRACT(match_data, '$.periodo_rate')) in (" . implode(',', array_fill(0, count($rawValues), '?')) . ")", $rawValues); $entrate = (float) $query->sum(DB::raw('CASE WHEN importo > 0 THEN importo ELSE 0 END')); $uscite = (float) $query->sum(DB::raw('CASE WHEN importo < 0 THEN ABS(importo) ELSE 0 END')); $count = (int) $query->count(); return [ 'entrate' => $entrate, 'uscite' => $uscite, 'saldo' => $entrate - $uscite, 'count' => $count, 'label' => (string) ($map[$selected]['label'] ?? $selected), ]; } /** @return array{options:array, map:array}>} */ protected function loadPeriodoRateOptions(): array { if (! empty($this->periodoRateMap)) { $options = []; foreach ($this->periodoRateMap as $key => $payload) { $options[$key] = $payload['label']; } return ['options' => $options, 'map' => $this->periodoRateMap]; } $user = Auth::user(); if (! $user instanceof User) { return ['options' => [], 'map' => []]; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return ['options' => [], 'map' => []]; } $values = MovimentoBanca::query() ->where('stabile_id', $stabileId) ->when($this->contoId !== null, fn(Builder $q): Builder => $q->where('conto_id', $this->contoId)) ->when($this->contoId === null && $this->iban !== null, fn(Builder $q): Builder => $q->where('iban', $this->iban)) ->whereRaw("JSON_EXTRACT(match_data, '$.periodo_rate') IS NOT NULL") ->selectRaw("DISTINCT JSON_UNQUOTE(JSON_EXTRACT(match_data, '$.periodo_rate')) AS periodo_rate") ->pluck('periodo_rate') ->filter(fn($v) => is_string($v) && trim($v) !== '') ->values() ->all(); $map = []; foreach ($values as $val) { $norm = $this->normalizePeriodoRate($val); if ($norm === null) { continue; } if (! isset($map[$norm])) { $map[$norm] = ['label' => $norm, 'raw' => []]; } $map[$norm]['raw'][] = $val; } ksort($map); $this->periodoRateMap = $map; $options = []; foreach ($map as $key => $payload) { $options[$key] = $payload['label']; } return ['options' => $options, 'map' => $map]; } protected function normalizePeriodoRate(?string $value): ?string { $v = trim((string) $value); if ($v === '') { return null; } $v = preg_replace('/\b(20)?\d{2}\b/', '', $v) ?? $v; $v = preg_replace('/\s{2,}/', ' ', $v) ?? $v; $v = trim($v, " \t\n\r\0\x0B-/"); return $v !== '' ? $v : null; } protected function getHeaderActions(): array { return [ Action::make('hub_conti') ->label('Tab conti') ->icon('heroicon-o-banknotes') ->action(fn() => $this->goToHubTab('conti')), Action::make('hub_saldi') ->label('Tab saldi') ->icon('heroicon-o-scale') ->action(fn() => $this->goToHubTab('saldi')), Action::make('hub_riconciliazione') ->label('Riconciliazione') ->icon('heroicon-o-sparkles') ->action(fn() => $this->goToHubTab('riconciliazione')), Action::make('registra_saldo_estratto') ->label('Registra saldo / estratto') ->icon('heroicon-o-document-duplicate') ->modalWidth('4xl') ->form([ Select::make('conto_id') ->label('Conto / cassa') ->native(false) ->searchable() ->options(function (): array { $opts = []; foreach ($this->getContiImportabili() as $conto) { $contoId = isset($conto['id']) && is_numeric($conto['id']) ? (int) $conto['id'] : 0; if ($contoId <= 0) { continue; } $opts[$contoId] = (string) ($conto['label'] ?? ('Conto #' . $contoId)); } return $opts; }) ->default(fn(): ?int => $this->contoId) ->required(), DatePicker::make('data_saldo') ->label('Data saldo ufficiale') ->required(), TextInput::make('saldo') ->label('Saldo ufficiale') ->numeric() ->required(), DatePicker::make('periodo_da') ->label('Periodo estratto dal'), DatePicker::make('periodo_a') ->label('Periodo estratto al'), Select::make('tipo_estratto') ->label('Tipo riferimento') ->native(false) ->options($this->getTipoEstrattoOptions()) ->default('estratto_conto'), FileUpload::make('documento') ->label('Allega estratto conto') ->directory('tmp/banca') ->disk('local') ->acceptedFileTypes([ 'application/pdf', 'text/plain', 'text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.pdf', '.csv', '.txt', '.qif', '.xlsx', ]), Textarea::make('note') ->label('Note') ->rows(3) ->maxLength(255), ]) ->action(function (array $data): void { $user = Auth::user(); if (! $user instanceof User) { Notification::make()->title('Utente non valido')->danger()->send(); return; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { Notification::make()->title('Seleziona uno stabile')->danger()->send(); return; } $contoId = isset($data['conto_id']) && is_numeric($data['conto_id']) ? (int) $data['conto_id'] : 0; if ($contoId <= 0) { Notification::make()->title('Seleziona un conto valido')->danger()->send(); return; } $conto = DatiBancari::query() ->where('stabile_id', $stabileId) ->where('id', $contoId) ->first(['id', 'denominazione_banca', 'iban', 'numero_conto', 'legacy_cod_cassa']); if (! $conto) { Notification::make()->title('Conto non valido per lo stabile attivo')->danger()->send(); return; } $documento = $this->storeSaldoDocumento($stabileId, $conto, $data['documento'] ?? null, $user, $data); SaldoConto::query()->create([ 'stabile_id' => $stabileId, 'conto_id' => (int) $conto->id, 'iban' => $this->normalizeIbanValue($conto->iban), 'data_saldo' => $data['data_saldo'] ?? null, 'periodo_da' => $data['periodo_da'] ?? null, 'periodo_a' => $data['periodo_a'] ?? null, 'saldo' => isset($data['saldo']) ? (float) $data['saldo'] : 0.0, 'tipo_estratto' => $this->normalizeTipoEstrattoValue($data['tipo_estratto'] ?? null), 'note' => isset($data['note']) && is_string($data['note']) ? trim((string) $data['note']) : null, 'documento_stabile_id' => $documento?->id, 'created_by' => (int) $user->id, 'updated_by' => (int) $user->id, ]); $this->contoId = (int) $conto->id; $this->iban = $this->normalizeIbanValue($conto->iban); Notification::make() ->title('Saldo ufficiale registrato') ->success() ->send(); }), Action::make('importa_estratto_unificato') ->label('Importa estratto') ->icon('heroicon-o-arrow-up-tray') ->modalWidth('7xl') ->form([ Select::make('conto_id') ->label('Conto / cassa') ->native(false) ->searchable() ->options(function (): array { $opts = []; foreach ($this->getContiImportabili() as $c) { $contoId = isset($c['id']) && is_numeric($c['id']) ? (int) $c['id'] : null; if (! $contoId) { continue; } $opts[$contoId] = (string) ($c['label'] ?? ('Conto #' . $contoId)); } return $opts; }) ->default(fn(): ?int => $this->contoId) ->required() ->helperText('Obbligatorio: l\'import viene sempre legato al conto/cassa selezionato, usando il codice legacy quando presente.'), Select::make('formato') ->label('Formato file') ->native(false) ->options(function (): array { return [ 'auto_csv' => 'CSV banca (rilevamento automatico)', 'mps_qif' => 'MPS QIF', 'unicredit_wri' => 'Unicredit WRI', 'intesa_csv' => 'Intesa CSV', 'xlsx' => 'Excel XLSX', ]; }) ->default(fn(): string => $this->resolvePreferredImportFormatForConto($this->contoId)) ->required() ->helperText('Un solo flusso di import: scegli il formato corretto per il conto selezionato. Per Monte dei Paschi usa QIF.'), Select::make('gestione_id') ->label('Gestione (opzionale)') ->native(false) ->searchable() ->options(function (): array { $user = Auth::user(); if (! $user instanceof User) { return []; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return []; } if (! DB::getSchemaBuilder()->hasTable('gestioni_contabili')) { return []; } return GestioneContabile::query() ->where('stabile_id', $stabileId) ->orderByDesc('anno_gestione') ->orderBy('tipo_gestione') ->orderByDesc('id') ->get(['id', 'denominazione', 'protocollo_prefix', 'stato']) ->mapWithKeys(fn(GestioneContabile $g) => [ (string) $g->id => trim(($g->protocollo_prefix ? $g->protocollo_prefix . ' · ' : '') . $g->denominazione) . ($g->stato !== 'aperta' ? (' (' . $g->stato . ')') : ''), ]) ->all(); }) ->default(function (): ?string { $user = Auth::user(); if (! $user instanceof User) { return null; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return null; } return $this->resolveDefaultGestioneId($stabileId); }), FileUpload::make('file') ->label('File estratto') ->directory('tmp/banca') ->disk('local') ->acceptedFileTypes([ 'text/plain', 'text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.csv', '.txt', '.wri', '.qif', '.xlsx', ]) ->required(), Toggle::make('replace') ->label('Sostituisci import nel periodo') ->helperText('Elimina SOLO i movimenti importati e NON riconciliati per lo stesso conto e per l\'intervallo date del file, poi reimporta.') ->default(false), ]) ->action(function (array $data): void { $user = Auth::user(); if (! $user instanceof User) { Notification::make()->title('Utente non valido')->danger()->send(); return; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { Notification::make()->title('Seleziona uno stabile')->danger()->send(); return; } $contoId = isset($data['conto_id']) && is_numeric($data['conto_id']) ? (int) $data['conto_id'] : null; if (! $contoId) { Notification::make()->title('Seleziona un conto o una cassa')->danger()->send(); return; } $conto = DatiBancari::query() ->where('stabile_id', $stabileId) ->where('id', $contoId) ->first(['id', 'iban']); if (! $conto) { Notification::make()->title('Conto non valido per lo stabile attivo')->danger()->send(); return; } $path = (string) ($data['file'] ?? ''); if ($path === '') { Notification::make()->title('Seleziona un file')->danger()->send(); return; } $format = isset($data['formato']) && is_string($data['formato']) ? trim((string) $data['formato']) : ''; if ($format === '') { Notification::make()->title('Seleziona il formato del file')->danger()->send(); return; } $gestioneId = isset($data['gestione_id']) && is_numeric($data['gestione_id']) ? (int) $data['gestione_id'] : null; $replace = isset($data['replace']) ? (bool) $data['replace'] : false; try { $importer = $this->makeMovimentiImporter(); $filename = basename($path); $res = match ($format) { 'xlsx' => $importer->importExcelXlsxForConto( Storage::disk('local')->path($path), $stabileId, $contoId, $filename, $gestioneId, $replace, ), 'unicredit_wri' => $importer->importUnicreditWriForConto( Storage::disk('local')->get($path), $stabileId, $contoId, $filename, $gestioneId, $replace, ), 'intesa_csv' => $importer->importIntesaCsvForConto( Storage::disk('local')->get($path), $stabileId, $contoId, $filename, $gestioneId, $replace, ), 'mps_qif' => $importer->importMpsQifForConto( Storage::disk('local')->get($path), $stabileId, $contoId, $filename, $gestioneId, $replace, ), default => $importer->importCsvAutoForConto( Storage::disk('local')->get($path), $stabileId, $contoId, $filename, $gestioneId, $replace, ), }; $this->contoId = $contoId; $iban = is_string($conto->iban) ? trim((string) $conto->iban) : ''; $this->iban = $iban !== '' ? $iban : null; Notification::make() ->title('Import completato') ->body('Formato: ' . $format . ' · Importati: ' . $res['imported'] . ' · Duplicati: ' . $res['duplicates']) ->success() ->send(); } catch (\Throwable $e) { Notification::make()->title('Errore import')->body($e->getMessage())->danger()->send(); } finally { try { Storage::disk('local')->delete($path); } catch (\Throwable) { // ignore } } }), ]; } protected function getTableQuery(): Builder { $user = Auth::user(); if (! $user instanceof User) { return MovimentoBanca::query()->whereRaw('1 = 0'); } $activeStabileId = StabileContext::resolveActiveStabileId($user); if (! $activeStabileId) { return MovimentoBanca::query()->whereRaw('1 = 0'); } $query = MovimentoBanca::query() ->with('gestioneContabile') ->where('stabile_id', $activeStabileId) ->when($this->contoId !== null, fn(Builder $q): Builder => $q->where('conto_id', $this->contoId)) ->when($this->contoId === null && $this->iban !== null, fn(Builder $q): Builder => $q->where('iban', $this->iban)) ->when($this->movimentiFocusFrom, fn(Builder $q): Builder => $q->whereDate('data', '>=', $this->movimentiFocusFrom)) ->when($this->movimentiFocusTo, fn(Builder $q): Builder => $q->whereDate('data', '<=', $this->movimentiFocusTo)) ->orderBy('data') ->orderBy('id'); if ($this->dbSupportsWindowFunctions()) { $query->select('contabilita_movimenti_banca.*') ->selectRaw( "SUM(importo) OVER (PARTITION BY stabile_id, COALESCE(iban, '') ORDER BY data, id) AS saldo_progressivo" ); } return $query; } public function table(Table $table): Table { return $table ->striped() ->filters([ Filter::make('ricerca_descrizione') ->label('Ricerca') ->form([ TextInput::make('q') ->label('Descrizione') ->placeholder('Es. Basta Monica') ->autocomplete(false), ]) ->query(function (Builder $query, array $data): Builder { $q = trim((string) ($data['q'] ?? '')); if ($q === '') { return $query; } $qLike = '%' . mb_strtolower($q) . '%'; return $query->where(function (Builder $sub) use ($qLike): Builder { $sub->whereRaw('LOWER(descrizione) LIKE ?', [$qLike]) ->orWhereRaw('LOWER(descrizione_estesa) LIKE ?', [$qLike]) ->orWhereRaw('LOWER(note) LIKE ?', [$qLike]); if (Schema::hasColumn('contabilita_movimenti_banca', 'mittente')) { $sub->orWhereRaw('LOWER(mittente) LIKE ?', [$qLike]); } if (Schema::hasColumn('contabilita_movimenti_banca', 'intestatario')) { $sub->orWhereRaw('LOWER(intestatario) LIKE ?', [$qLike]); } if (Schema::hasColumn('contabilita_movimenti_banca', 'ordinante')) { $sub->orWhereRaw('LOWER(ordinante) LIKE ?', [$qLike]); } return $sub; }); }), Filter::make('periodo') ->label('Periodo') ->form([ DatePicker::make('from')->label('Dal'), DatePicker::make('to')->label('Al'), ]) ->query(function (Builder $query, array $data): Builder { $from = $data['from'] ?? null; $to = $data['to'] ?? null; return $query ->when($from, fn(Builder $q) => $q->whereDate('data', '>=', $from)) ->when($to, fn(Builder $q) => $q->whereDate('data', '<=', $to)); }), Filter::make('causale_bancaria') ->label('Causale') ->form([ Select::make('causale') ->label('Causale') ->native(false) ->searchable() ->options(function (): array { if (! DB::getSchemaBuilder()->hasTable('contabilita_causali_bancarie')) { return []; } return CausaleBancaria::query() ->where('attivo', true) ->orderBy('banca') ->orderBy('codice') ->get(['banca', 'codice', 'descrizione']) ->mapWithKeys(fn(CausaleBancaria $c) => [ (string) $c->codice => (string) $c->banca . ' · ' . (string) $c->codice . ' · ' . (string) $c->descrizione, ]) ->all(); }), ]) ->query(function (Builder $query, array $data): Builder { $code = $data['causale'] ?? null; $code = is_string($code) ? trim($code) : ''; if ($code === '') { return $query; } return $query->where('causale', $code); }), Filter::make('gestioni') ->label('Gestioni') ->form([ Select::make('gestione_ids') ->label('Gestione') ->multiple() ->options(function (): array { $user = Auth::user(); if (! $user instanceof User) { return []; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return []; } if (! DB::getSchemaBuilder()->hasTable('gestioni_contabili')) { return []; } return GestioneContabile::query() ->where('stabile_id', $stabileId) ->orderByDesc('anno_gestione') ->orderBy('tipo_gestione') ->orderByDesc('id') ->get(['id', 'denominazione', 'protocollo_prefix', 'stato']) ->mapWithKeys(fn(GestioneContabile $g) => [ (string) $g->id => trim(($g->protocollo_prefix ? $g->protocollo_prefix . ' · ' : '') . $g->denominazione) . ($g->stato !== 'aperta' ? (' (' . $g->stato . ')') : ''), ]) ->all(); }) ->searchable(), ]) ->query(function (Builder $query, array $data): Builder { $ids = $data['gestione_ids'] ?? null; if (! is_array($ids) || $ids === []) { return $query; } $ids = array_values(array_filter(array_map('intval', $ids), fn(int $v) => $v > 0)); if ($ids === []) { return $query; } return $query->whereIn('gestione_id', $ids); }), ]) ->columns([ TextColumn::make('codice_descrizione') ->label('Codice') ->state(function (MovimentoBanca $record): string { $descr = (string) ($record->descrizione ?? ''); $raw = strtoupper($descr); if (str_contains($raw, 'ACCREDITO_BEU_CON_CONTABILE')) { return 'ACCBEUCONCON'; } if (str_contains($raw, 'COMBONMYB')) { return 'COMBONMYB'; } $raw = preg_replace('/[^A-Z0-9]+/', ' ', $raw) ?? $raw; $parts = array_filter(explode(' ', $raw), fn($v) => $v !== ''); if (! empty($parts)) { $code = ''; foreach ($parts as $p) { $chunk = substr($p, 0, 3); $code .= $chunk; if (strlen($code) >= 12) { break; } } $code = substr($code, 0, 12); if ($code !== '') { return $code; } } $raw = preg_replace('/[^A-Z0-9]+/', '_', $raw) ?? $raw; $raw = trim($raw, '_'); $raw = preg_replace('/_+/', '_', $raw) ?? $raw; return mb_substr($raw, 0, 32); }) ->toggleable(isToggledHiddenByDefault: true), TextColumn::make('disp') ->label('Disp') ->state(function (MovimentoBanca $record): string { $match = is_array($record->match_data ?? null) ? $record->match_data : []; $disp = $match['cod_disp'] ?? null; return is_string($disp) ? trim($disp) : ''; }) ->toggleable(), TextColumn::make('cash') ->label('Cash') ->state(function (MovimentoBanca $record): string { $match = is_array($record->match_data ?? null) ? $record->match_data : []; $cash = $match['cash'] ?? null; return is_string($cash) ? trim($cash) : ''; }) ->toggleable(), TextColumn::make('mittente') ->label('Mittente') ->state(function (MovimentoBanca $record): string { $match = is_array($record->match_data ?? null) ? $record->match_data : []; $mitt = $match['mittente'] ?? null; return is_string($mitt) ? trim($mitt) : ''; }) ->wrap() ->toggleable(), BadgeColumn::make('commissioni') ->label('Comm.') ->getStateUsing(function (MovimentoBanca $record): string { $raw = strtoupper((string) ($record->descrizione ?? '')); return str_contains($raw, 'COMBONMYB') ? 'si' : 'no'; }) ->colors([ 'success' => 'si', 'gray' => 'no', ]) ->formatStateUsing(fn(string $state): string => $state === 'si' ? 'SI' : '—') ->toggleable(isToggledHiddenByDefault: true), TextColumn::make('disp') ->label('Disp') ->state(function (MovimentoBanca $record): string { $match = is_array($record->match_data ?? null) ? $record->match_data : []; $disp = $match['cod_disp'] ?? null; return is_string($disp) ? trim($disp) : ''; }) ->toggleable(), BadgeColumn::make('da_confermare') ->label('Conferma') ->getStateUsing(fn(MovimentoBanca $record): string => ! empty($record->da_confermare) ? 'da_confermare' : 'ok') ->colors([ 'warning' => 'da_confermare', 'success' => 'ok', ]) ->formatStateUsing(fn(string $state): string => $state === 'da_confermare' ? 'DA CONF.' : 'OK') ->toggleable(isToggledHiddenByDefault: true), BadgeColumn::make('stato_quadratura') ->label('Stato') ->getStateUsing(fn(MovimentoBanca $record): string => $this->resolveStatoQuadratura($record)) ->colors([ 'gray' => 'non_collegato', 'warning' => 'collegato_non_quadrato', 'success' => 'quadrato', ]) ->formatStateUsing(function (string $state): string { return match ($state) { 'quadrato' => 'OK', 'collegato_non_quadrato' => 'ATT', default => 'NO', }; }) ->sortable(false), TextColumn::make('voci_collegate') ->label('Voce spesa') ->state(function (MovimentoBanca $record): string { if (! $record->registrazione_id || ! Schema::hasColumn('contabilita_movimenti', 'voce_spesa_id')) { return '—'; } static $cache = []; $regId = (int) $record->registrazione_id; if (array_key_exists($regId, $cache)) { return $cache[$regId]; } $rows = DB::table('contabilita_movimenti as m') ->leftJoin('voci_spesa as v', 'v.id', '=', 'm.voce_spesa_id') ->where('m.registrazione_id', $regId) ->whereNotNull('m.voce_spesa_id') ->select('v.codice', 'v.descrizione') ->distinct() ->limit(5) ->get(); if ($rows->isEmpty()) { return $cache[$regId] = '—'; } $labels = []; foreach ($rows as $row) { $code = trim((string) ($row->codice ?? '')); $desc = trim((string) ($row->descrizione ?? '')); $labels[] = $code !== '' ? ($code . ($desc !== '' ? ' · ' . $desc : '')) : ($desc !== '' ? $desc : 'Voce'); } return $cache[$regId] = implode(' | ', array_values(array_unique($labels))); }) ->wrap() ->toggleable(), TextColumn::make('data') ->label('Data') ->date('d/m/Y') ->sortable(), TextColumn::make('valuta') ->label('Valuta') ->date('d/m/Y') ->toggleable(isToggledHiddenByDefault: true), TextColumn::make('descrizione') ->label('Descrizione') ->state(fn(MovimentoBanca $record): string => (string) ($record->descrizione_estesa_pulita ?? $record->descrizione_estesa ?? $record->descrizione ?? '')) ->wrap() ->searchable(), TextColumn::make('gestioneContabile.denominazione') ->label('Gestione') ->toggleable(isToggledHiddenByDefault: true), TextColumn::make('entrate') ->label('Entrate') ->alignEnd() ->state(fn(MovimentoBanca $record): float => max(0, (float) $record->importo)) ->formatStateUsing(fn($state) => $state > 0 ? ('€ ' . number_format((float) $state, 2, ',', '.')) : ''), TextColumn::make('uscite') ->label('Uscite') ->alignEnd() ->state(fn(MovimentoBanca $record): float => max(0, abs((float) $record->importo) * ((float) $record->importo < 0 ? 1 : 0))) ->formatStateUsing(fn($state) => $state > 0 ? ('€ ' . number_format((float) $state, 2, ',', '.')) : ''), TextColumn::make('saldo_progressivo') ->label('Saldo') ->alignEnd() ->getStateUsing(fn(MovimentoBanca $record): ?float => $this->resolveSaldoConSaldi($record)) ->formatStateUsing(fn($state) => $state !== null ? ('€ ' . number_format((float) $state, 2, ',', '.')) : ''), TextColumn::make('importo') ->label('Importo (raw)') ->alignEnd() ->toggleable(isToggledHiddenByDefault: true) ->formatStateUsing(fn($state) => '€ ' . number_format((float) $state, 2, ',', '.')), TextColumn::make('causale') ->label('Caus.') ->toggleable(), TextColumn::make('iban') ->label('IBAN') ->toggleable(isToggledHiddenByDefault: true), ]) ->actions([ Action::make('dettaglio_movimento') ->label('Dettaglio') ->icon('heroicon-o-eye') ->modalWidth('7xl') ->action(function (MovimentoBanca $record): void { $this->detailMovementId = $record->id; }) ->modalHeading(fn(): string => 'Dettaglio movimento') ->modalContent(function () { $record = $this->getDetailMovement(); return view('filament.pages.contabilita.partials.movimento-banca-dettaglio', [ 'record' => $record, 'prevId' => $this->getAdjacentMovementId('prev'), 'nextId' => $this->getAdjacentMovementId('next'), ]); }), Action::make('conferma_movimento') ->label('Conferma') ->icon('heroicon-o-check-circle') ->visible(fn(MovimentoBanca $record): bool => (bool) ($record->da_confermare ?? false)) ->action(function (MovimentoBanca $record): void { if (! Schema::hasColumn('contabilita_movimenti_banca', 'da_confermare')) { return; } $record->da_confermare = false; $record->save(); Notification::make()->title('Movimento confermato')->success()->send(); $this->resetTable(); }), Action::make('genera_prima_nota') ->label('Genera prima nota') ->icon('heroicon-o-book-open') ->visible(function (MovimentoBanca $record): bool { if (! Schema::hasColumn('contabilita_movimenti_banca', 'registrazione_id')) { return false; } return empty($record->registrazione_id); }) ->form([ Select::make('gestione_id') ->label('Gestione') ->options(function (): array { if (! DB::getSchemaBuilder()->hasTable('gestioni_contabili')) { return []; } $user = Auth::user(); if (! $user instanceof User) { return []; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return []; } return GestioneContabile::query() ->where('stabile_id', $stabileId) ->orderByDesc('anno_gestione') ->orderBy('tipo_gestione') ->orderBy('numero_straordinaria') ->get(['id', 'denominazione', 'tipo_gestione', 'anno_gestione', 'numero_straordinaria']) ->mapWithKeys(fn(GestioneContabile $g) => [ (string) $g->id => $g->denominazione . ' (' . $g->tipo_gestione . ' ' . $g->anno_gestione . ($g->numero_straordinaria ? ' #' . $g->numero_straordinaria : '') . ')', ]) ->all(); }) ->searchable() ->visible(fn(MovimentoBanca $record) => empty($record->gestione_id)) ->required(fn(MovimentoBanca $record) => empty($record->gestione_id)), ]) ->action(function (MovimentoBanca $record, array $data): void { $user = Auth::user(); if (! $user instanceof User) { Notification::make()->title('Utente non valido')->danger()->send(); return; } if (empty($record->gestione_id) && isset($data['gestione_id']) && is_numeric($data['gestione_id'])) { $record->gestione_id = (int) $data['gestione_id']; $record->save(); } try { $service = app(MovimentoBancaPrimaNotaService::class); $service->generaRegistrazioneDaMovimento($user, $record); Notification::make()->title('Prima nota generata')->success()->send(); $this->resetTable(); } catch (\Throwable $e) { Notification::make()->title('Errore')->body($e->getMessage())->danger()->send(); } }), Action::make('paga_fornitore') ->label('Paga fornitore') ->icon('heroicon-o-banknotes') ->visible(function (MovimentoBanca $record): bool { if (! Schema::hasColumn('contabilita_movimenti_banca', 'registrazione_id')) { return false; } if (! Schema::hasTable('contabilita_registrazioni') || ! Schema::hasTable('contabilita_movimenti')) { return false; } $importo = (float) ($record->importo ?? 0); if ($importo >= 0) { return false; } return empty($record->registrazione_id); }) ->form([ Select::make('gestione_id') ->label('Gestione') ->options(function (): array { if (! DB::getSchemaBuilder()->hasTable('gestioni_contabili')) { return []; } $user = Auth::user(); if (! $user instanceof User) { return []; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return []; } return GestioneContabile::query() ->where('stabile_id', $stabileId) ->orderByDesc('anno_gestione') ->orderBy('tipo_gestione') ->orderBy('numero_straordinaria') ->get(['id', 'denominazione', 'tipo_gestione', 'anno_gestione', 'numero_straordinaria']) ->mapWithKeys(fn(GestioneContabile $g) => [ (string) $g->id => $g->denominazione . ' (' . $g->tipo_gestione . ' ' . $g->anno_gestione . ($g->numero_straordinaria ? ' #' . $g->numero_straordinaria : '') . ')', ]) ->all(); }) ->searchable() ->visible(fn(MovimentoBanca $record) => empty($record->gestione_id)) ->required(fn(MovimentoBanca $record) => empty($record->gestione_id)), Select::make('fornitore_id') ->label('Fornitore') ->options(function (): array { $q = Fornitore::query(); if (Schema::hasColumn('fornitori', 'ragione_sociale')) { $q->orderBy('ragione_sociale'); } elseif (Schema::hasColumn('fornitori', 'cognome')) { $q->orderBy('cognome'); } return $q ->limit(500) ->get(['id', 'ragione_sociale', 'nome', 'cognome']) ->mapWithKeys(function (Fornitore $f): array { $label = is_string($f->ragione_sociale ?? null) && trim((string) $f->ragione_sociale) !== '' ? trim((string) $f->ragione_sociale) : trim(((string) ($f->cognome ?? '')) . ' ' . ((string) ($f->nome ?? ''))); $label = $label !== '' ? $label : ('Fornitore #' . (string) $f->id); return [(string) $f->id => $label]; }) ->all(); }) ->searchable() ->required(), Select::make('conto_finanziario_id') ->label('Conto finanziario (Banca/Cassa)') ->options(function (): array { $base = PianoConti::query(); if (Schema::hasColumn('contabilita_piano_conti', 'tipo')) { $base->where('tipo', 'Attività'); } $q = (clone $base)->where(function ($w) { $w->where('descrizione', 'like', '%Banca%') ->orWhere('descrizione', 'like', '%banca%') ->orWhere('descrizione', 'like', '%Cassa%') ->orWhere('descrizione', 'like', '%cassa%'); }); $rows = $q->orderBy('codice')->limit(500)->get(['id', 'codice', 'descrizione']); if ($rows->count() === 0) { $rows = $base->orderBy('codice')->limit(500)->get(['id', 'codice', 'descrizione']); } return $rows ->mapWithKeys(fn(PianoConti $c) => [(string) $c->id => $c->codice . ' - ' . $c->descrizione]) ->all(); }) ->searchable() ->required(), ]) ->action(function (MovimentoBanca $record, array $data): void { $user = Auth::user(); if (! $user instanceof User) { Notification::make()->title('Utente non valido')->danger()->send(); return; } $gestioneId = (empty($record->gestione_id) && isset($data['gestione_id']) && is_numeric($data['gestione_id'])) ? (int) $data['gestione_id'] : (int) ($record->gestione_id ?? 0); $fornitoreId = isset($data['fornitore_id']) && is_numeric($data['fornitore_id']) ? (int) $data['fornitore_id'] : 0; $contoFinId = isset($data['conto_finanziario_id']) && is_numeric($data['conto_finanziario_id']) ? (int) $data['conto_finanziario_id'] : 0; try { $service = app(PagamentoFornitorePrimaNotaService::class); $service->generaPagamentoDaMovimento($user, $record, $fornitoreId, [ 'gestione_id' => $gestioneId, 'conto_finanziario_id' => $contoFinId, ]); Notification::make()->title('Pagamento contabilizzato')->success()->send(); $this->resetTable(); } catch (\Throwable $e) { Notification::make()->title('Errore')->body($e->getMessage())->danger()->send(); } }), ]); } public function getDetailMovement(): ?MovimentoBanca { if (! $this->detailMovementId) { return null; } return MovimentoBanca::query()->where('id', $this->detailMovementId)->first(); } public function setDetailMovement(int $id): void { $this->detailMovementId = $id; } private function getAdjacentMovementId(string $dir): ?int { if (! $this->detailMovementId) { return null; } $current = MovimentoBanca::query()->where('id', $this->detailMovementId)->first(['id', 'data']); if (! $current) { return null; } $query = MovimentoBanca::query() ->when($this->contoId !== null, fn(Builder $q): Builder => $q->where('conto_id', $this->contoId)) ->when($this->contoId === null && $this->iban !== null, fn(Builder $q): Builder => $q->where('iban', $this->iban)); if ($dir === 'prev') { $query->where(function (Builder $q) use ($current): void { $q->where('data', '<', $current->data) ->orWhere(function (Builder $q2) use ($current): void { $q2->where('data', $current->data)->where('id', '<', $current->id); }); })->orderByDesc('data')->orderByDesc('id'); } else { $query->where(function (Builder $q) use ($current): void { $q->where('data', '>', $current->data) ->orWhere(function (Builder $q2) use ($current): void { $q2->where('data', $current->data)->where('id', '>', $current->id); }); })->orderBy('data')->orderBy('id'); } return $query->value('id'); } /** @return array */ protected function getActiveStabileIbans(): array { $user = Auth::user(); if (! $user instanceof User) { return []; } $stabile = StabileContext::getActiveStabile($user); if (! $stabile) { return []; } $ibans = []; foreach ( [ $stabile->iban_principale ?? null, $stabile->iban_secondario ?? null, $stabile->iban_condominio ?? null, ] as $iban ) { $iban = is_string($iban) ? trim($iban) : ''; if ($iban !== '') { $ibans[$iban] = $iban; } } return $ibans; } protected function resolveSaldoProgressivoConSaldoIniziale(MovimentoBanca $record): ?float { $base = $this->resolveSaldoProgressivo($record); if ($base === null) { return null; } $statePeriodo = $this->getTableFilterState('periodo'); $from = is_array($statePeriodo) ? ($statePeriodo['from'] ?? null) : null; if (! $from) { return $base; } $iban = is_string($this->iban) ? trim($this->iban) : ''; if ($iban === '') { return $base; } $saldoIniziale = $this->resolveSaldoIniziale((int) $record->stabile_id, $iban, (string) $from); if ($saldoIniziale === null) { return $base; } return $saldoIniziale + $base; } protected function resolveSaldoConSaldi(MovimentoBanca $record): ?float { $baseProgressivo = $this->resolveSaldoProgressivo($record); if ($baseProgressivo === null) { return null; } $stabileId = (int) $record->stabile_id; $contoId = isset($record->conto_id) && is_numeric($record->conto_id) ? (int) $record->conto_id : null; $iban = $this->normalizeIbanValue($record->iban); $saldoIniziale = $this->resolveSaldoInizialeDaDatiBancari($stabileId, $contoId, $iban); // Offset da eventuali saldi intermedi: saldo atteso alla data_saldo meno saldo calcolato fino a quella data. $offset = $this->resolveSaldoOffsetDaSaldi($stabileId, $contoId, $iban, $record->data); return $saldoIniziale + (float) $baseProgressivo + $offset; } protected function resolveSaldoInizialeDaDatiBancari(int $stabileId, ?int $contoId, ?string $iban): float { static $cache = []; $key = $stabileId . '|' . ($contoId ?: 0) . '|' . ($iban ?: '-'); if (array_key_exists($key, $cache)) { return (float) $cache[$key]; } $q = DatiBancari::query()->where('stabile_id', $stabileId); if ($contoId) { $q->where('id', $contoId); } elseif ($iban) { $q->where('iban', $iban); } else { $cache[$key] = 0.0; return 0.0; } $row = $q->first(['saldo_iniziale']); $cache[$key] = $row && is_numeric($row->saldo_iniziale) ? (float) $row->saldo_iniziale : 0.0; return (float) $cache[$key]; } protected function resolveSaldoOffsetDaSaldi(int $stabileId, ?int $contoId, ?string $iban, Carbon $recordDate): float { if (! DB::getSchemaBuilder()->hasTable('contabilita_saldi_conti')) { return 0.0; } if (! $contoId && ! $iban) { return 0.0; } static $saldiCache = []; $cacheKey = $stabileId . '|' . ($contoId ?: 0) . '|' . ($iban ?: '-'); if (! array_key_exists($cacheKey, $saldiCache)) { $q = SaldoConto::query()->where('stabile_id', $stabileId); if ($contoId) { $q->where('conto_id', $contoId); } elseif ($iban) { $q->where('iban', $iban); } $saldiCache[$cacheKey] = $q ->orderBy('data_saldo') ->orderBy('id') ->get(['id', 'data_saldo', 'saldo']) ->all(); } $saldi = $saldiCache[$cacheKey]; if (! is_array($saldi) || $saldi === []) { return 0.0; } $match = null; foreach ($saldi as $s) { if (! $s || ! isset($s->data_saldo)) { continue; } if ($s->data_saldo->toDateString() <= $recordDate->toDateString()) { $match = $s; } else { break; } } if (! $match) { return 0.0; } static $sumToDateCache = []; $sumKey = $cacheKey . '|' . $match->data_saldo->toDateString() . '|' . (int) $match->id; if (! array_key_exists($sumKey, $sumToDateCache)) { $q = MovimentoBanca::query()->where('stabile_id', $stabileId); if ($contoId) { $q->where('conto_id', $contoId); } elseif ($iban) { $q->where('iban', $iban); } $q->whereDate('data', '<=', $match->data_saldo->toDateString()); $sumToDateCache[$sumKey] = (float) ($q->sum('importo') ?? 0.0); } $saldoIniziale = $this->resolveSaldoInizialeDaDatiBancari($stabileId, $contoId, $iban); $saldoAttesoAllaDataSaldo = (float) $match->saldo; $saldoCalcolatoAllaDataSaldo = $saldoIniziale + (float) $sumToDateCache[$sumKey]; return $saldoAttesoAllaDataSaldo - $saldoCalcolatoAllaDataSaldo; } protected function resolveSaldoIniziale(int $stabileId, string $iban, string $fromDate): ?float { if (! DB::getSchemaBuilder()->hasTable('contabilita_saldi_conti')) { return null; } static $cache = []; $key = $stabileId . '|' . $iban . '|' . $fromDate; if (array_key_exists($key, $cache)) { return $cache[$key]; } $row = SaldoConto::query() ->where('stabile_id', $stabileId) ->where('iban', $iban) ->whereDate('data_saldo', '<=', $fromDate) ->orderByDesc('data_saldo') ->orderByDesc('id') ->first(); $cache[$key] = $row ? (float) $row->saldo : null; return $cache[$key]; } protected function resolveStatoQuadratura(MovimentoBanca $record): string { if ($record->registrazione_id === null) { return 'non_collegato'; } try { $row = DB::table('contabilita_movimenti') ->where('registrazione_id', (int) $record->registrazione_id) ->selectRaw("SUM(CASE WHEN tipo = 'dare' THEN importo ELSE 0 END) AS dare") ->selectRaw("SUM(CASE WHEN tipo = 'avere' THEN importo ELSE 0 END) AS avere") ->first(); $dare = $row && isset($row->dare) ? (float) $row->dare : 0.0; $avere = $row && isset($row->avere) ? (float) $row->avere : 0.0; if (abs($dare - $avere) <= 0.01) { return 'quadrato'; } return 'collegato_non_quadrato'; } catch (\Throwable) { return 'collegato_non_quadrato'; } } protected function resolveDefaultGestioneId(int $stabileId): ?string { if (! DB::getSchemaBuilder()->hasTable('gestioni_contabili')) { return null; } $anno = AnnoGestioneContext::resolveActiveAnno(); $tipo = GestioneContext::resolveActiveGestione(); $match = GestioneContabile::query() ->where('stabile_id', $stabileId) ->where('anno_gestione', $anno) ->where('tipo_gestione', $tipo) ->where('stato', 'aperta') ->orderByDesc('gestione_attiva') ->orderByDesc('id') ->first(); if (! $match) { $match = GestioneContabile::query() ->where('stabile_id', $stabileId) ->where('stato', 'aperta') ->orderByDesc('gestione_attiva') ->orderByDesc('id') ->first(); } return $match ? (string) $match->id : null; } protected function resolveSaldoProgressivo(MovimentoBanca $record): ?float { if (isset($record->saldo_progressivo)) { return is_numeric($record->saldo_progressivo) ? (float) $record->saldo_progressivo : null; } // Fallback (DB senza window functions): calcolo best-effort sul conto (IBAN) fino a questa riga. $q = MovimentoBanca::query() ->where('stabile_id', (int) $record->stabile_id) ->where(function (Builder $q) use ($record) { if ($record->iban === null) { $q->whereNull('iban'); } else { $q->where('iban', $record->iban); } }) ->where(function (Builder $q) use ($record) { $q->whereDate('data', '<', $record->data->toDateString()) ->orWhere(function (Builder $q) use ($record) { $q->whereDate('data', '=', $record->data->toDateString()) ->where('id', '<=', (int) $record->id); }); }); return (float) ($q->sum('importo') ?? 0); } protected function dbSupportsWindowFunctions(): bool { if (self::$supportsWindowFunctions !== null) { return self::$supportsWindowFunctions; } try { $driver = DB::getDriverName(); if ($driver === 'pgsql' || $driver === 'sqlite') { return self::$supportsWindowFunctions = true; } if ($driver !== 'mysql') { return self::$supportsWindowFunctions = false; } $row = DB::selectOne('select version() as v'); $v = is_object($row) && isset($row->v) ? (string) $row->v : ''; $vLower = strtolower($v); if (str_contains($vLower, 'mariadb')) { // MariaDB window functions: 10.2+ if (preg_match('/(\d+)\.(\d+)\.(\d+)/', $v, $m)) { $major = (int) $m[1]; $minor = (int) $m[2]; return self::$supportsWindowFunctions = ($major > 10) || ($major === 10 && $minor >= 2); } return self::$supportsWindowFunctions = false; } // MySQL window functions: 8.0+ if (preg_match('/(\d+)\.(\d+)\.(\d+)/', $v, $m)) { $major = (int) $m[1]; $minor = (int) $m[2]; return self::$supportsWindowFunctions = ($major > 8) || ($major === 8 && $minor >= 0); } return self::$supportsWindowFunctions = false; } catch (\Throwable) { return self::$supportsWindowFunctions = false; } } public function getActiveStabile(): ?Stabile { $user = Auth::user(); if (! $user instanceof User) { return null; } return StabileContext::getActiveStabile($user); } protected function getActiveStabileId(): ?int { $user = Auth::user(); if (! $user instanceof User) { return null; } return StabileContext::resolveActiveStabileId($user); } protected function normalizeHubTabValue(?string $value): string { $value = is_string($value) ? trim(strtolower($value)) : ''; return in_array($value, ['conti', 'saldi', 'movimenti', 'riconciliazione'], true) ? $value : 'conti'; } protected function syncSelectedContoFromId(?int $contoId): void { $contoId = $contoId && $contoId > 0 ? $contoId : null; $this->contoId = $contoId; if (! $contoId) { $this->iban = null; return; } $stabileId = $this->getActiveStabileId(); if (! $stabileId) { $this->contoId = null; $this->iban = null; return; } $conto = DatiBancari::query() ->where('stabile_id', $stabileId) ->where('id', $contoId) ->first(['id', 'iban']); if (! $conto) { $this->contoId = null; $this->iban = null; return; } $this->iban = $this->normalizeIbanValue($conto->iban); } protected function resetContoDependentState(): void { $this->periodoRateMap = []; $this->periodoRate = null; $this->riconciliazioneOffset = 0; $this->clearMovimentiFocus(); } protected function applyPeriodoStateFromFocusRange(): void { if (! $this->movimentiFocusFrom || ! $this->movimentiFocusTo) { return; } try { $from = Carbon::parse($this->movimentiFocusFrom); $to = Carbon::parse($this->movimentiFocusTo); } catch (\Throwable) { return; } $this->periodoAnno = (int) $from->year; $quarterStart = $from->copy()->startOfQuarter(); $quarterEnd = $from->copy()->endOfQuarter(); if ($from->isSameDay($quarterStart) && $to->isSameDay($quarterEnd)) { $this->periodoTipo = 'trimestre'; $this->periodoValore = (int) $from->quarter; return; } $this->periodoTipo = 'mese'; $this->periodoValore = (int) $from->month; } /** @return array> */ public function getHubContiRows(): array { $stabileId = $this->getActiveStabileId(); if (! $stabileId) { return []; } $rows = []; foreach ($this->getContiImportabili() as $conto) { $contoId = isset($conto['id']) && is_numeric($conto['id']) ? (int) $conto['id'] : 0; if ($contoId <= 0) { continue; } $iban = $this->normalizeIbanValue($conto['iban'] ?? null); $latestSaldo = $this->getLatestSaldoSnapshotForConto($stabileId, $contoId, $iban); $lastMovement = MovimentoBanca::query() ->where('stabile_id', $stabileId) ->where('conto_id', $contoId) ->orderByDesc('data') ->orderByDesc('id') ->first(['data']); $rows[] = [ 'id' => $contoId, 'label' => (string) ($conto['label'] ?? ('Conto #' . $contoId)), 'iban' => $iban, 'saldo_attuale' => $this->resolveSaldoAttualeConto($stabileId, $contoId, $iban), 'saldo_snapshot' => $latestSaldo?->saldo !== null ? (float) $latestSaldo->saldo : null, 'snapshot_data' => $latestSaldo?->data_saldo?->format('d/m/Y'), 'snapshot_tipo' => $latestSaldo ? $this->formatTipoEstrattoLabel($latestSaldo->tipo_estratto) : null, 'movimenti_count' => MovimentoBanca::query()->where('stabile_id', $stabileId)->where('conto_id', $contoId)->count(), 'ultima_movimentazione' => $lastMovement?->data?->format('d/m/Y'), 'selected' => $this->contoId === $contoId, ]; } return $rows; } /** @return array> */ public function getSaldoArchivioByYear(): array { $stabileId = $this->getActiveStabileId(); if (! $stabileId || ! DB::getSchemaBuilder()->hasTable('contabilita_saldi_conti')) { return []; } if (! $this->contoId && ! $this->normalizeIbanValue($this->iban)) { return []; } $query = SaldoConto::query() ->with('documento') ->where('stabile_id', $stabileId); if ($this->contoId) { $query->where('conto_id', $this->contoId); } else { $query->where('iban', $this->normalizeIbanValue($this->iban)); } $groups = []; foreach ($query->orderByDesc('data_saldo')->orderByDesc('id')->get() as $saldo) { $year = $saldo->data_saldo?->format('Y') ?? 'Senza data'; $groups[$year] ??= [ 'year' => $year, 'rows' => [], ]; $groups[$year]['rows'][] = [ 'id' => (int) $saldo->id, 'data' => $saldo->data_saldo?->format('d/m/Y') ?? '—', 'saldo' => (float) $saldo->saldo, 'tipo' => $this->formatTipoEstrattoLabel($saldo->tipo_estratto), 'periodo' => $this->formatPeriodoEstrattoLabel($saldo->periodo_da, $saldo->periodo_a), 'periodo_breve' => $this->formatPeriodoSinteticoLabel($saldo->periodo_da, $saldo->periodo_a, $saldo->data_saldo), 'note' => is_string($saldo->note) ? trim((string) $saldo->note) : '', 'documento_label' => $saldo->documento?->nome_originale, 'documento_url' => $saldo->documento?->url_view, ]; } krsort($groups); return array_values($groups); } /** @return array */ public function getRiconciliazioneStats(): array { $stabileId = $this->getActiveStabileId(); if (! $stabileId) { return ['totale' => 0, 'senza_prima_nota' => 0, 'collegati' => 0, 'da_confermare' => 0]; } $query = MovimentoBanca::query()->where('stabile_id', $stabileId); if ($this->contoId) { $query->where('conto_id', $this->contoId); } elseif ($this->iban) { $query->where('iban', $this->iban); } $totale = (clone $query)->count(); $senzaPrimaNota = Schema::hasColumn('contabilita_movimenti_banca', 'registrazione_id') ? (clone $query)->whereNull('registrazione_id')->count() : 0; $collegati = Schema::hasColumn('contabilita_movimenti_banca', 'registrazione_id') ? (clone $query)->whereNotNull('registrazione_id')->count() : 0; $daConfermare = Schema::hasColumn('contabilita_movimenti_banca', 'da_confermare') ? (clone $query)->where('da_confermare', true)->count() : 0; return [ 'totale' => $totale, 'senza_prima_nota' => $senzaPrimaNota, 'collegati' => $collegati, 'da_confermare' => $daConfermare, ]; } /** @return array> */ public function getRiconciliazioneQueue(): array { $stabileId = $this->getActiveStabileId(); if (! $stabileId) { return []; } $query = MovimentoBanca::query() ->where('stabile_id', $stabileId) ->when($this->contoId !== null, fn(Builder $q): Builder => $q->where('conto_id', $this->contoId)) ->when($this->contoId === null && $this->iban !== null, fn(Builder $q): Builder => $q->where('iban', $this->iban)) ->orderBy('data') ->orderBy('id'); if (Schema::hasColumn('contabilita_movimenti_banca', 'registrazione_id') || Schema::hasColumn('contabilita_movimenti_banca', 'da_confermare')) { $query->where(function (Builder $sub): void { if (Schema::hasColumn('contabilita_movimenti_banca', 'registrazione_id')) { $sub->whereNull('registrazione_id'); } if (Schema::hasColumn('contabilita_movimenti_banca', 'da_confermare')) { $sub->orWhere('da_confermare', true); } }); } return $query ->limit(200) ->get(['id', 'data', 'importo', 'descrizione', 'descrizione_estesa', 'match_data', 'registrazione_id']) ->map(function (MovimentoBanca $movimento): array { $stato = $this->resolveStatoQuadratura($movimento); return [ 'id' => (int) $movimento->id, 'data' => $movimento->data?->format('d/m/Y') ?? '—', 'importo' => (float) $movimento->importo, 'descrizione' => (string) ($movimento->descrizione_estesa_pulita ?? $movimento->descrizione_estesa ?? $movimento->descrizione ?? '—'), 'stato' => $stato, 'has_registrazione' => ! empty($movimento->registrazione_id), 'record' => $movimento, ]; }) ->all(); } /** @return array|null */ public function getRiconciliazioneCurrent(): ?array { $queue = $this->getRiconciliazioneQueue(); if ($queue === []) { $this->riconciliazioneOffset = 0; return null; } $max = max(0, count($queue) - 1); $this->riconciliazioneOffset = max(0, min($this->riconciliazioneOffset, $max)); return $queue[$this->riconciliazioneOffset] ?? null; } public function previousRiconciliazione(): void { $this->riconciliazioneOffset = max(0, $this->riconciliazioneOffset - 1); } public function nextRiconciliazione(): void { $queue = $this->getRiconciliazioneQueue(); if ($queue === []) { $this->riconciliazioneOffset = 0; return; } $this->riconciliazioneOffset = min(count($queue) - 1, $this->riconciliazioneOffset + 1); } /** @return array> */ public function getRiconciliazioneCandidates(): array { $current = $this->getRiconciliazioneCurrent(); if (! $current || ! ($current['record'] instanceof MovimentoBanca)) { return []; } $record = $current['record']; $stabileId = $this->getActiveStabileId(); if (! $stabileId) { return []; } if ((float) $record->importo >= 0) { return $this->buildIncassoCandidates($record, $stabileId); } return $this->buildFatturaCandidates($record, $stabileId); } protected function getLatestSaldoSnapshotForConto(int $stabileId, int $contoId, ?string $iban): ?SaldoConto { if (! DB::getSchemaBuilder()->hasTable('contabilita_saldi_conti')) { return null; } $query = SaldoConto::query()->where('stabile_id', $stabileId); if ($contoId > 0) { $query->where('conto_id', $contoId); } elseif ($iban) { $query->where('iban', $iban); } else { return null; } return $query->orderByDesc('data_saldo')->orderByDesc('id')->first(); } protected function resolveSaldoAttualeConto(int $stabileId, int $contoId, ?string $iban): float { $latestSaldo = $this->getLatestSaldoSnapshotForConto($stabileId, $contoId, $iban); $saldoBase = $latestSaldo ? (float) $latestSaldo->saldo : $this->resolveSaldoInizialeDaDatiBancari($stabileId, $contoId, $iban); $dataBase = $latestSaldo?->data_saldo?->toDateString(); $query = MovimentoBanca::query() ->where('stabile_id', $stabileId) ->where('conto_id', $contoId); if ($dataBase) { $query->whereDate('data', '>', $dataBase); } return $saldoBase + (float) ($query->sum('importo') ?? 0.0); } protected function formatPeriodoSinteticoLabel(mixed $from, mixed $to, mixed $fallbackDate = null): string { $fromDate = $from instanceof Carbon ? $from : ($from ? Carbon::parse((string) $from) : null); $toDate = $to instanceof Carbon ? $to : ($to ? Carbon::parse((string) $to) : null); if ($fromDate && $toDate) { $quarterStart = $fromDate->copy()->startOfQuarter(); $quarterEnd = $fromDate->copy()->endOfQuarter(); if ($fromDate->isSameDay($quarterStart) && $toDate->isSameDay($quarterEnd)) { return 'T' . $fromDate->quarter . ' / ' . $fromDate->format('Y'); } if ($fromDate->isSameDay($fromDate->copy()->startOfMonth()) && $toDate->isSameDay($fromDate->copy()->endOfMonth())) { return $fromDate->format('m/Y'); } } if ($fallbackDate instanceof Carbon) { return $fallbackDate->format('m/Y'); } return $this->formatPeriodoEstrattoLabel($from, $to); } /** @return array> */ protected function buildIncassoCandidates(MovimentoBanca $movimento, int $stabileId): array { if (! Schema::hasTable('incassi_pagamenti')) { return []; } $importo = abs((float) $movimento->importo); $descrizione = (string) ($movimento->descrizione_estesa_pulita ?? $movimento->descrizione_estesa ?? $movimento->descrizione ?? ''); return IncassoPagamento::query() ->with('rata') ->where('stabile_id', $stabileId) ->where('riconciliato', false) ->whereBetween('data_incasso', [ $movimento->data->copy()->subDays(30)->toDateString(), $movimento->data->copy()->addDays(30)->toDateString(), ]) ->whereBetween('importo', [$importo - 10, $importo + 10]) ->orderBy('data_incasso') ->limit(20) ->get() ->map(function (IncassoPagamento $incasso) use ($movimento, $descrizione, $importo): array { $score = $this->scoreCandidate( $importo, $movimento->data, $descrizione, (float) $incasso->importo, $incasso->data_incasso, trim((string) ($incasso->causale ?? '')) . ' ' . trim((string) ($incasso->note_bancarie ?? '')) ); return [ 'tipo' => 'Incasso registrato', 'titolo' => 'Incasso #' . (int) $incasso->id . ($incasso->rata ? (' · rata ' . (string) $incasso->rata->numero_rata) : ''), 'score' => $score['totale'], 'importo' => (float) $incasso->importo, 'data' => $incasso->data_incasso?->format('d/m/Y') ?? '—', 'dettaglio' => trim((string) ($incasso->causale ?? $incasso->modalita_pagamento_label ?? 'Incasso')), 'motivo' => $score['motivo'], ]; }) ->sortByDesc('score') ->take(5) ->values() ->all(); } /** @return array> */ protected function buildFatturaCandidates(MovimentoBanca $movimento, int $stabileId): array { if (! Schema::hasTable('fatture_elettroniche')) { return []; } $importo = abs((float) $movimento->importo); $descrizione = (string) ($movimento->descrizione_estesa_pulita ?? $movimento->descrizione_estesa ?? $movimento->descrizione ?? ''); return FatturaElettronica::query() ->where('stabile_id', $stabileId) ->whereBetween('data_fattura', [ $movimento->data->copy()->subDays(120)->toDateString(), $movimento->data->copy()->addDays(30)->toDateString(), ]) ->whereBetween('totale', [$importo - 15, $importo + 15]) ->orderByDesc('data_fattura') ->limit(20) ->get(['id', 'numero_fattura', 'data_fattura', 'totale', 'fornitore_denominazione', 'stato']) ->map(function (FatturaElettronica $fattura) use ($movimento, $descrizione, $importo): array { $score = $this->scoreCandidate( $importo, $movimento->data, $descrizione, (float) $fattura->totale, $fattura->data_fattura, trim((string) ($fattura->fornitore_denominazione ?? '')) . ' ' . trim((string) ($fattura->numero_fattura ?? '')) ); return [ 'tipo' => 'Fattura fornitore', 'titolo' => trim((string) ($fattura->fornitore_denominazione ?: 'Fattura')) . ' · n. ' . trim((string) ($fattura->numero_fattura ?: $fattura->id)), 'score' => $score['totale'], 'importo' => (float) $fattura->totale, 'data' => $fattura->data_fattura?->format('d/m/Y') ?? '—', 'dettaglio' => 'Stato FE: ' . trim((string) ($fattura->stato ?: '—')), 'motivo' => $score['motivo'], ]; }) ->sortByDesc('score') ->take(5) ->values() ->all(); } /** @return array{totale:int,motivo:string} */ protected function scoreCandidate(float $movimentoImporto, ?Carbon $movimentoData, string $movimentoText, float $candidateImporto, mixed $candidateData, string $candidateText): array { $score = 0; $motivi = []; $diffImporto = abs($movimentoImporto - $candidateImporto); if ($diffImporto < 0.01) { $score += 50; $motivi[] = 'importo identico'; } elseif ($diffImporto <= 1) { $score += 42; $motivi[] = 'importo quasi identico'; } elseif ($diffImporto <= 5) { $score += 30; $motivi[] = 'importo vicino'; } elseif ($diffImporto <= 15) { $score += 15; } if ($movimentoData && $candidateData) { $candidateCarbon = $candidateData instanceof Carbon ? $candidateData : Carbon::parse((string) $candidateData); $days = abs($movimentoData->diffInDays($candidateCarbon)); if ($days === 0) { $score += 25; $motivi[] = 'stessa data'; } elseif ($days <= 3) { $score += 20; $motivi[] = 'entro 3 giorni'; } elseif ($days <= 10) { $score += 12; } elseif ($days <= 30) { $score += 6; } } $overlap = $this->calculateTokenOverlap($movimentoText, $candidateText); if ($overlap >= 3) { $score += 25; $motivi[] = 'descrizione coerente'; } elseif ($overlap === 2) { $score += 18; } elseif ($overlap === 1) { $score += 8; } return [ 'totale' => min(100, $score), 'motivo' => $motivi !== [] ? implode(' · ', $motivi) : 'match debole da confermare', ]; } protected function calculateTokenOverlap(string $left, string $right): int { $leftTokens = $this->extractMeaningfulTokens($left); $rightTokens = $this->extractMeaningfulTokens($right); if ($leftTokens === [] || $rightTokens === []) { return 0; } return count(array_intersect($leftTokens, $rightTokens)); } /** @return array */ protected function extractMeaningfulTokens(string $value): array { $value = mb_strtolower($value); $value = preg_replace('/[^a-z0-9]+/u', ' ', $value) ?? $value; $parts = preg_split('/\s+/', trim($value)) ?: []; $stopWords = ['bonifico', 'pagamento', 'banca', 'conto', 'del', 'della', 'per', 'con', 'the', 'iban']; return array_values(array_unique(array_filter($parts, function (?string $token) use ($stopWords): bool { if (! is_string($token) || strlen($token) < 3) { return false; } return ! in_array($token, $stopWords, true); }))); } /** @return array */ public function getDisponibilitaFinanziarie(): array { $user = Auth::user(); if (! $user instanceof User) { return []; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return []; } $conti = []; if (DB::getSchemaBuilder()->hasTable('dati_bancari')) { $conti = DatiBancari::query() ->where('stabile_id', $stabileId) ->whereNotNull('iban') ->where('iban', '!=', '') ->orderBy('denominazione_banca') ->orderBy('iban') ->get(['id', 'denominazione_banca', 'iban', 'saldo_iniziale']) ->map(fn(DatiBancari $r) => [ 'id' => (int) $r->id, 'iban' => trim((string) $r->iban), 'label' => trim((string) ($r->denominazione_banca ?: 'Conto') . ' · ' . (string) $r->iban), 'saldo_iniziale' => is_numeric($r->saldo_iniziale) ? (float) $r->saldo_iniziale : 0.0, ]) ->filter(fn(array $r) => $r['iban'] !== '') ->values() ->all(); } $sums = MovimentoBanca::query() ->where('stabile_id', $stabileId) ->whereNotNull('iban') ->where('iban', '!=', '') ->groupBy('iban') ->selectRaw('iban, COALESCE(SUM(importo), 0) AS saldo_movimenti') ->pluck('saldo_movimenti', 'iban') ->map(fn($v) => (float) $v) ->all(); $byIban = []; foreach ($conti as $c) { $iban = $c['iban']; $saldo = ($c['saldo_iniziale'] ?? 0.0) + ($sums[$iban] ?? 0.0); $byIban[$iban] = [ 'id' => $c['id'] ?? null, 'iban' => $iban, 'label' => (string) $c['label'], 'saldo' => $saldo, ]; } foreach ($sums as $iban => $saldoMov) { if (! isset($byIban[$iban])) { $byIban[$iban] = [ 'id' => null, 'iban' => (string) $iban, 'label' => (string) $iban, 'saldo' => (float) $saldoMov, ]; } } uasort($byIban, fn($a, $b) => strcmp((string) $a['label'], (string) $b['label'])); return array_values($byIban); } /** @return array */ public function getContiImportabili(): array { $user = Auth::user(); if (! $user instanceof User) { return []; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId || ! DB::getSchemaBuilder()->hasTable('dati_bancari')) { return []; } return DatiBancari::query() ->where('stabile_id', $stabileId) ->orderBy('denominazione_banca') ->orderBy('legacy_cod_cassa') ->orderBy('iban') ->orderBy('numero_conto') ->get(['id', 'denominazione_banca', 'iban', 'numero_conto', 'legacy_cod_cassa']) ->map(function (DatiBancari $conto): array { $iban = is_string($conto->iban) ? trim((string) $conto->iban) : null; $iban = $iban !== '' ? $iban : null; $numeroConto = is_string($conto->numero_conto) ? trim((string) $conto->numero_conto) : null; $numeroConto = $numeroConto !== '' ? $numeroConto : null; $legacyCodCassa = is_string($conto->legacy_cod_cassa) ? strtoupper(trim((string) $conto->legacy_cod_cassa)) : null; $legacyCodCassa = $legacyCodCassa !== '' ? $legacyCodCassa : null; $denominazione = is_string($conto->denominazione_banca) ? trim((string) $conto->denominazione_banca) : null; $denominazione = $denominazione !== '' ? $denominazione : null; $parts = []; $parts[] = $denominazione ?: 'Conto'; if ($legacyCodCassa) { $parts[] = 'cassa ' . $legacyCodCassa; } if ($iban) { $parts[] = $iban; } elseif ($numeroConto) { $parts[] = 'n. ' . $numeroConto; } return [ 'id' => (int) $conto->id, 'iban' => $iban, 'label' => implode(' · ', $parts), 'legacy_cod_cassa' => $legacyCodCassa, 'numero_conto' => $numeroConto, 'denominazione_banca' => $denominazione, ]; }) ->values() ->all(); } /** @return array{id:int,iban:?string,label:string,legacy_cod_cassa:?string,numero_conto:?string,denominazione_banca:?string}|null */ public function getSelectedContoImportInfo(): ?array { if (! $this->contoId) { return null; } foreach ($this->getContiImportabili() as $conto) { if ((int) ($conto['id'] ?? 0) === $this->contoId) { return $conto; } } return null; } protected function resolvePreferredImportFormatForConto(?int $contoId): string { if (! $contoId) { return 'auto_csv'; } foreach ($this->getContiImportabili() as $conto) { if ((int) ($conto['id'] ?? 0) !== $contoId) { continue; } $haystack = strtolower(implode(' ', array_filter([ $conto['denominazione_banca'] ?? null, $conto['legacy_cod_cassa'] ?? null, $conto['numero_conto'] ?? null, ], static fn($value): bool => is_string($value) && trim($value) !== ''))); if (str_contains($haystack, 'mps') || str_contains($haystack, 'monte dei paschi') || str_contains($haystack, 'paschi')) { return 'mps_qif'; } if (str_contains($haystack, 'intesa')) { return 'intesa_csv'; } if (str_contains($haystack, 'unicredit')) { return 'unicredit_wri'; } return 'auto_csv'; } return 'auto_csv'; } protected function makeMovimentiImporter(): MovimentiBancaImporter { return new MovimentiBancaImporter( new UnicreditWriParser(), new IntesaCsvParser(), new ExcelMovimentiParser(), null, null, new MpsQifParser(), ); } public function getSelectedIbanLabel(): ?string { $iban = is_string($this->iban) ? trim($this->iban) : ''; if ($iban === '') { return null; } foreach ($this->getDisponibilitaFinanziarie() as $c) { if (($c['iban'] ?? '') === $iban) { return (string) ($c['label'] ?? $iban); } } return $iban; } protected function getDefaultIban(): string { foreach ($this->getDisponibilitaFinanziarie() as $c) { $iban = is_string($c['iban'] ?? null) ? trim((string) $c['iban']) : ''; if ($iban !== '') { return $iban; } } return ''; } /** @return array{label:string,data:?string,saldo:?float} */ public function getHeaderSaldoInfo(): array { $user = Auth::user(); if (! $user instanceof User) { return ['label' => 'Movimenti', 'data' => null, 'saldo' => null]; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId) { return ['label' => 'Movimenti', 'data' => null, 'saldo' => null]; } $conto = null; if ($this->contoId) { $conto = DatiBancari::query() ->where('stabile_id', $stabileId) ->where('id', $this->contoId) ->first(['id', 'denominazione_banca', 'iban']); } elseif ($this->iban) { $conto = DatiBancari::query() ->where('stabile_id', $stabileId) ->where('iban', $this->iban) ->orderBy('id') ->first(['id', 'denominazione_banca', 'iban']); } $label = $conto ? $this->buildContoLabel($conto) : (string) (($this->getSelectedContoImportInfo()['label'] ?? null) ?: ($this->getSelectedIbanLabel() ?: 'Movimenti')); $movQ = MovimentoBanca::query()->where('stabile_id', $stabileId); if ($this->contoId) { $movQ->where('conto_id', $this->contoId); } elseif ($this->iban) { $movQ->where('iban', $this->iban); } $lastMov = $movQ->orderByDesc('data')->orderByDesc('id')->first(['data']); // Saldo attuale: usa l'ultimo saldo inserito come base (se presente), poi somma i movimenti successivi. $iban = $this->normalizeIbanValue($this->iban); if (! $this->contoId && ! $iban) { return ['label' => $label, 'data' => $lastMov ? $lastMov->data->format('d/m/Y') : null, 'saldo' => null]; } $saldoBase = null; $dataBase = null; $periodFrom = null; if (is_array($this->tableFilters ?? null)) { $periodFrom = $this->tableFilters['periodo']['from'] ?? null; $periodFrom = is_string($periodFrom) && trim($periodFrom) !== '' ? trim($periodFrom) : null; } if (DB::getSchemaBuilder()->hasTable('contabilita_saldi_conti')) { $qSaldo = SaldoConto::query()->where('stabile_id', $stabileId); if ($this->contoId) { $qSaldo->where('conto_id', $this->contoId); } elseif ($iban) { $qSaldo->where('iban', $iban); } if ($periodFrom) { $qSaldo->whereDate('data_saldo', '<=', $periodFrom); } $row = $qSaldo->orderByDesc('data_saldo')->orderByDesc('id')->first(['data_saldo', 'saldo']); if ($row) { $saldoBase = (float) $row->saldo; $dataBase = $row->data_saldo->toDateString(); } } $saldoIniziale = $this->resolveSaldoInizialeDaDatiBancari($stabileId, $this->contoId, $iban); $sumQ = MovimentoBanca::query()->where('stabile_id', $stabileId); if ($this->contoId) { $sumQ->where('conto_id', $this->contoId); } elseif ($iban) { $sumQ->where('iban', $iban); } if ($dataBase) { $sumQ->whereDate('data', '>', $dataBase); } $sumAfter = (float) ($sumQ->sum('importo') ?? 0.0); $saldoAttuale = ($saldoBase !== null ? $saldoBase : $saldoIniziale) + $sumAfter; $dataLabel = $lastMov ? $lastMov->data->format('d/m/Y') : ($dataBase ? Carbon::parse($dataBase)->format('d/m/Y') : null); return ['label' => $label, 'data' => $dataLabel, 'saldo' => $saldoAttuale]; } public function getSaldoSnapshotCards(): array { $user = Auth::user(); if (! $user instanceof User) { return []; } $stabileId = StabileContext::resolveActiveStabileId($user); if (! $stabileId || ! DB::getSchemaBuilder()->hasTable('contabilita_saldi_conti')) { return []; } if (! $this->contoId && ! $this->normalizeIbanValue($this->iban)) { return []; } $query = SaldoConto::query() ->with('documento') ->where('stabile_id', $stabileId); if ($this->contoId) { $query->where('conto_id', $this->contoId); } else { $query->where('iban', $this->normalizeIbanValue($this->iban)); } return $query ->orderByDesc('data_saldo') ->orderByDesc('id') ->limit(6) ->get() ->map(function (SaldoConto $saldo): array { return [ 'data' => $saldo->data_saldo?->format('d/m/Y'), 'saldo' => (float) $saldo->saldo, 'tipo' => $this->formatTipoEstrattoLabel($saldo->tipo_estratto), 'periodo' => $this->formatPeriodoEstrattoLabel($saldo->periodo_da, $saldo->periodo_a), 'documento_label' => $saldo->documento?->nome_originale, 'documento_url' => $saldo->documento?->url_view, ]; }) ->all(); } protected function getTipoEstrattoOptions(): array { return [ 'estratto_conto' => 'Estratto conto', 'saldo_banca' => 'Saldo banca', 'riconciliazione' => 'Riconciliazione', 'altro' => 'Altro', ]; } protected function normalizeTipoEstrattoValue(mixed $value): ?string { $value = is_string($value) ? trim($value) : ''; if ($value === '') { return null; } return array_key_exists($value, $this->getTipoEstrattoOptions()) ? $value : 'altro'; } protected function formatTipoEstrattoLabel(?string $value): string { $value = $this->normalizeTipoEstrattoValue($value); if (! $value) { return 'Saldo registrato'; } return $this->getTipoEstrattoOptions()[$value] ?? 'Saldo registrato'; } protected function formatPeriodoEstrattoLabel(mixed $from, mixed $to): string { $fromDate = $from instanceof Carbon ? $from : ($from ? Carbon::parse((string) $from) : null); $toDate = $to instanceof Carbon ? $to : ($to ? Carbon::parse((string) $to) : null); if ($fromDate && $toDate) { return $fromDate->format('d/m/Y') . ' - ' . $toDate->format('d/m/Y'); } if ($toDate) { return 'Fino al ' . $toDate->format('d/m/Y'); } if ($fromDate) { return 'Dal ' . $fromDate->format('d/m/Y'); } return 'Periodo non indicato'; } protected function buildContoLabel(DatiBancari $conto): string { $parts = []; $parts[] = trim((string) ($conto->denominazione_banca ?: 'Conto')); $legacyCodCassa = is_string($conto->legacy_cod_cassa ?? null) ? trim((string) $conto->legacy_cod_cassa) : ''; $numeroConto = is_string($conto->numero_conto ?? null) ? trim((string) $conto->numero_conto) : ''; $iban = $this->normalizeIbanValue($conto->iban); if ($legacyCodCassa !== '') { $parts[] = 'cassa ' . strtoupper($legacyCodCassa); } if ($iban) { $parts[] = $iban; } elseif ($numeroConto !== '') { $parts[] = 'n. ' . $numeroConto; } return implode(' · ', array_filter($parts, fn(?string $part): bool => is_string($part) && trim($part) !== '')); } protected function normalizeIbanValue(mixed $value): ?string { $iban = is_string($value) ? trim((string) $value) : ''; return $iban !== '' ? $iban : null; } protected function storeSaldoDocumento(int $stabileId, DatiBancari $conto, mixed $tempPath, User $user, array $data): ?DocumentoStabile { $path = is_string($tempPath) ? trim($tempPath) : ''; if ($path === '') { return null; } $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION)); $extension = $extension !== '' ? $extension : 'bin'; $filename = 'estratto-conto-' . $stabileId . '-' . (int) $conto->id . '-' . now()->format('YmdHis') . '.' . $extension; $publicPath = 'documenti/stabili/' . $stabileId . '/bancari/' . $filename; Storage::disk('public')->put($publicPath, Storage::disk('local')->get($path)); try { Storage::disk('local')->delete($path); } catch (\Throwable) { // ignore } $descrizione = 'Estratto conto ' . $this->buildContoLabel($conto); $periodo = $this->formatPeriodoEstrattoLabel($data['periodo_da'] ?? null, $data['periodo_a'] ?? null); if ($periodo !== 'Periodo non indicato') { $descrizione .= ' · ' . $periodo; } return DocumentoStabile::query()->create([ 'stabile_id' => $stabileId, 'nome_file' => $filename, 'nome_originale' => $filename, 'percorso_file' => $publicPath, 'categoria' => 'bancari', 'tipo_mime' => Storage::disk('public')->mimeType($publicPath), 'dimensione' => Storage::disk('public')->size($publicPath), 'descrizione' => $descrizione, 'caricato_da' => (int) $user->id, ]); } }