Files
verifikator/app/Console/Commands/Remunerasi/HitungSimulasiP2Mengajar2026JsonCommand.php
T

220 lines
8.1 KiB
PHP

<?php
namespace App\Console\Commands\Remunerasi;
use App\Models\Verifikator\Periode;
use App\Models\Verifikator\View\Pegawai;
use App\Services\PerhitunganKegiatanSimulasiService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class HitungSimulasiP2Mengajar2026JsonCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'remunerasi:simulasi-p2-mengajar-2026-json
{nip?* : NIP pegawai (boleh satu atau lebih, pisahkan spasi)}
{--all : Proses semua pegawai yang memiliki jabatan aktif}
{--periode= : ID periode (default: periode aktif)}
{--unit= : Filter berdasarkan ID unit kerja}
{--dry-run : Tampilkan hasil di terminal saja tanpa menulis file JSON}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Hitung remunerasi simulasi P2 mengajar 2026 (aturan standar sebelum 401 dan data API aktif) lalu simpan ke JSON di resources/data/2026/simulasi-p2-mengajar-2026/ tanpa menyentuh database';
public function handle(): int
{
$periode = (int) ($this->option('periode') ?? Periode::where('status', true)->value('id_periode'));
if (! $periode) {
$this->error('Periode tidak ditemukan. Gunakan opsi --periode=<id_periode>.');
return self::FAILURE;
}
$namaPeriode = (string) (Periode::where('id_periode', $periode)->value('nama') ?? $periode);
$this->info("Menjalankan Simulasi P2 Mengajar 2026 untuk Periode: {$periode} ({$namaPeriode})");
$nips = $this->argument('nip');
if ($this->option('all') || empty($nips)) {
$query = Pegawai::withoutGlobalScope('aktif')
->whereHas('jabatans', function ($q) use ($periode) {
$q->where('periode', $periode)->where('active', true);
});
if ($this->option('unit')) {
$query->where('unit_kerja_id', $this->option('unit'));
}
$nips = $query->pluck('nip')->unique()->filter()->values()->toArray();
$this->info('Memproses semua pegawai yang terdaftar: '.count($nips).' pegawai.');
}
if (empty($nips)) {
$this->warn('Tidak ada NIP pegawai yang akan diproses.');
return self::FAILURE;
}
$bulan = $periode % 2 === 1 ? [1, 2, 3, 4, 5, 6] : [7, 8, 9, 10, 11, 12];
$service = new PerhitunganKegiatanSimulasiService;
$hasil = [];
$bar = $this->output->createProgressBar(count($nips));
$bar->setFormat(" %current%/%max% [%bar%] %percent:3s%% -- %message%\n");
$bar->setMessage('Memulai perhitungan...');
$bar->start();
foreach ($nips as $nip) {
$nip = preg_replace("/['.\-\s]/", '', (string) $nip);
if ($nip === '') {
$bar->advance();
continue;
}
$pegawai = Pegawai::withoutGlobalScope('aktif')->with([
'jabatans' => fn ($q) => $q->where('periode', $periode)->where('active', true),
'jabatans.detail' => fn ($q) => $q->whereIn('bulan', $bulan),
'unit:id,nama',
])
->where(fn ($q) => $q->where('nip', $nip)->orWhere('nip_siakad', $nip))
->first();
if (! $pegawai) {
$bar->setMessage("NIP {$nip} tidak ditemukan.");
$bar->advance();
continue;
}
$bar->setMessage(mb_substr((string) $pegawai->nama, 0, 30));
// Hanya proses bulan yang memiliki hak P2 untuk menghindari eksekusi create/delete di DB
$details = $pegawai->jabatans->first()?->detail ?? collect();
$bulanLayak = $details->filter(fn ($d) => $d->p2_jf === true || $d->p2_jtt === true)->pluck('bulan')->sort()->values()->all();
if (empty($bulanLayak)) {
$bar->advance();
continue;
}
try {
// Service simulasi tidak menulis ke DB. Parameter: aturanBaru = false (ATURAN STANDAR SEBELUM 401), useDataApi = true (DATA API AKTIF)
$kegiatans = $service->listKegiatan(
$pegawai->nip,
$periode,
$bulanLayak,
null,
aturanBaru: false,
useDataApi: true
);
} catch (Exception $e) {
$this->newLine();
$this->warn("{$nip} ({$pegawai->nama}): Gagal dihitung - {$e->getMessage()}");
$bar->advance();
continue;
}
$totalBruto = 0.0;
$totalPajak = 0.0;
$totalNetto = 0.0;
foreach ($kegiatans ?: [] as $bulanNum => $dataBulan) {
foreach ($dataBulan['units'] ?? [] as $unit) {
$totalBruto += (float) ($unit['p2']['ratio'] ?? ($unit['p2']['bruto'] ?? 0));
$totalPajak += (float) ($unit['p2']['tax'] ?? 0);
$totalNetto += (float) ($unit['p2']['netto'] ?? 0);
}
}
$unitKerjaId = $pegawai->unit_kerja_id ?? $details->first()?->unit_kerja_id;
$unitPembayaranId = $details->first()?->unit_pembayaran_id ?? $unitKerjaId;
$hasil[$pegawai->nip] = [
'nip' => $pegawai->nip,
'nama' => $pegawai->nama,
'unit_kerja_id' => $unitKerjaId !== null ? (int) $unitKerjaId : null,
'unit_pembayaran_id' => $unitPembayaranId !== null ? (int) $unitPembayaranId : null,
'p2_bruto' => $this->rapikan($totalBruto),
'p2_pajak' => $this->rapikan($totalPajak),
'p2_netto' => $this->rapikan($totalNetto),
];
$bar->advance();
}
$bar->finish();
$this->newLine(2);
if (empty($hasil)) {
$this->warn('Tidak ada data hasil perhitungan yang diproses.');
return self::FAILURE;
}
// Tampilkan ringkasan di console
$this->info('Ringkasan Hasil Perhitungan:');
$sampleCount = 0;
foreach ($hasil as $nipKey => $row) {
$this->line(sprintf(
'%-18s %-32s | Bruto: Rp %14s | Pajak: Rp %12s | Netto: Rp %14s',
$nipKey,
mb_substr($row['nama'], 0, 32),
number_format($row['p2_bruto'], 2, ',', '.'),
number_format($row['p2_pajak'], 2, ',', '.'),
number_format($row['p2_netto'], 2, ',', '.')
));
$sampleCount++;
if ($sampleCount >= 10 && count($hasil) > 10) {
$this->line('... dan '.(count($hasil) - 10).' pegawai lainnya.');
break;
}
}
if ($this->option('dry-run')) {
$this->info('Mode --dry-run aktif: Data tidak ditulis ke file JSON.');
return self::SUCCESS;
}
// Simpan ke direktori yang diminta: resources/data/2026/simulasi-p2-mengajar-2026/
$directory = resource_path('data/2026/simulasi-p2-mengajar-2026');
File::ensureDirectoryExists($directory);
$filename = "periode_{$periode}.json";
$filepath = "{$directory}/{$filename}";
$existing = is_file($filepath) ? (json_decode((string) file_get_contents($filepath), true) ?: []) : [];
$merged = array_replace($existing, $hasil);
ksort($merged, SORT_STRING);
File::put($filepath, json_encode($merged, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
$this->info("✓ Berhasil menyimpan ".count($hasil)." pegawai ke JSON:");
$this->info(" Lokasi: {$filepath} (Total: ".count($merged)." entri tersimpan)");
return self::SUCCESS;
}
/**
* Membulatkan nilai desimal ke 2 angka dan membuang .0 untuk bilangan bulat
*/
private function rapikan(float $nilai): int|float
{
$nilai = round($nilai, 2);
return $nilai == floor($nilai) ? (int) $nilai : $nilai;
}
}