Penambahn P1 Dev

This commit is contained in:
Ariyutta
2026-10-20 10:24:22 +07:00
parent 8418a63fc0
commit ee0e6deacc
43 changed files with 5406 additions and 44 deletions
+80
View File
@@ -0,0 +1,80 @@
<?php
namespace App\Services\P1Dev;
use Error;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Throwable;
class DawaiService extends \App\Services\DawaiService
{
private Client $client;
public function __construct($default = 'http://172.16.40.128/')
{
parent::__construct($default);
$this->client = new Client(['base_uri' => $default, 'timeout' => 0]);
}
public function setPembayaranP1(string $nip, int $tahun, int $bulan): bool
{
try {
$response = $this->client->post('api/v1/update-paid-at-psatu', [
'multipart' => [
['name' => 'nip', 'contents' => $nip],
['name' => 'tahun', 'contents' => (string) $tahun],
['name' => 'bulan', 'contents' => (string) $bulan],
],
'connect_timeout' => 5,
'timeout' => 15,
]);
$data = json_decode((string) $response->getBody(), true);
if (! is_array($data)
|| (array_key_exists('status', $data) && ! $data['status'])
|| (array_key_exists('success', $data) && ! $data['success'])
|| (isset($data['meta']['code']) && (int) $data['meta']['code'] >= 400)) {
throw new Error($data['message'] ?? $data['meta']['message'] ?? 'Respons pembayaran DAWAI tidak berhasil');
}
return true;
} catch (Throwable $th) {
Log::error('DAWAI pembayaran P1: '.$th->getMessage(), compact('nip', 'tahun', 'bulan'));
return false;
}
}
public function getDataP1Response(?string $jenisPegawai, int $tahun, int $bulan, ?int $unit): array
{
try {
$response = $this->client->get("api/v1/psatu/$tahun/$bulan/?id_unit=$unit&jenis_pegawai=$jenisPegawai", [
'connect_timeout' => 3,
'timeout' => 10,
]);
$data = json_decode($response->getBody()->getContents(), true);
return is_array($data) ? $data : [];
} catch (Throwable $th) {
Log::error('DAWAI : '.$th->getMessage());
throw new Error($th->getMessage(), 500);
}
}
public function getDataP1SelisihResponse(?string $jenisPegawai, int $tahun, int $bulan, ?int $unit): array
{
try {
$response = $this->client->get("api/v1/psatu/$tahun/$bulan/?id_unit=$unit&jenis_pegawai=$jenisPegawai&selisih=true", [
'connect_timeout' => 3,
'timeout' => 10,
]);
$data = json_decode($response->getBody()->getContents(), true);
return is_array($data) ? $data : [];
} catch (Throwable $th) {
Log::error('DAWAI : '.$th->getMessage());
throw new Error($th->getMessage(), 500);
}
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Services\P1Dev;
use App\Models\Rekapitulasi\P1Dev as P1;
use App\Models\Rekapitulasi\P1Penyesuaian;
use App\Models\Verifikator\JabatanFungsional;
use App\Models\Verifikator\JabatanTugasTambahan;
use Illuminate\Support\Facades\DB;
class P1ChangeHistory
{
public function load(string $nip, int $year): array
{
$jf = JabatanFungsional::with('detail')->get()->keyBy('id');
$jtt = JabatanTugasTambahan::with('detail')->get()->keyBy('id');
$paid = DB::connection('sidia')->table('p_satus')->where('nip', $nip)->where('tahun', (string) $year)
->whereNull('deleted_at')->orderByRaw('paid_at IS NOT NULL')->orderBy('id')->get()
->keyBy(fn ($row) => (int) $row->bulan);
$corrections = P1Penyesuaian::where('nip', $nip)->where('tahun', $year)->orderBy('id')->get()
->keyBy(fn ($row) => (int) $row->bulan);
$result = [];
foreach (P1::where('nip', $nip)->where('tahun', $year)->orderBy('bulan')->get() as $record) {
$month = (int) $record->bulan;
$old = $paid->get($month);
$before = $old ? [
'jafung' => $jf->get($old->jafung_id)?->nama ?? '-',
'grade_jafung' => $jf->get($old->jafung_id)?->detail?->grade,
'jtt' => $jtt->get($old->jtt_id)?->nama ?? '-',
'grade_jtt' => $jtt->get($old->jtt_id)?->detail?->grade,
'golongan' => $old->golongan,
'status_pegawai' => $old->status_pegawai,
] : [];
$correction = $corrections->get($month);
if ($correction) {
$before = array_replace($before, $correction->sebelum ?? []);
}
$result[$month] = ['p1_lama' => $before, 'p1_baru' => [
'jafung' => $record->nama_jabatan_fungsional ?: '-',
'grade_jafung' => $record->grade_jabatan_fungsional,
'jtt' => $record->nama_jabatan_tugas_tambahan ?: '-',
'grade_jtt' => $record->grade_jabatan_tugas_tambahan,
'golongan' => $record->golongan,
'status_pegawai' => $record->status_pegawai,
]];
}
return $result;
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Services\P1Dev;
use Closure;
use Illuminate\Support\Facades\Cache;
class P1DataCache
{
public function key(string $kind, int|string $year, int|string $month, mixed $unit, string $employeeType): string
{
$unitKey = $unit === null || $unit === '' ? 'all' : (string) ((int) $unit === 0 ? 99 : (int) $unit);
return 'p1_snapshot_v1:'.(int) $year.':'.(int) $month.':'.$unitKey.':'.$kind.':'.$employeeType;
}
public function remember(string $kind, int|string $year, int|string $month, mixed $unit, string $employeeType, Closure $load): array
{
return Cache::rememberForever($this->key($kind, $year, $month, $unit, $employeeType), $load);
}
public function forget(int|string $year, int|string $month, mixed $unit): void
{
foreach (['', 'dosen', 'tendik', 'jtt', 'jtt-univ'] as $type) {
foreach (['main', 'selisih', 'perbandingan'] as $kind) {
Cache::forget($this->key($kind, $year, $month, $unit, $type));
}
}
}
public function refresh(int|string $year, int|string $month, mixed $unit, string $employeeType, Closure $main, Closure $selisih): void
{
// Keep the previous snapshot intact if an upstream request fails.
$mainData = $main();
$selisihData = $selisih();
$this->forget($year, $month, $unit);
Cache::forever($this->key('main', $year, $month, $unit, $employeeType), $mainData);
Cache::forever($this->key('selisih', $year, $month, $unit, $employeeType), $selisihData);
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Services\P1Dev;
class P1DawaiPaymentComparison
{
public static function reference(?array $dawai, array $local): ?array
{
if ($dawai === null) {
return null;
}
// Use the newest payment ID regardless of whether older amounts match locally.
$latest = null;
foreach ($dawai['riwayat_pembayaran'] ?? [] as $payment) {
if ($latest === null || (int) ($payment['id'] ?? 0) > (int) ($latest['id'] ?? 0)) {
$latest = $payment;
}
}
return $latest ?? $dawai;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Services\P1Dev;
use App\Models\Rekapitulasi\P1Dev as P1;
use Illuminate\Validation\ValidationException;
class P1MarkPayment
{
public static function validateDifference(bool $hasDifference, int $year, int $month, bool $acknowledged): void
{
if (! $hasDifference) {
return;
}
if (! $acknowledged) {
throw ValidationException::withMessages(['acknowledge_difference' => 'Centang peringatan selisih untuk menggunakan nominal pembayaran dari Excel.']);
}
}
public function mark(array $ids, int $year, int $month, array $upload, ?int $unit, bool $acknowledged = false): int
{
if ((int) ($upload['meta']['tahun'] ?? 0) !== $year || (int) ($upload['meta']['bulan'] ?? 0) !== $month) {
throw ValidationException::withMessages(['file' => 'Unggah Excel pembayaran untuk tahun dan bulan yang dipilih.']);
}
return (new P1)->getConnection()->transaction(function () use ($ids, $year, $month, $upload, $unit, $acknowledged) {
$rows = P1::whereIn('id', $ids)->where('tahun', $year)->where('bulan', $month)
->when($unit, fn ($q) => $q->where('id_unit_kerja', $unit))->lockForUpdate()->get();
if ($rows->count() !== count($ids)) {
throw ValidationException::withMessages(['ids' => 'Ada baris di luar periode/unit yang dipilih atau sudah dihapus. Muat ulang tabel.']);
}
foreach ($rows as $row) {
$payment = $upload['payments'][ltrim($row->nip, "'").':'.$month] ?? null;
if ($row->paid_at || ! $payment) {
throw ValidationException::withMessages(['ids' => 'Ada baris yang sudah ditandai atau tidak memiliki pembayaran di Excel. Muat ulang tabel.']);
}
foreach (['bruto', 'pajak', 'netto'] as $field) {
if (! isset($payment[$field]) || ! is_numeric($payment[$field]) || ! is_finite((float) $payment[$field])) {
throw ValidationException::withMessages(['file' => 'Nominal pembayaran Excel tidak valid. Unggah ulang file.']);
}
}
if (abs((float) $payment['bruto'] - (float) $payment['pajak'] - (float) $payment['netto']) > 0.01) {
throw ValidationException::withMessages(['file' => 'Bruto, pajak, dan netto pembayaran tidak konsisten.']);
}
$review = (new P1PaymentReview)->compare([
'bruto' => (float) $row->gaji_yang_dibayarkan,
'pajak' => (float) $row->pph21,
'netto' => (float) $row->gaji_bersih,
], $payment);
self::validateDifference($review['needs_review'], $year, $month, $acknowledged);
}
foreach ($rows as $row) {
$payment = $upload['payments'][ltrim($row->nip, "'").':'.$month];
$row->update([
'paid_at' => now(),
'gaji_yang_dibayarkan_final' => $payment['bruto'],
'pph_21_final' => $payment['pajak'],
'gaji_bersih_final' => $payment['netto'],
]);
}
return $rows->count();
});
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Services\P1Dev;
use App\Models\Rekapitulasi\P1Dev;
use Carbon\Carbon;
class P1MonthlyDifferences
{
public function summarize(int $year, mixed $unit = null, string $employeeType = '', bool $includePppk2025 = false): array
{
$end = $year < now()->year ? 12 : ($year === now()->year ? now()->month : 0);
$records = P1Dev::where('tahun', $year)->whereBetween('bulan', [1, $end])
->when($unit !== null && $unit !== '', fn ($query) => $query->where('id_unit_kerja', $unit))
->when($employeeType !== '', fn ($query) => $query->whereRaw('LOWER(jenis_pegawai) = ?', [strtolower($employeeType)]))
->when(! $includePppk2025, fn ($query) => $query->where('nip', 'not like', '%202521%'))
->toBase()->get(['nip', 'bulan', 'paid_at', 'gaji_yang_dibayarkan', 'pph21', 'gaji_bersih', 'gaji_yang_dibayarkan_final', 'pph_21_final', 'gaji_bersih_final'])
->groupBy('bulan');
$store = new P1PaymentUploadStore;
$reviewer = new P1PaymentReview;
$result = [];
for ($month = 1; $month <= $end; $month++) {
$upload = $store->get($year, $month);
$snapshots = $store->snapshots($year, $month);
$row = ['bulan' => $month, 'label' => Carbon::create($year, $month, 1)->locale('id')->translatedFormat('F'),
'sudah' => ['kekurangan' => 0.0, 'kelebihan' => 0.0, 'jumlah' => 0],
'belum' => ['kekurangan' => 0.0, 'kelebihan' => 0.0, 'jumlah' => 0],
'tidak_diketahui' => 0, 'dibandingkan' => 0];
foreach ($records->get($month, collect()) as $record) {
// Zero-entitlement records without an actual payment are not payment candidates.
if ((float) $record->gaji_yang_dibayarkan == 0 && empty($record->paid_at) && ! isset($upload['payments'][ltrim((string) $record->nip, "'").':'.$month])) { continue; }
$payment = $upload['payments'][ltrim((string) $record->nip, "'").':'.$month] ?? null;
$comparison = $reviewer->forRecord($record, $payment, $snapshots);
if (! $comparison['known']) { $row['tidak_diketahui']++; continue; }
$row['dibandingkan']++;
$status = ! empty($record->paid_at) ? 'sudah' : 'belum';
$gap = $comparison['review']['difference']['netto'];
$row[$status]['kekurangan'] = round($row[$status]['kekurangan'] + max(0, $gap), 2);
$row[$status]['kelebihan'] = round($row[$status]['kelebihan'] + max(0, -$gap), 2);
if (abs($gap) >= 0.01) { $row[$status]['jumlah']++; }
}
$result[] = $row;
}
return $result;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Services\P1Dev;
class P1PaymentBalance
{
private array $monthLabels = [];
public function calculate(iterable $records, array $payments, int $month, array $changeHistory = []): array
{
$entries = [];
$changesByPeriod = [];
foreach ($changeHistory as $change) {
$changesByPeriod[(int) ($change['tahun'] ?? 0).':'.(int) ($change['bulan'] ?? 0)] = $change;
}
$totals = ['bruto' => 0.0, 'pajak' => 0.0, 'netto' => 0.0];
foreach ($records as $record) {
if ((int) $record->bulan > $month) {
continue;
}
$payment = $payments[ltrim((string) $record->nip, "'").':'.(int) $record->bulan] ?? null;
// Missing Excel months are unknown, never assume that nothing was paid.
if ($payment === null) {
continue;
}
$current = ['bruto' => (float) $record->gaji_yang_dibayarkan, 'pajak' => (float) $record->pph21, 'netto' => (float) $record->gaji_bersih];
$delta = [];
foreach ($totals as $field => $value) {
$delta[$field] = round($current[$field] - (float) $payment[$field], 2);
$totals[$field] = round($value + $delta[$field], 2);
}
$direction = $delta['bruto'] ?: ($delta['netto'] ?: -$delta['pajak']);
$period = (int) $record->tahun.':'.(int) $record->bulan;
$change = $changesByPeriod[$period] ?? [];
$monthLabel = $this->monthLabels[$period] ??= \Carbon\Carbon::create($record->tahun, $record->bulan, 1)
->locale('id')->translatedFormat('F Y');
$entries[] = [
'tahun' => (int) $record->tahun, 'bulan' => (int) $record->bulan,
'nama_bulan' => $monthLabel,
'status' => $direction > 0 ? 'kekurangan' : ($direction < 0 ? 'kelebihan' : ''),
'selisih_bruto' => $delta['bruto'], 'selisih_pajak' => $delta['pajak'], 'selisih_netto' => $delta['netto'],
'saldo' => $totals,
// Excel supplies amounts, while DAWAI/local corrections supply job/status history.
'p1_lama' => array_replace($change['p1_lama'] ?? [], $payment),
'p1_baru' => array_replace($change['p1_baru'] ?? [], $current),
];
}
return ['totals' => $totals, 'entries' => $entries];
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Services\P1Dev;
class P1PaymentReview
{
public function forRecord(object $record, ?array $uploaded, array $snapshots = []): array
{
$calculated = ['bruto' => (float) $record->gaji_yang_dibayarkan, 'pajak' => (float) $record->pph21, 'netto' => (float) $record->gaji_bersih];
$paid = ! empty($record->paid_at);
$payment = $uploaded;
$source = 'Excel bulan ini';
$notice = null;
if ($paid) {
if ($record->gaji_yang_dibayarkan_final === null || $record->pph_21_final === null || $record->gaji_bersih_final === null) {
return ['review' => null, 'known' => false, 'source' => 'Database', 'notice' => 'Sudah ditandai dibayar, tetapi nominal final belum tersedia.'];
}
$actual = ['bruto' => (float) $record->gaji_yang_dibayarkan_final, 'pajak' => (float) $record->pph_21_final, 'netto' => (float) $record->gaji_bersih_final];
$source = 'Nominal final database';
$matches = fn ($candidate) => $candidate !== null && count(array_filter(['bruto', 'pajak', 'netto'], fn ($field) => round((float) ($candidate[$field] ?? 0), 2) !== round($actual[$field], 2))) === 0;
$payment = $matches($uploaded) ? array_replace($uploaded, $actual) : null;
if ($payment === null) {
$key = ltrim((string) $record->nip, "'").':'.(int) $record->bulan;
foreach ($snapshots as $snapshot) {
$candidate = $snapshot[$key] ?? null;
if ($matches($candidate)) { $payment = array_replace($candidate, $actual); break; }
}
$notice = 'Excel aktif berbeda atau tidak tersedia; memakai nominal final database.';
}
$payment ??= $actual;
}
if ($payment === null) {
return ['review' => null, 'known' => false, 'source' => null, 'notice' => 'Belum ada hasil pembayaran untuk dibandingkan.'];
}
$review = $this->compare($calculated, $payment);
$known = isset($payment['components']) || ! $review['needs_review'];
if (! $known) {
$notice = 'Nominal tersedia, tetapi rincian potongan/tambahan belum tersedia. Selisih belum dapat diklasifikasikan.';
}
return ['review' => $review, 'known' => $known, 'source' => $source, 'notice' => $notice];
}
public function compare(array $calculated, array $payment): array
{
$components = $payment['components'] ?? ['reguler' => array_intersect_key($payment, array_flip(['bruto', 'pajak', 'netto']))];
$difference = [];
foreach (['bruto', 'pajak', 'netto'] as $field) {
// Supplements settle this source month's entitlement. Recovery deductions
// settle earlier debt and must not create a new shortfall in this month.
$expected = (float) ($calculated[$field] ?? 0) + (float) ($components['potongan'][$field] ?? 0);
$difference[$field] = round($expected - (float) $payment[$field], 2);
}
$netDifference = $difference['netto'];
return [
'components' => $components,
'calculated' => $calculated,
'difference' => $difference,
'status' => $netDifference >= 0.01 ? 'kekurangan' : ($netDifference <= -0.01 ? 'kelebihan' : (count(array_filter($difference, fn ($amount) => abs($amount) >= 0.01)) ? 'periksa' : 'sesuai')),
'needs_review' => ! isset($components['reguler']) || count(array_filter($difference, fn ($amount) => abs($amount) >= 0.01)) > 0,
];
}
}
+208
View File
@@ -0,0 +1,208 @@
<?php
namespace App\Services\P1Dev;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
class P1PaymentUpload
{
public function parse(string $path, string $sheetName = '', ?int $selectedMonth = null, ?int $selectedYear = null): array
{
$reader = IOFactory::createReaderForFile($path);
$names = $reader->listWorksheetNames($path);
if ($sheetName === '') {
$sheetName = in_array('Pembayaran', $names, true) ? 'Pembayaran'
: (in_array('REKAP ALL '.$selectedYear, $names, true) ? 'REKAP ALL '.$selectedYear : $names[0]);
}
if (! in_array($sheetName, $names, true)) {
throw ValidationException::withMessages(['sheet' => 'Sheet tidak ditemukan dalam Excel.']);
}
$reader->setReadDataOnly(true);
$reader->setLoadSheetsOnly([$sheetName]);
$reader->setReadEmptyCells(false);
$reader->setReadFilter(new class implements IReadFilter
{
public function readCell($columnAddress, $row, $worksheetName = ''): bool
{
return $row <= 20;
}
});
$book = $reader->load($path);
try {
$sheet = $book->getSheetByName($sheetName);
$headers = [];
$headerRow = 0;
$required = ['nip', 'gaji p1 yang dibayarkan', 'pph 21', 'gaji p1 bersih'];
foreach ($sheet->getRowIterator(1, min(20, $sheet->getHighestDataRow())) as $row) {
$headers = [];
foreach ($row->getCellIterator() as $cell) {
$label = strtolower(trim(preg_replace('/\s+/', ' ', (string) $cell->getValue())));
$headers[$label] = $cell->getColumn();
}
if (! array_diff($required, array_keys($headers))) {
$headerRow = $row->getRowIndex();
break;
}
}
if (! $headerRow) {
throw ValidationException::withMessages(['file' => 'Kolom wajib: NIP, Gaji P1 yang dibayarkan, PPH 21, Gaji P1 Bersih.']);
}
$book->disconnectWorksheets();
foreach (['jabatan akademik' => 'jabatan fungsional', 'grade jabatan akademik' => 'grade jabatan fungsional'] as $source => $target) {
if (! isset($headers[$target]) && isset($headers[$source])) {
$headers[$target] = $headers[$source];
}
}
$detailColumns = ['jafung' => 'jabatan fungsional', 'grade_jafung' => 'grade jabatan fungsional',
'jtt' => 'jabatan tugas tambahan', 'grade_jtt' => 'grade jabatan tugas tambahan',
'golongan' => 'golongan', 'status_pegawai' => 'status pegawai'];
$columns = array_values(array_intersect_key($headers, array_flip([...$required, 'bulan', 'jenis pembayaran', 'komponen', 'tahun', 'keterangan', 'tanggal spm', 'no spm', ...array_values($detailColumns)])));
$worksheetInfo = null;
foreach ($reader->listWorksheetInfo($path) as $info) {
if ($info['worksheetName'] === $sheetName) {
$worksheetInfo = $info;
break;
}
}
$lastRow = (int) ($worksheetInfo['totalRows'] ?? $headerRow);
unset($sheet);
$months = array_flip(['januari', 'februari', 'maret', 'april', 'mei', 'juni', 'juli', 'agustus', 'september', 'oktober', 'november', 'desember']);
$sheetMonth = null;
if (preg_match('/\b('.implode('|', array_keys($months)).')\b/i', $sheetName, $match)) {
$sheetMonth = $months[strtolower($match[1])] + 1;
}
$defaultMonth = $sheetMonth ?? $selectedMonth;
if (! isset($headers['bulan']) && ($defaultMonth === null || $defaultMonth < 1 || $defaultMonth > 12)) {
throw ValidationException::withMessages(['file' => 'Bulan tidak ditemukan. Gunakan nama sheet Januari–Desember atau pilih bulan pembayaran.']);
}
$payments = [];
$accepted = $skipped = $duplicates = 0;
for ($chunkStart = $headerRow + 1; $chunkStart <= $lastRow; $chunkStart += 2000) {
$chunkEnd = min($chunkStart + 1999, $lastRow);
$reader->setReadFilter(new class($columns, $chunkStart, $chunkEnd) implements IReadFilter
{
public function __construct(private array $columns, private int $first, private int $last) {}
public function readCell($columnAddress, $row, $worksheetName = ''): bool
{
return $row >= $this->first && $row <= $this->last && in_array($columnAddress, $this->columns, true);
}
});
$book = $reader->load($path);
$sheet = $book->getSheetByName($sheetName);
for ($r = $chunkStart; $r <= $chunkEnd; $r++) {
$get = fn ($name) => $sheet->getCell($headers[$name].$r)->getCalculatedValue();
$nip = trim((string) $get('nip'), " \t\n\r\0\x0B'");
$monthText = isset($headers['bulan']) ? strtolower(trim((string) $get('bulan'))) : (string) $defaultMonth;
$month = $this->resolveMonth($monthText);
if (isset($headers['jenis pembayaran']) && strtoupper(trim((string) $get('jenis pembayaran'))) !== 'P1') {
$skipped++;
continue;
}
if ($nip === '' && $monthText === '') {
continue;
}
if (preg_match('/^\d{18}$/', $nip) && ($month < 1 || $month > 12)) {
throw ValidationException::withMessages(['file' => "Bulan pada baris {$r} tidak dikenali atau memuat lebih dari satu bulan."]);
}
if (isset($headers['tahun']) && $selectedYear !== null && (int) $get('tahun') !== $selectedYear && preg_match('/^\d{18}$/', $nip)) {
throw ValidationException::withMessages(['file' => "Tahun pada baris {$r} berbeda dari tahun yang dipilih."]);
}
if (! preg_match('/^\d{18}$/', $nip) || $month < 1 || $month > 12) {
$skipped++;
continue;
}
$values = [];
foreach (['bruto' => 'gaji p1 yang dibayarkan', 'pajak' => 'pph 21', 'netto' => 'gaji p1 bersih'] as $key => $column) {
$value = $get($column);
// The source leaves tax blank for untaxed payments.
if ($key === 'pajak' && ($value === null || $value === '')
&& is_numeric($get('gaji p1 yang dibayarkan')) && is_numeric($get('gaji p1 bersih'))
&& abs((float) $get('gaji p1 yang dibayarkan') - (float) $get('gaji p1 bersih')) < 0.01) {
$value = 0;
}
if (! is_numeric($value) || ! is_finite((float) $value)) {
throw ValidationException::withMessages(['file' => "Nominal {$column} tidak valid pada baris {$r}."]);
}
$values[$key] = round((float) $value, 2);
}
if (abs($values['bruto'] - $values['pajak'] - $values['netto']) > 0.01) {
throw ValidationException::withMessages(['file' => "Bruto dikurangi pajak tidak sama dengan netto pada baris {$r}."]);
}
$component = isset($headers['komponen']) ? strtolower(trim((string) $get('komponen'))) : '';
if ($component !== '' && ! in_array($component, ['reguler', 'tambahan', 'potongan'], true)) {
throw ValidationException::withMessages(['file' => "Komponen pada baris {$r} harus Reguler, Tambahan, atau Potongan."]);
}
$kind = $component !== '' ? $component : (($values['bruto'] < 0 || $values['netto'] < 0) ? 'potongan'
: (preg_match('/kekurangan|susulan|rapel/i', $monthText) ? 'tambahan' : 'reguler'));
if ($kind === 'potongan') {
foreach ($values as $field => $value) {
$values[$field] = -abs($value);
}
} elseif ($values['bruto'] < 0 || $values['pajak'] < 0 || $values['netto'] < 0) {
throw ValidationException::withMessages(['file' => "Nominal Reguler/Tambahan pada baris {$r} harus positif atau nol."]);
}
if (abs($values['bruto'] - $values['pajak'] - $values['netto']) > 0.01) {
throw ValidationException::withMessages(['file' => "Tanda bruto, pajak, dan netto potongan pada baris {$r} tidak konsisten."]);
}
$key = $nip.':'.$month;
if (isset($payments[$key])) {
$duplicates++;
}
foreach ($values as $field => $value) {
$payments[$key][$field] = round(($payments[$key][$field] ?? 0) + $value, 2);
$payments[$key]['components'][$kind][$field] = round(($payments[$key]['components'][$kind][$field] ?? 0) + $value, 2);
}
$payments[$key]['sources'][] = array_merge($values, [
'row' => $r, 'kind' => $kind, 'bulan' => $monthText,
'keterangan' => isset($headers['keterangan']) ? (string) $get('keterangan') : null,
'tanggal_spm' => isset($headers['tanggal spm']) ? (string) $get('tanggal spm') : null,
'no_spm' => isset($headers['no spm']) ? (string) $get('no spm') : null,
]);
foreach ($detailColumns as $field => $column) {
if (isset($headers[$column])) {
$value = trim((string) $get($column));
if ($value !== '' && ($kind === 'reguler' || ! isset($payments[$key][$field]))) {
$payments[$key][$field] = $value;
}
}
}
$accepted++;
}
$book->disconnectWorksheets();
unset($sheet);
gc_collect_cycles();
}
if (! $accepted) {
throw ValidationException::withMessages(['file' => 'Tidak ditemukan pembayaran P1 dengan NIP 18 digit dan bulan Januari–Desember.']);
}
return compact('payments', 'accepted', 'skipped', 'duplicates', 'sheetName');
} finally {
$book->disconnectWorksheets();
}
}
private function resolveMonth(string $text): int
{
if (ctype_digit($text)) {
return (int) $text;
}
$names = [1 => 'jan(?:uari)?', 2 => 'feb(?:ruari)?', 3 => 'mar(?:et)?',
4 => 'apr(?:il)?', 5 => 'mei', 6 => 'jun(?:i)?', 7 => 'jul(?:i)?',
8 => '(?:agu(?:stus)?|agt)', 9 => 'sep(?:tember|t)?', 10 => 'okt(?:ober)?',
11 => 'nov(?:ember)?', 12 => 'des(?:ember)?'];
$found = [];
foreach ($names as $month => $pattern) {
if (preg_match('/\b'.$pattern.'\b/i', $text)) {
$found[] = $month;
}
}
return count($found) === 1 ? $found[0] : 0;
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Services\P1Dev;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class P1PaymentUploadStore
{
private function directory(int $year, int $month): string
{
if ($year < 2025 || $year > 2100 || $month < 1 || $month > 12) {
throw ValidationException::withMessages(['bulan' => 'Pilih tahun dan bulan pembayaran yang valid.']);
}
return sprintf('p1-dev/payments/%04d/%02d', $year, $month);
}
public function put(int $year, int $month, UploadedFile $file, array $upload): array
{
$directory = $this->directory($year, $month);
$payments = array_filter($upload['payments'] ?? [], fn ($key) => (int) substr($key, strrpos($key, ':') + 1) === $month, ARRAY_FILTER_USE_KEY);
if (! $payments) {
throw ValidationException::withMessages(['file' => 'Tidak ditemukan pembayaran untuk bulan yang dipilih. Periksa kolom Bulan atau nama sheet.']);
}
$id = (string) Str::uuid();
$path = $file->storeAs($directory, $id.'.'.$file->extension(), 'local');
if (! $path) {
throw new \RuntimeException('File pembayaran tidak dapat disimpan.');
}
$upload['meta'] = array_merge($upload['meta'], [
'tahun' => $year, 'bulan' => $month, 'upload_id' => $id,
'filename' => $file->getClientOriginalName(), 'path' => $path,
'uploaded_at' => now()->toIso8601String(),
]);
$upload['payments'] = $payments;
$upload['meta']['pegawai'] = count($payments);
$upload['meta']['totals'] = ['bruto' => 0.0, 'pajak' => 0.0, 'netto' => 0.0, 'tambahan' => 0.0, 'potongan' => 0.0];
foreach ($payments as $payment) {
foreach (['bruto', 'pajak', 'netto'] as $field) {
$upload['meta']['totals'][$field] = round($upload['meta']['totals'][$field] + (float) ($payment[$field] ?? 0), 2);
}
$upload['meta']['totals']['tambahan'] += (float) ($payment['components']['tambahan']['netto'] ?? 0);
$upload['meta']['totals']['potongan'] += abs((float) ($payment['components']['potongan']['netto'] ?? 0));
}
try {
// Replace the active period atomically; old Excel files remain available in storage.
$json = json_encode($upload, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION);
File::replace(Storage::disk('local')->path($directory.'/'.$id.'.json'), $json);
File::replace(Storage::disk('local')->path($directory.'/current.json'), $json);
} catch (\Throwable $e) {
Storage::disk('local')->delete($path);
throw $e;
}
return $upload;
}
public function period(int $year, int $month): array
{
$path = $this->directory($year, $month).'/current.json';
$disk = Storage::disk('local');
if (! $disk->exists($path)) {
return [];
}
return json_decode($disk->get($path), true, 512, JSON_THROW_ON_ERROR);
}
public function get(int $year, int $month): array
{
return $this->period($year, $month) ?: ['meta' => [], 'payments' => []];
}
public function snapshots(int $year, int $month): array
{
$snapshots = [];
foreach (Storage::disk('local')->files($this->directory($year, $month)) as $path) {
if (str_ends_with($path, '.json') && basename($path) !== 'current.json') {
$snapshot = json_decode(Storage::disk('local')->get($path), true, 512, JSON_THROW_ON_ERROR);
$snapshots[] = $snapshot['payments'] ?? [];
}
}
return $snapshots;
}
public function forget(int $year, int $month): void
{
$path = $this->directory($year, $month).'/current.json';
if (Storage::disk('local')->exists($path) && ! Storage::disk('local')->delete($path)) {
throw new \RuntimeException('Pembanding pembayaran tidak dapat dihapus.');
}
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
namespace App\Services\P1Dev;
use App\Http\Controllers\Perhitungan\Remunerasi\P1DevController as P1Controller;
use App\Models\Rekapitulasi\P1Dev as P1;
use App\Models\Rekapitulasi\P1Penyesuaian;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class P1TmtService
{
public function effectiveMonth(string $tmt): CarbonImmutable
{
$date = CarbonImmutable::parse($tmt, 'Asia/Jakarta');
return $date->day <= 10 ? $date->startOfMonth() : $date->startOfMonth()->addMonth();
}
public function snapshot(P1 $record): array
{
$harga = max((float) $record->gaji_jabatan_fungsional, (float) $record->gaji_jabatan_tugas_tambahan);
return [
'jafung' => $record->nama_jabatan_fungsional ?: '-',
'jtt' => $record->nama_jabatan_tugas_tambahan ?: '-',
'grade_jafung' => $record->grade_jabatan_fungsional,
'grade_jtt' => $record->grade_jabatan_tugas_tambahan,
'golongan' => $record->golongan,
'is_cpns' => $harga > 0 && abs((float) $record->gaji_yang_dibayarkan - 2 * $harga * 0.8) < 1,
'bruto' => (float) $record->gaji_yang_dibayarkan,
'pajak' => (float) $record->pph21,
'netto' => (float) $record->gaji_bersih,
];
}
/** Null TMT leaves that attribute untouched. All supplied ranges end today. */
public function update(P1 $pegawai, array $tmt, array $attributes, CarbonImmutable $today): array
{
$starts = collect($tmt)->filter()->map(fn ($date) => $this->effectiveMonth($date));
if ($starts->isEmpty()) {
throw ValidationException::withMessages(['tmt' => 'Isi minimal satu TMT untuk menerapkan perubahan.']);
}
foreach ($starts as $field => $date) {
if ($date->greaterThan($today->startOfMonth())) {
throw ValidationException::withMessages([$field.'_tmt' => 'Bulan efektif TMT melewati bulan sekarang.']);
}
}
return DB::transaction(function () use ($pegawai, $tmt, $attributes, $today, $starts) {
$first = $starts->sortBy(fn ($date) => $date->timestamp)->first();
$records = P1::where('nip', $pegawai->nip)
->whereRaw('(tahun * 100 + bulan) >= ?', [$first->year * 100 + $first->month])
->whereRaw('(tahun * 100 + bulan) <= ?', [$today->year * 100 + $today->month])
->orderBy('tahun')->orderBy('bulan')->lockForUpdate()->get();
// Never silently skip a missing month in the requested calculation.
$periods = $records->map(fn ($r) => sprintf('%04d-%02d', $r->tahun, $r->bulan));
for ($month = $first; $month->lessThanOrEqualTo($today->startOfMonth()); $month = $month->addMonth()) {
if (! $periods->contains($month->format('Y-m'))) {
throw ValidationException::withMessages(['tmt' => 'Rekap P1 '.$month->translatedFormat('F Y').' belum tersedia untuk pegawai ini.']);
}
}
$updated = [];
foreach ($records as $record) {
$month = CarbonImmutable::create((int) $record->tahun, (int) $record->bulan, 1, 0, 0, 0, 'Asia/Jakarta');
$before = $this->snapshot($record);
$cpns = $before['is_cpns'];
foreach ($starts as $field => $start) {
if ($month->lessThan($start)) {
continue;
}
if ($field === 'cpns') {
$cpns = $attributes['cpns'];
} else {
$record->fill($attributes[$field]);
}
}
$calc = P1Controller::calculateP1($record->gaji_jabatan_fungsional, $record->gaji_jabatan_tugas_tambahan, $record->golongan, $cpns);
$record->fill(['gaji_yang_dibayarkan' => $calc['bruto'], 'pph21' => $calc['pajak'], 'gaji_bersih' => $calc['netto']]);
if (! $record->isDirty()) {
continue;
}
$key = ['nip' => $record->nip, 'tahun' => $record->tahun, 'bulan' => $record->bulan,
'tahun_pembayaran' => $today->year, 'bulan_pembayaran' => $today->month];
$adjustment = P1Penyesuaian::firstOrNew($key);
// Keep the original baseline across repeated saves in this payment month.
if (! $adjustment->exists) {
$adjustment->sebelum = $before;
}
$adjustment->sesudah = $this->snapshot($record);
$adjustment->tmt = array_filter(array_merge($adjustment->tmt ?? [], array_filter($tmt)));
$adjustment->tst = $today->toDateString();
$adjustment->save();
$record->save();
$updated[] = ['tahun' => $record->tahun, 'bulan' => $record->bulan, 'unit' => $record->id_unit_kerja,
'unit_pembayaran' => $record->id_unit_pembayaran];
}
return $updated;
});
}
/** Combine local corrections with Dawai by source month, never add the same correction twice. */
public function mergeAdjustments(array $dawai, iterable $local): array
{
$entries = collect($dawai)->keyBy(fn ($r) => $r['tahun'].'-'.$r['bulan']);
foreach ($local as $adjustment) {
$key = $adjustment->tahun.'-'.$adjustment->bulan;
$existing = $entries->get($key);
// If Dawai already has an adjustment for this month, retain its paid baseline.
$before = $existing['p1_lama'] ?? $adjustment->sebelum;
$after = $adjustment->sesudah;
$bruto = round($after['bruto'] - $before['bruto'], 2);
$netto = round($after['netto'] - $before['netto'], 2);
$status = $bruto != 0 ? ($bruto > 0 ? 'kekurangan' : 'kelebihan') : ($netto > 0 ? 'kekurangan' : ($netto < 0 ? 'kelebihan' : ''));
$entries->put($key, [
'tahun' => (int) $adjustment->tahun, 'bulan' => (int) $adjustment->bulan,
'nama_bulan' => CarbonImmutable::create($adjustment->tahun, $adjustment->bulan, 1)->locale('id')->translatedFormat('F Y'),
'status' => $status, 'status_label' => ucfirst($status), 'sumber' => 'lokal',
'selisih_bruto' => $bruto, 'selisih_pajak' => round(($after['pajak'] - $before['pajak']), 2),
'selisih_netto' => $netto, 'p1_lama' => $before, 'p1_baru' => $after,
]);
}
return $entries->sortBy(fn ($r) => $r['tahun'] * 100 + $r['bulan'])->values()->all();
}
}