61 lines
2.4 KiB
PHP
61 lines
2.4 KiB
PHP
<?php
|
|
namespace App\Services\Stabili;
|
|
|
|
use App\Models\Amministratore;
|
|
use App\Models\Stabile;
|
|
use App\Models\StabileAmministratoreTransfer;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
|
|
class StabileTransferService
|
|
{
|
|
public function transfer(
|
|
Stabile $stabile,
|
|
Amministratore $destination,
|
|
?User $actor = null,
|
|
bool $alsoRubrica = true,
|
|
?string $reason = null,
|
|
string $source = 'portal-superadmin',
|
|
?string $ipAddress = null,
|
|
array $meta = []
|
|
): StabileAmministratoreTransfer {
|
|
$fromId = (int) ($stabile->amministratore_id ?? 0);
|
|
$toId = (int) $destination->id;
|
|
|
|
if ($fromId === $toId) {
|
|
throw new \InvalidArgumentException('Lo stabile e` gia` assegnato a questo amministratore.');
|
|
}
|
|
|
|
return DB::transaction(function () use ($stabile, $destination, $actor, $alsoRubrica, $reason, $source, $ipAddress, $meta, $fromId, $toId): StabileAmministratoreTransfer {
|
|
$stabile->amministratore_id = $toId;
|
|
$stabile->save();
|
|
|
|
if ($alsoRubrica && (int) ($stabile->rubrica_id ?? 0) > 0) {
|
|
if (Schema::hasTable('rubrica_universale') && Schema::hasColumn('rubrica_universale', 'amministratore_id')) {
|
|
DB::table('rubrica_universale')
|
|
->where('id', (int) $stabile->rubrica_id)
|
|
->update(['amministratore_id' => $toId, 'updated_at' => now()]);
|
|
}
|
|
}
|
|
|
|
if (method_exists($destination, 'provisionArchiveIfMissing')) {
|
|
$destination->provisionArchiveIfMissing();
|
|
}
|
|
|
|
return StabileAmministratoreTransfer::query()->create([
|
|
'stabile_id' => (int) $stabile->id,
|
|
'from_amministratore_id' => $fromId > 0 ? $fromId : null,
|
|
'to_amministratore_id' => $toId,
|
|
'changed_by_user_id' => $actor?->id,
|
|
'changed_by_name' => $actor?->name ?: 'Sistema',
|
|
'source' => $source,
|
|
'reason' => $reason !== null ? trim($reason) : null,
|
|
'also_rubrica' => $alsoRubrica,
|
|
'ip_address' => $ipAddress,
|
|
'meta' => $meta,
|
|
]);
|
|
});
|
|
}
|
|
}
|