209 lines
12 KiB
PHP
209 lines
12 KiB
PHP
<?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;
|
||
}
|
||
}
|