Files
verifikator/app/Console/Commands/SK/SKReklaimAllVerifikasiCommand.php
2026-08-07 10:47:09 +07:00

343 lines
12 KiB
PHP

<?php
namespace App\Console\Commands\SK;
use App\Models\Siska\Sk as SiskaSk;
use App\Models\Verifikator\Periode;
use App\Models\Verifikator\Sk;
use App\Services\DokSiremunService;
use App\Services\SiskaService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class SKReklaimAllVerifikasiCommand extends Command
{
private SiskaService $siskaService;
private DokSiremunService $dokumenService;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sk:reklaim-all {--unit= : Filter berdasarkan ID Unit Penandatangan} {--limit= : Batasi jumlah SK yang diproses}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Reklaim semua SK dari SK Klaim Ulang yang belum diklaim ke periode aktif';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->siskaService = new SiskaService();
$this->dokumenService = new DokSiremunService();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$unitFilter = $this->option('unit');
$limit = $this->option('limit');
// Cetak Header
$this->printHeader($unitFilter, $limit);
// Ambil semua data dari API reclaim
$this->info('Mengambil data SK dari API reclaim...');
$allData = $this->getAllReclaimData();
if (empty($allData)) {
$this->warn('Tidak ada data SK yang ditemukan dari API reclaim');
return Command::SUCCESS;
}
// Filter berdasarkan unit jika ada
if ($unitFilter) {
$allData = array_filter($allData, function ($row) use ($unitFilter) {
return $row['id_unit_penandatangan'] == $unitFilter;
});
$this->info("Filter unit: {$unitFilter}");
}
// Ambil periode aktif untuk reklaim SK baru
$periodeAktif = Periode::where('status', true)->first();
if (!$periodeAktif) {
$this->error('Tidak ada periode aktif');
return Command::FAILURE;
}
$this->info("Target periode reklaim: {$periodeAktif->nama} (ID: {$periodeAktif->id_periode})");
// Proses setiap SK - filter hanya yang belum diklaim di periode aktif
$dataToProcess = [];
foreach ($allData as $item) {
// Cek apakah SK sudah diklaim di periode aktif
$sudahDiklaim = Sk::where('id_sk', $item['id'])
->where('periode', $periodeAktif->id_periode)
->exists();
// Hanya proses SK yang BELUM diklaim di periode aktif
if (!$sudahDiklaim) {
$item['periode_reklaim'] = $periodeAktif->id_periode;
$item['periode_nama'] = $periodeAktif->nama;
$dataToProcess[] = $item;
}
}
if (empty($dataToProcess)) {
$this->warn('Semua SK sudah diklaim di periode aktif');
return Command::SUCCESS;
}
// Batasi jumlah jika ada limit
if ($limit) {
$dataToProcess = array_slice($dataToProcess, 0, $limit);
}
$totalSk = count($dataToProcess);
$this->info("Total SK yang akan diproses: {$totalSk}");
$this->info('══════════════════════════════════════════════════════');
if (!$this->confirm('Lanjutkan proses reklaim?', true)) {
$this->info('Proses dibatalkan');
return Command::SUCCESS;
}
// Progress tracking
$processed = 0;
$success = 0;
$failed = 0;
$errors = [];
$progressBar = $this->output->createProgressBar($totalSk);
$progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% -- %message%');
$progressBar->setMessage('Memulai...');
$progressBar->start();
foreach ($dataToProcess as $item) {
// Tampilkan info SK yang sedang diproses
$tentang = substr($item['tentang'], 0, 50) . (strlen($item['tentang']) > 50 ? '...' : '');
$message = sprintf(
'ID: %s | %s | Periode: %s',
$item['id'],
$tentang,
$item['periode_nama']
);
$progressBar->setMessage($message);
try {
$this->prosesReklaimSk($item);
$success++;
} catch (Exception $e) {
$failed++;
$errors[] = [
'id_sk' => $item['id'],
'no_sk' => $item['no_sk'],
'tentang' => $item['tentang'],
'periode' => $item['periode_nama'] ?? 'Unknown',
'error' => $e->getMessage()
];
// Log error dengan try-catch untuk menghindari crash jika log file bermasalah
try {
Log::error("Error reklaim SK {$item['id']}: " . $e->getMessage());
} catch (\Throwable $logError) {
// Ignore log errors
}
}
$processed++;
$progressBar->advance();
}
$progressBar->setMessage('Selesai!');
$progressBar->finish();
$this->newLine(2);
// Print hasil
$this->printResult($totalSk, $success, $failed, $errors);
return Command::SUCCESS;
}
/**
* Ambil semua data dari API reclaim
*/
private function getAllReclaimData(): array
{
$allData = [];
$page = 1;
$maxPages = 50; // Tingkatkan maksimal halaman
while ($page <= $maxPages) {
// Suppress error logging untuk 404 di halaman selanjutnya
try {
$response = $this->siskaService->skReclaim($page);
if ($response === null) {
// Jika halaman pertama null, mungkin ada masalah
if ($page === 1) {
$this->warn('Service SISKA tidak tersedia atau sedang maintenance');
}
break;
}
$data = $response['data'] ?? [];
if (empty($data)) {
break;
}
$allData = array_merge($allData, $data);
$page++;
} catch (\Throwable $e) {
// Ignore errors pada pagination, biasanya 404 karena data habis
break;
}
}
return $allData;
}
/**
* Proses reklaim SK
*/
private function prosesReklaimSk(array $item): void
{
// Log info SK yang sedang diproses
$this->info("Memproses SK ID: {$item['id']} - {$item['tentang']}");
DB::beginTransaction();
try {
// Ambil data dari Siska SK
$siska = SiskaSk::find($item['id']);
// Gunakan periode reklaim yang sudah ditentukan
$periodeReklaim = $item['periode_reklaim'];
$this->info(" → Periode: {$periodeReklaim}");
// Simpan SK ke tabel verifikator.sks
$sk = Sk::updateOrCreate(
[
'id_sk' => $item['id'],
'periode' => $periodeReklaim,
],
[
'id_unit' => $item['id_unit'],
'id_unit_penandatangan' => $item['id_unit_penandatangan'],
'id_pimpinan' => $siska->id_pimpinan ?? null,
'no_sk' => $item['no_sk'],
'tanggal' => $item['tanggal_sk'],
'tentang' => $item['tentang'],
'verif_verifikator' => $item['status_verifikator'],
'finalisasi' => $item['finalisasi'],
'must_fix' => $item['must_fix'],
'sk_jadi' => $item['sk'],
'visible' => false,
]
);
// Simpan anggota SK
$jumlahAnggota = count($item['anggota']);
$this->info(" → Menyimpan {$jumlahAnggota} anggota SK...");
foreach ($item['anggota'] as $anggota) {
$sk->anggota()->updateOrCreate(
[
'id_anggota_sk' => $anggota['id'],
],
[
'id_sk' => $item['id'],
'kategori_id' => $anggota['kategori_id'],
'rubrik_id' => $anggota['rubrik_id'],
'nip' => $anggota['nip'],
'nama' => $anggota['nama'],
'jangka_waktu' => 6, // Statis 6 bulan
'catatan' => 'SK Periode Sebelumnya - ' . $periodeReklaim,
'keterangan' => $anggota['keterangan'],
'posisi' => $anggota['posisi'],
]
);
}
// Verifikasi SK jika sudah terverifikasi dan finalisasi SEBELUM commit
if ($item['status_verifikator'] && $item['finalisasi']) {
$this->info(" → Memverifikasi dokumen SK...");
try {
$this->dokumenService->verifikasiSkSemesterLalu($item['id']);
$this->info(" ✓ Dokumen SK berhasil diverifikasi");
} catch (Exception $verificationError) {
// Jika verifikasi dokumen gagal, rollback transaksi
DB::rollback();
$this->error(" ✗ Verifikasi dokumen gagal, transaksi dibatalkan");
throw new Exception("Dokumen Verifikasi SK Semester Lalu ({$item['id']}): " . $verificationError->getMessage());
}
}
DB::commit();
$this->info(" ✓ SK berhasil disimpan ke database");
} catch (Exception $e) {
DB::rollback();
throw $e;
}
}
/**
* Print header information
*/
private function printHeader($unitFilter, $limit): void
{
$this->info('══════════════════════════════════════════════════════');
$this->info(' REKLAIM SEMUA SK KLAIM ULANG ');
$this->info('══════════════════════════════════════════════════════');
$this->info('Mode: Reklaim SK yang belum diklaim ke periode aktif');
if ($unitFilter) {
$this->info('Unit Filter: ' . $unitFilter);
}
if ($limit) {
$this->info('Limit: ' . $limit . ' SK');
}
$this->info('══════════════════════════════════════════════════════');
}
/**
* Print hasil proses
*/
private function printResult(int $total, int $success, int $failed, array $errors): void
{
$this->info('══════════════════════════════════════════════════════');
$this->info(' HASIL REKLAIM SK ');
$this->info('══════════════════════════════════════════════════════');
$this->info("Total SK Diproses: {$total}");
$this->info("Berhasil: {$success}");
$this->info("Gagal: {$failed}");
$this->info('══════════════════════════════════════════════════════');
if (!empty($errors)) {
$this->error('Detail Error:');
foreach ($errors as $error) {
$periode = isset($error['periode']) ? " - Periode: {$error['periode']}" : '';
$tentang = isset($error['tentang']) ? substr($error['tentang'], 0, 40) . '...' : '';
$this->error("- SK #{$error['id_sk']} | {$tentang} | ({$error['no_sk']}){$periode}");
$this->error(" Error: {$error['error']}");
}
}
}
}