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

565 lines
19 KiB
PHP

<?php
namespace App\Console\Commands\Pegawai;
use App\Models\Verifikator\JabatanFungsional;
use App\Models\Verifikator\JabatanPegawai;
use App\Models\Verifikator\JabatanTugasTambahan;
use App\Models\Verifikator\View\Pegawai;
use App\Services\DawaiService;
use App\Services\P1PegawaiService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Throwable;
class UpdateJabatanPegawaiCommand extends Command
{
private DawaiService $dawaiService;
private P1PegawaiService $p1Service;
private array $month = [
'Januari' => 1,
'Februari' => 2,
'Maret' => 3,
'April' => 4,
'Mei' => 5,
'Juni' => 6,
'Juli' => 7,
'Agustus' => 8,
'September' => 9,
'Oktober' => 10,
'November' => 11,
'Desember' => 12,
];
private array $periode = [
'371' => 2021,
'374' => 2021,
'377' => 2022,
'380' => 2022,
'383' => 2023,
'386' => 2023,
'389' => 2024,
'392' => 2024,
'395' => 2025,
'398' => 2025,
'401' => 2026,
];
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'pegawai:sync-data {periode*}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Sinkronisasi data pegawai per periode';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->dawaiService = new DawaiService;
$this->p1Service = new P1PegawaiService;
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$periodes = $this->argument('periode');
$jabatanTambahanIds = config('jtt.universitas') ?? [];
$pegawais = Pegawai::query()
->withoutGlobalScope('aktif')
->whereNotIn('nip', ['dummy', 'verifikatorKK', '196512201994011001'])
->get();
// Hitung total iterasi untuk progress
$totalIterations = count($periodes) * $pegawais->count();
$currentIteration = 0;
// Cetak Header
$this->printHeader($periodes, $pegawais, $totalIterations);
// Tambahkan baris kosong untuk progress bar
echo "\n\n\n\n\n\n\n";
try {
DB::beginTransaction();
foreach ($periodes as $periode) {
foreach ($pegawais as $pegawai) {
$currentIteration++;
// Update progress bar
$this->updateProgressBar($currentIteration, $totalIterations, $periode, $pegawai->nip, $pegawai->nama);
$this->syncPegawaiData($pegawai, $periode, $jabatanTambahanIds);
// Small delay to make progress visible
usleep(1000); // 1ms delay
}
}
DB::commit();
// Clear progress lines and show completion
$this->clearProgressLines();
$this->printCompletion();
} catch (Throwable $th) {
DB::rollBack();
// Clear progress lines and show error
$this->clearProgressLines();
$this->printError($pegawai ?? null, $th);
throw $th;
}
return Command::SUCCESS;
}
/**
* Sync pegawai data for specific periode
*/
private function syncPegawaiData(Pegawai $pegawai, string $periode, array $jabatanTambahanIds): void
{
$newVersion = false;
$createdBy = null;
$existing = $this->getExistingJabatan($pegawai, $periode);
$dawai = $this->getSidiaData($pegawai, $periode);
if (! $dawai) {
return;
}
$fungsional = collect($dawai['data']['fungsional']);
$tambahan = collect($dawai['data']['tugas_tambahan']);
// Check if new version is needed
$checkResult = $this->checkNewVersion($existing, $fungsional, $tambahan);
$newVersion = $checkResult['newVersion'];
$createdBy = $checkResult['createdBy'];
// Create or update jabatan
$jabatan = $this->createOrUpdateJabatan($pegawai, $periode, $existing, $newVersion, $createdBy);
// Process jabatan details
$this->processJabatanDetails($jabatan, $fungsional, $tambahan, $jabatanTambahanIds);
// Recount remunerasi if needed
if ($newVersion && $periode == 389) {
Artisan::call('periode389:count-remunerasi '.$pegawai->nip);
}
}
/**
* Get existing jabatan pegawai
*/
private function getExistingJabatan(Pegawai $pegawai, string $periode): ?JabatanPegawai
{
return JabatanPegawai::with('detail')
->active()
->where(function ($query) use ($pegawai) {
$query->where('nip', $pegawai->nip)
->orWhere('nip', $pegawai->nip_siakad);
})
->where('periode', $periode)
->first();
}
/**
* Get DAWAI data for pegawai
*/
private function getSidiaData(Pegawai $pegawai, string $periode): ?array
{
$dawai = $this->dawaiService->getJabatan($pegawai->nip, $periode);
if (! $dawai) {
$dawai = $this->dawaiService->getJabatan($pegawai->nip_siakad, $periode);
}
return $dawai ?: null;
}
/**
* Check if new version is needed
*/
private function checkNewVersion(?JabatanPegawai $existing, $fungsional, $tambahan): array
{
$newVersion = false;
$createdBy = null;
if (! $existing) {
$newVersion = true;
}
if ($existing && $fungsional->count() == 0) {
$newVersion = true;
}
if ((! $existing || $existing->detail->count() === 0) && $fungsional->count() > 0) {
$newVersion = true;
$dataFungsional = $fungsional->last();
$dataTambahan = $tambahan->last();
if ($dataFungsional && count($dataFungsional['log']) > 0) {
$createdBy = $dataFungsional['log'][count($dataFungsional['log']) - 1]['username'];
}
if ($dataTambahan && count($dataTambahan['log']) > 0) {
$createdBy = $dataTambahan['log'][count($dataTambahan['log']) - 1]['username'];
}
}
// Check existing details for changes
foreach ($existing?->detail?->sortBy('bulan') ?? [] as $detail) {
if ($newVersion) {
continue;
}
$month = array_search($detail->bulan, $this->month);
if ($fungsional->where('bulan', $month)->count() > 0) {
$dataFungsional = $fungsional->where('bulan', $month)->first();
if ($this->hasFungsionalChanged($detail, $dataFungsional)) {
$newVersion = true;
$createdBy = $dataFungsional['log'][count($dataFungsional['log']) - 1]['username'];
break;
}
$dataTambahan = $tambahan->where('bulan', $month)->first();
if ($dataTambahan && $this->hasTambahanChanged($detail, $dataTambahan)) {
$newVersion = true;
$createdBy = $dataTambahan['log'][count($dataTambahan['log']) - 1]['username'];
break;
}
} else {
$dataFungsional = $fungsional->last()['log'] ?? [];
$dataTambahan = $tambahan->last()['log'] ?? [];
$newVersion = true;
if (count($dataFungsional) > 0) {
$createdBy = $dataFungsional[count($dataFungsional) - 1]['username'];
break;
}
if (count($dataTambahan) > 0) {
$createdBy = $dataTambahan[count($dataTambahan) - 1]['username'];
break;
}
}
}
return ['newVersion' => $newVersion, 'createdBy' => $createdBy];
}
/**
* Check if jabatan fungsional has changed
*/
private function hasFungsionalChanged($detail, array $dataFungsional): bool
{
$statusChanged = $detail->status_jf !== strtolower($dataFungsional['kode_status'])
&& ($detail->status_jf === 'nonaktif'
&& ! in_array(strtolower($dataFungsional['kode_status']), ['nonaktif', 'pensiun', 'wafat', 'mutkel']));
return $dataFungsional['id_jabatan'] !== $detail->jabatan_fungsional_id
|| $dataFungsional['status_pns'] !== $detail->status_pns
|| $dataFungsional['golongan'] !== $detail->golongan
|| $dataFungsional['jenis_pegawai'] !== $detail->jenis_pegawai
|| $dataFungsional['unit_kerja']['id'] !== $detail->unit_kerja_id
|| $statusChanged
|| $dataFungsional['p1'] != $detail->p1_jf
|| $dataFungsional['p2'] != $detail->p2_jf;
}
/**
* Check if jabatan tambahan has changed
*/
private function hasTambahanChanged($detail, array $dataTambahan): bool
{
$statusChanged = $detail->status_jtt !== strtolower($dataTambahan['kode_status'])
&& ($detail->status_jtt === 'nonaktif'
&& ! in_array(strtolower($dataTambahan['kode_status']), ['nonaktif', 'pensiun', 'wafat', 'mutkel']));
return $dataTambahan['id_jabatan'] !== $detail->jabatan_tambahan_id
|| $statusChanged
|| $dataTambahan['p1'] != $detail->p1_jtt
|| $dataTambahan['p2'] != $detail->p2_jtt;
}
/**
* Create or update jabatan pegawai
*/
private function createOrUpdateJabatan(
Pegawai $pegawai,
string $periode,
?JabatanPegawai $existing,
bool $newVersion,
?string $createdBy
): JabatanPegawai {
if ($newVersion) {
$existing?->update(['active' => false]);
// Cari version tertinggi untuk kombinasi nip + periode
$maxVersion = JabatanPegawai::where('nip', $pegawai->nip)
->where('periode', $periode)
->max('version') ?? 0;
return JabatanPegawai::create([
'nip' => $pegawai->nip,
'periode' => $periode,
'tahun' => $this->periode[$periode] ?? 2023,
'version' => $maxVersion + 1,
'created_by' => $createdBy,
'active' => true,
]);
}
return $existing;
}
/**
* Process jabatan details
*/
private function processJabatanDetails(
JabatanPegawai $jabatan,
$fungsional,
$tambahan,
array $jabatanTambahanIds
): void {
foreach ($fungsional as $jabFung) {
$unitPembayaran = $jabFung['unit_kerja']['id'] > 9 ? 0 : $jabFung['unit_kerja']['id'];
if ($jabFung['jenis_pegawai'] === 'tendik') {
$unitPembayaran = 0;
}
$this->checkJabatanFungsional($jabFung['id_jabatan']);
$jtt = $tambahan->where('bulan', $jabFung['bulan'])->first();
$jttData = $this->processJabatanTambahan($jtt, $jabatanTambahanIds);
if (
$jttData['id'] && in_array($jttData['id'], $jabatanTambahanIds)
&& in_array($jttData['status'], ['aktif', 'izbel'])
) {
$unitPembayaran = 0;
}
$p1 = $this->p1Service->p1(
$jabFung['p1'] ? $jabFung['id_jabatan'] : null,
$jabFung['p2'] ? $jttData['id'] : null,
$jabFung['status_pns']
);
$golongan = $jabFung['golongan'] ?? $fungsional->whereNotNull('golongan')->first()['golongan'];
$p1Tax = $this->p1Service->tax($p1, $golongan);
$jabatan->detail()->firstOrCreate(
[
'bulan' => $this->month[$jabFung['bulan']],
],
[
'unit_pembayaran_id' => $unitPembayaran,
'unit_kerja_id' => $jabFung['unit_kerja']['id'],
'jenis_pegawai' => $jabFung['jenis_pegawai'],
'jabatan_fungsional_id' => $jabFung['id_jabatan'],
'keterangan_jf' => $jabFung['keterangan_jabatan'],
'p1_jf' => $jabFung['p1'],
'p2_jf' => $jabFung['p2'],
'status_jf' => strtolower($jabFung['kode_status']),
'golongan' => $jabFung['golongan'],
'status_pns' => $jabFung['status_pns'],
'jabatan_tambahan_id' => $jttData['id'],
'keterangan_jtt' => $jttData['keterangan'],
'p1_jtt' => $jttData['p1'],
'p2_jtt' => $jttData['p2'],
'status_jtt' => $jttData['status'],
'p1' => $p1,
'p1_tax' => $p1Tax,
'p1_netto' => $p1 - $p1Tax,
]
);
}
}
/**
* Process jabatan tambahan data
*/
private function processJabatanTambahan(?array $jtt, array $jabatanTambahanIds): array
{
if (! $jtt) {
return [
'id' => null,
'keterangan' => null,
'p1' => false,
'p2' => false,
'status' => 'nonaktif',
];
}
$jttId = $jtt['id_jabatan'];
if ($jttId) {
$this->checkJabatanTambahan($jttId);
}
return [
'id' => $jttId,
'keterangan' => $jtt['keterangan_jabatan'],
'p1' => $jtt['p1'],
'p2' => $jtt['p2'],
'status' => strtolower($jtt['kode_status']),
];
}
/**
* Check and create jabatan fungsional if not exists
*/
private function checkJabatanFungsional(?int $id = null): void
{
if (! $id) {
return;
}
$exists = JabatanFungsional::find($id);
if (! $exists) {
$jf = $this->dawaiService->listJabatanFungsional($id);
$jf = $jf[0];
$jabatanFungsional = JabatanFungsional::create([
'id' => $id,
'nama' => $jf['nama'],
'jenis_pegawai_id' => $jf['jenis_pegawai'] === 'dosen' ? 1 : 2,
]);
$jabatanFungsional->detail()->create([
'periode' => 377,
'grade' => $jf['grade'],
'harga' => $jf['harga'],
]);
}
}
/**
* Check and create jabatan tambahan if not exists
*/
private function checkJabatanTambahan(?int $id = null): void
{
if (! $id) {
return;
}
$exists = JabatanTugasTambahan::find($id);
if (! $exists) {
$jt = $this->dawaiService->listJabatanTambahan($id);
$jt = $jt[0];
$jabatanTambahan = JabatanTugasTambahan::create([
'id' => $id,
'nama' => $jt['nama'],
'jenis_pegawai_id' => $jt['jenis_pegawai'] === 'dosen' ? 1 : 2,
]);
$jabatanTambahan->detail()->create([
'periode' => 377,
'grade' => $jt['grade'],
'harga' => $jt['harga'],
]);
}
}
/**
* Print header information
*/
private function printHeader(array $periodes, $pegawais, int $totalIterations): void
{
$this->info('══════════════════════════════════════════════════════');
$this->info(' SYNC DATA PEGAWAI PER PERIODE ');
$this->info('══════════════════════════════════════════════════════');
$this->info('Total Periode: '.count($periodes));
$this->info('Total Pegawai: '.$pegawais->count());
$this->info('Total Proses: '.$totalIterations);
$this->info('══════════════════════════════════════════════════════');
}
/**
* Update progress bar display
*/
private function updateProgressBar(int $current, int $total, string $periode, string $nip, string $nama): void
{
// Calculate progress
$progress = number_format(($current / $total) * 100, 2);
$barLength = 43;
$filledLength = round(($barLength * $current) / $total);
$progressBar = str_repeat('█', $filledLength).str_repeat('░', $barLength - $filledLength);
// Data counts
$dataCount = $current.'/'.$total;
// Move cursor back to update lines
echo "\033[F\033[F\033[F\033[F\033[F\033[F\033[F";
// Print updated information
$this->info('Periode: '.str_pad($periode, 10).' | Progress: '.$progress.'%');
$this->info('NIP: '.str_pad($nip, 25));
$this->info('Nama: '.str_pad(substr($nama, 0, 40), 40));
$this->info('Progress: |'.$progressBar.'|');
$this->info('Data: '.$dataCount);
$this->info('Status: Memproses...');
$this->info('');
}
/**
* Clear progress lines
*/
private function clearProgressLines(): void
{
echo "\033[F\033[F\033[F\033[F\033[F\033[F\033[F";
}
/**
* Print completion message
*/
private function printCompletion(): void
{
$this->info('══════════════════════════════════════════════════════');
$this->info(' SINKRONISASI SELESAI ');
$this->info('══════════════════════════════════════════════════════');
}
/**
* Print error message
*/
private function printError(?Pegawai $pegawai, Throwable $th): void
{
$this->error('══════════════════════════════════════════════════════');
$this->error(' ERROR OCCURRED ');
$this->error('══════════════════════════════════════════════════════');
$this->error('NIP: '.($pegawai->nip ?? 'Unknown'));
$this->error('Nama: '.($pegawai->nama ?? 'Unknown'));
$this->error('Error: '.$th->getMessage());
}
}