55 lines
1.9 KiB
PHP
55 lines
1.9 KiB
PHP
<?php
|
|
namespace App\Modules\Contabilita\Services;
|
|
|
|
use App\Models\DatiBancari;
|
|
use App\Modules\Contabilita\Models\MovimentoBanca;
|
|
use App\Modules\Contabilita\Models\PianoConti;
|
|
use RuntimeException;
|
|
|
|
class ContiFinanziariService
|
|
{
|
|
public function resolveContoFinanziarioDaMovimentoBanca(MovimentoBanca $movimento): PianoConti
|
|
{
|
|
$stabileId = (int) ($movimento->stabile_id ?? 0);
|
|
if ($stabileId <= 0) {
|
|
throw new RuntimeException('Movimento banca senza stabile_id.');
|
|
}
|
|
|
|
$conto = null;
|
|
$contoId = (int) ($movimento->conto_id ?? 0);
|
|
if ($contoId > 0) {
|
|
$conto = DatiBancari::query()->find($contoId);
|
|
}
|
|
|
|
if (! $conto) {
|
|
$iban = is_string($movimento->iban ?? null) ? trim((string) $movimento->iban) : '';
|
|
if ($iban !== '') {
|
|
$conto = DatiBancari::query()
|
|
->where('stabile_id', $stabileId)
|
|
->where('iban', $iban)
|
|
->orderBy('id')
|
|
->first();
|
|
}
|
|
}
|
|
|
|
if (! $conto) {
|
|
throw new RuntimeException('Il movimento banca non ha un conto finanziario risolvibile. Seleziona o collega il conto bancario corretto.');
|
|
}
|
|
|
|
$codice = '1100B' . str_pad((string) $conto->id, 5, '0', STR_PAD_LEFT);
|
|
|
|
$label = trim((string) ($conto->denominazione_banca ?? 'Banca'));
|
|
$iban = is_string($conto->iban ?? null) ? trim((string) $conto->iban) : '';
|
|
$numeroConto = is_string($conto->numero_conto ?? null) ? trim((string) $conto->numero_conto) : '';
|
|
|
|
$descrizione = $label !== '' ? $label : 'Conto banca';
|
|
if ($iban !== '') {
|
|
$descrizione .= ' · ' . $iban;
|
|
} elseif ($numeroConto !== '') {
|
|
$descrizione .= ' · n. ' . $numeroConto;
|
|
}
|
|
|
|
return app(ChiusuraGestioneService::class)->resolveOrCreateConto($codice, $descrizione, 'Attività');
|
|
}
|
|
}
|