[Operator] Perbaikan Laman Portal -> Konsultasi

This commit is contained in:
Ariyutta
2026-11-11 09:28:34 +07:00
parent 52d49cdb41
commit d6425a601d
19 changed files with 1134 additions and 301 deletions
@@ -0,0 +1,215 @@
<?php
namespace App\Support\Legacy\Concerns;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
/**
* Logika isian biodata yang dipakai bersama StudentBiodata dan EmployeeBiodata: bentuk baku nilai kolom, nilai isian dan
* teks tampil satu bagian, serta validasi yang hanya memeriksa isian yang berubah (data lama boleh tidak seragam).
*
* Isian bagian: name (kunci JSON dan kolom), label, type (text|textarea|email|date|number|select), max, min, lookup (nama
* pilihan untuk select), required, wide, alnum, digits, notnull (kolom teks NOT NULL: kosong ditulis ''), zero (kode 0 adalah
* nilai nyata, bukan "tidak diisi"), placeholder, affix (front|back: gelar depan/belakang; di formulir ditulis tanpa koma dan
* spasi pemisah, DB lama menyimpannya sebagai "Dr. " dan ", M.Pd" sehingga pemisah ditambahkan saat menulis).
*/
trait BiodataFields
{
/**
* Pilihan select (kode => label) menurut nama lookup.
*
* @return array<string, array<int, string>>
*/
abstract public function lookups(): array;
/**
* Nilai kolom dalam bentuk baku agar dua nilai bisa dibandingkan: teks dipangkas (kosong = null), tanggal Y-m-d,
* angka integer, pilihan integer (kosong = 0 pada pilihan yang punya kode 0, selain itu null).
*
* @param array<string, mixed> $field
* @param array<string, array<int, string>> $lookups
*/
protected function normalize(array $field, mixed $value, array $lookups): string|int|null
{
$type = $field['type'] ?? 'text';
$text = is_scalar($value) ? trim((string) $value) : '';
// Pilihan tanpa kode 0: nilai kosong atau 0 di DB berarti belum diisi (null).
$none = $type === 'select' && ! isset($lookups[$field['lookup']][0]);
return match ($type) {
'select' => $text === '' || ($none && (int) $text === 0) ? ($none ? null : 0) : (int) $text,
'number' => $text === '' ? null : (int) $text,
'date' => $text === '' ? null : substr($text, 0, 10),
default => ($text = self::stripAffix($field, $text)) === '' ? null : $text,
};
}
/** Buang pemisah gelar (koma dan spasi di depan gelar belakang, spasi pada gelar depan) agar nilai konsisten. */
private static function stripAffix(array $field, string $text): string
{
return match ($field['affix'] ?? null) {
'back' => trim(ltrim($text, " ,\t")),
'front' => trim($text),
default => $text,
};
}
/**
* Nilai siap tulis ke kolom: gelar belakang diberi awalan ", " dan gelar depan spasi penutup (konvensi DB lama);
* kolom teks NOT NULL yang kosong ditulis ''.
*
* @param array<string, mixed> $field
*/
private function stored(array $field, string|int|null $value): string|int|null
{
if ($value === null) {
return ($field['notnull'] ?? false) ? '' : null;
}
return match ($field['affix'] ?? null) {
'back' => ', '.$value,
'front' => $value.' ',
default => $value,
};
}
/**
* Nilai isian (untuk formulir) dan teks tampil satu bagian.
*
* @param array<string, mixed> $section
* @param array<string, array<int, string>> $lookups
* @return array{fields: list<array<string, mixed>>, values: array<string, mixed>, display: array<string, string>}
*/
protected function present(array $section, object $row, array $lookups): array
{
$fields = [];
$values = [];
$display = [];
foreach ($section['fields'] as $field) {
$name = $field['name'];
$value = $this->normalize($field, $row->{$name} ?? null, $lookups);
if (($field['type'] ?? '') === 'select') {
$options = $lookups[$field['lookup']];
if ($value === null) {
// Kolom boleh kosong dan pilihannya tidak punya kode 0: tampil pilihan kosong.
$field['blank'] = true;
$values[$name] = '';
$display[$name] = '–';
} else {
// Kode yang tidak ada di tabel referensi tetap tampil dan bisa dipertahankan.
$options += isset($options[$value]) ? [] : [$value => 'Kode '.$value];
$values[$name] = $value;
$display[$name] = $value === 0 && ! ($field['zero'] ?? false) ? '–' : $options[$value];
}
$field['options'] = $options;
} else {
$values[$name] = $value ?? '';
$display[$name] = match (true) {
$value === null => '–',
($field['type'] ?? '') === 'date' => Carbon::parse($value)->locale('id')->isoFormat('D MMMM YYYY'),
default => (string) $value,
};
}
$fields[] = $field;
}
return ['fields' => $fields, 'values' => $values, 'display' => $display];
}
/**
* Kolom yang berubah dari satu bagian (kolom => nilai baru siap tulis). Isian yang tidak dikirim dilewati.
*
* @param list<array<string, mixed>> $fields
* @param array<string, mixed> $input
* @param array<string, array<int, string>> $lookups
* @return array<string, string|int|null>
*/
protected function changes(array $fields, object $row, array $input, array $lookups): array
{
$changes = [];
foreach ($fields as $field) {
$name = $field['name'];
if (! array_key_exists($name, $input)) {
continue;
}
$new = $this->normalize($field, $input[$name], $lookups);
if ($new !== $this->normalize($field, $row->{$name} ?? null, $lookups)) {
$changes[$name] = $this->stored($field, $new);
}
}
return $changes;
}
/**
* Periksa isian satu bagian. Isian yang nilainya sama dengan yang tersimpan (dan tidak kosong) tidak diperiksa bentuknya
* dan tidak ikut dikembalikan; isian wajib yang kosong selalu diperiksa.
*
* @param list<array<string, mixed>> $fields
* @param array<string, mixed> $input
* @param array<string, list<mixed>> $extraRules aturan tambahan per isian
* @return array<string, mixed>
*
* @throws ValidationException
*/
protected function validateFields(array $fields, object $row, array $input, array $extraRules = []): array
{
$lookups = $this->lookups();
$rules = $this->rulesFor($fields, $lookups);
foreach ($fields as $field) {
$name = $field['name'];
if (array_key_exists($name, $input)) {
$new = $this->normalize($field, $input[$name], $lookups);
if ($new !== null && $new === $this->normalize($field, $row->{$name} ?? null, $lookups)) {
unset($rules[$name]);
continue;
}
}
if (isset($extraRules[$name])) {
$rules[$name] = array_merge($rules[$name], $extraRules[$name]);
}
}
$attributes = collect($fields)->mapWithKeys(fn (array $f): array => [$f['name'] => mb_strtolower($f['label'])])->all();
return Validator::make($input, $rules, [], $attributes)->validate();
}
/**
* @param list<array<string, mixed>> $fields
* @param array<string, array<int, string>> $lookups
* @return array<string, list<string>>
*/
private function rulesFor(array $fields, array $lookups): array
{
$rules = [];
foreach ($fields as $field) {
$type = $field['type'] ?? 'text';
$base = ($field['required'] ?? false) ? ['required'] : ['nullable'];
$rules[$field['name']] = array_merge($base, match (true) {
$type === 'select' => ['integer', 'in:'.implode(',', array_keys($lookups[$field['lookup']]))],
$type === 'number' => ['integer', 'min:'.($field['min'] ?? 0), 'max:'.($field['max'] ?? 99)],
$type === 'date' => ['date_format:Y-m-d', 'before_or_equal:today'],
$type === 'email' => ['string', 'email', 'max:'.$field['max']],
default => array_values(array_filter([
'string',
'max:'.$field['max'],
($field['alnum'] ?? false) ? 'regex:/^[0-9A-Za-z]+$/' : null,
($field['digits'] ?? false) ? 'regex:/^[0-9]{4}$/' : null,
])),
});
}
return $rules;
}
}
+308
View File
@@ -0,0 +1,308 @@
<?php
namespace App\Support\Legacy;
use App\Support\Legacy\Concerns\BiodataFields;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
/**
* Biodata lengkap pegawai DB lama (t_pegawai, dan t_dosen untuk dosen) untuk halaman detail operator: data pribadi, kontak
* dan alamat, kepegawaian, pendidikan dan rekening, serta data dosen. Dibaca dan ditulis per bagian dalam cakupan yang sama
* dengan daftar (EmployeeDirectory::scoped). Hanya kolom yang nilainya berubah yang ditulis. Akun login tidak disentuh dan
* jenis pegawai (dosen atau staf) tidak diubah di sini.
*/
final class EmployeeBiodata
{
use BiodataFields;
/** Bagian yang ditulis ke t_dosen (bukan t_pegawai); hanya ada untuk pegawai yang punya baris t_dosen. */
private const string DOSEN = 'dosen';
private const array ACTIVE = [1 => 'Aktif', 0 => 'Tidak aktif'];
/** @var array<string, array<int, string>>|null */
private ?array $lookups = null;
/** @var list<int> */
private array $prodi = [];
public function __construct(private readonly EmployeeDirectory $directory) {}
/**
* Bagian halaman; lihat BiodataFields untuk arti isian.
*
* @return array<string, array{title: string, icon: string, description: string, fields: list<array<string, mixed>>}>
*/
public static function sections(): array
{
return [
'pribadi' => [
'title' => 'Data pribadi',
'icon' => 'user',
'description' => 'Nama, gelar, dan identitas diri.',
'fields' => [
['name' => 'nama', 'label' => 'Nama', 'type' => 'text', 'max' => 50, 'required' => true],
['name' => 'gelardepan', 'label' => 'Gelar depan', 'type' => 'text', 'max' => 19, 'notnull' => true, 'affix' => 'front', 'placeholder' => 'Contoh: Dr. atau Prof. Dr.'],
['name' => 'gelarbelakang', 'label' => 'Gelar belakang', 'type' => 'text', 'max' => 23, 'notnull' => true, 'affix' => 'back', 'placeholder' => 'Contoh: S.Kom., M.T. (tanpa koma di depan)'],
['name' => 'kelamin', 'label' => 'Jenis kelamin', 'type' => 'select', 'lookup' => 'kelamin'],
['name' => 'tempatlahir', 'label' => 'Tempat lahir', 'type' => 'text', 'max' => 60],
['name' => 'tgllahir', 'label' => 'Tanggal lahir', 'type' => 'date'],
['name' => 'agama', 'label' => 'Agama', 'type' => 'select', 'lookup' => 'agama'],
['name' => 'no_id', 'label' => 'NIK', 'type' => 'text', 'max' => 16, 'alnum' => true],
['name' => 'jmlistri', 'label' => 'Jumlah istri atau suami', 'type' => 'number', 'min' => 0, 'max' => 20, 'required' => true],
['name' => 'jmlanak', 'label' => 'Jumlah anak', 'type' => 'number', 'min' => 0, 'max' => 30, 'required' => true],
],
],
'kontak' => [
'title' => 'Kontak dan alamat',
'icon' => 'map-pin',
'description' => 'Alamat tinggal dan cara menghubungi.',
'fields' => [
['name' => 'hp', 'label' => 'No. HP', 'type' => 'text', 'max' => 20],
['name' => 'telepon', 'label' => 'Telepon', 'type' => 'text', 'max' => 15],
['name' => 'email', 'label' => 'Email', 'type' => 'email', 'max' => 125],
['name' => 'kodepos', 'label' => 'Kode pos', 'type' => 'text', 'max' => 5, 'alnum' => true],
['name' => 'alamat', 'label' => 'Alamat', 'type' => 'textarea', 'max' => 255, 'wide' => true],
],
],
'kepegawaian' => [
'title' => 'Kepegawaian',
'icon' => 'briefcase',
'description' => 'Nomor induk, status, dan surat keputusan.',
'fields' => [
['name' => 'nip', 'label' => 'NIP', 'type' => 'text', 'max' => 20, 'required' => true],
['name' => 'nipnasional', 'label' => 'NIP nasional', 'type' => 'text', 'max' => 30],
['name' => 'nidn', 'label' => 'NIDN', 'type' => 'text', 'max' => 25],
['name' => 'idstatuspegawai', 'label' => 'Status kepegawaian', 'type' => 'select', 'lookup' => 'status'],
['name' => 'statusaktif', 'label' => 'Status aktif', 'type' => 'select', 'lookup' => 'aktif', 'required' => true, 'zero' => true],
['name' => 'skpegawai', 'label' => 'No. SK pegawai', 'type' => 'text', 'max' => 30],
['name' => 'tglskpegawai', 'label' => 'Tanggal SK pegawai', 'type' => 'date'],
['name' => 'npwp', 'label' => 'NPWP', 'type' => 'text', 'max' => 20],
['name' => 'no_bpjs', 'label' => 'No. BPJS', 'type' => 'text', 'max' => 20],
],
],
'pendidikan' => [
'title' => 'Pendidikan dan bank',
'icon' => 'academic-cap',
'description' => 'Pendidikan terakhir dan rekening gaji.',
'fields' => [
['name' => 'pendidikanterakhir', 'label' => 'Pendidikan terakhir', 'type' => 'select', 'lookup' => 'pendidikan'],
['name' => 'idbank', 'label' => 'Bank', 'type' => 'select', 'lookup' => 'bank'],
['name' => 'norekening', 'label' => 'No. rekening', 'type' => 'text', 'max' => 30],
],
],
self::DOSEN => [
'title' => 'Data dosen',
'icon' => 'identification',
'description' => 'Home base, pangkat, dan jabatan fungsional.',
'fields' => [
['name' => 'idprogdi', 'label' => 'Home base (program studi)', 'type' => 'select', 'lookup' => 'prodi', 'required' => true],
['name' => 'idpangkatdosen', 'label' => 'Pangkat', 'type' => 'select', 'lookup' => 'pangkat', 'required' => true],
['name' => 'idjabatanfungsional', 'label' => 'Jabatan fungsional', 'type' => 'select', 'lookup' => 'jabfung'],
['name' => 'nomerpa', 'label' => 'Nomor PA', 'type' => 'text', 'max' => 10],
],
],
];
}
/** @return list<string> */
public static function sectionKeys(): array
{
return array_keys(self::sections());
}
private function db(): ConnectionInterface
{
return DB::connection('untan');
}
/** Pilihan home base dibatasi pada program studi akun, jadi pilihan bergantung pada cakupan. */
private function scope(array $prodi): void
{
if ($this->prodi !== $prodi) {
$this->prodi = $prodi;
$this->lookups = null;
}
}
/**
* Pilihan select (kode => label). Kode 0 berarti "Tidak diisi" pada kolom yang memakainya di DB asli.
*
* @return array<string, array<int, string>>
*/
public function lookups(): array
{
if ($this->lookups !== null) {
return $this->lookups;
}
$zero = fn (array $options): array => [0 => 'Tidak diisi'] + array_diff_key($options, [0 => true]);
$names = fn (string $table, string $key, string $label, bool $upper = false): array => $this->db()->table($table)->orderBy($key)->pluck($label, $key)
->mapWithKeys(fn (?string $name, int|string $id): array => [(int) $id => $upper ? ucfirst(trim((string) $name)) : trim((string) $name)])->all();
// Pendidikan terakhir pegawai memakai skala id_simalum (1 SMP, 2 SMA, 3 D1 ... 7 S1, 8 S2, 9 S3), bukan idtingkat.
$education = $this->db()->table('t_tingkat_pendidikan')->where('id_simalum', '>', 0)->orderBy('id_simalum')->pluck('tingkatpendidikan', 'id_simalum')
->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => trim($name)])->all();
return $this->lookups = [
'kelamin' => EmployeeRecords::GENDER,
'agama' => $zero($names('xs_agama', 'idagama', 'agama')),
'aktif' => self::ACTIVE,
'status' => $names('t_statuspegawai', 'idstatuspegawai', 'statuspegawai', true),
'pendidikan' => $zero($education),
'bank' => $names('t_bank', 'idbank', 'namabank'),
'prodi' => $this->prodi === [] ? [] : $this->db()->table('t_bagian')->whereIn('idbagian', $this->prodi)->orderBy('namabagian')->pluck('namabagian', 'idbagian')
->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => trim($name)])->all(),
'pangkat' => $names('t_pangkatdosen', 'idpangkatdosen', 'pangkatdosen'),
'jabfung' => $names('t_jabatanfungsional', 'idjabatanfungsional', 'jabatan'),
];
}
/**
* @param list<int> $prodi
* @param list<int> $faculties
*/
public function exists(array $prodi, array $faculties, int $id): bool
{
return $this->directory->scoped($prodi, $faculties)->where('p.idpegawai', $id)->exists();
}
/**
* Biodata satu pegawai dalam cakupan: per bagian, nilai isian dan teks tampil. Bagian dosen hanya untuk dosen.
*
* @param list<int> $prodi
* @param list<int> $faculties
* @return array{sections: array<string, array<string, mixed>>, extra: array<string, mixed>}|null
*/
public function find(array $prodi, array $faculties, int $id): ?array
{
$this->scope($prodi);
$row = $this->row($prodi, $faculties, $id);
if ($row === null) {
return null;
}
$lookups = $this->lookups();
$sections = [];
foreach (self::sections() as $key => $section) {
if ($key === self::DOSEN && $row->dosen_id === null) {
continue;
}
$sections[$key] = $this->present($section, $row, $lookups) + ['key' => $key, 'title' => $section['title'], 'icon' => $section['icon'], 'description' => $section['description']];
}
return ['sections' => $sections, 'extra' => $this->extra($row, $id)];
}
/**
* Periksa isian satu bagian. NIP diperiksa tidak kembar dengan pegawai lain; home base hanya prodi akun.
*
* @param list<int> $prodi
* @param list<int> $faculties
* @param array<string, mixed> $input
* @return array<string, mixed>
*
* @throws ValidationException
*/
public function validated(array $prodi, array $faculties, int $id, string $key, array $input): array
{
$this->scope($prodi);
$row = $this->row($prodi, $faculties, $id) ?? throw new PortalException('Pegawai tidak ditemukan.');
if ($key === self::DOSEN && $row->dosen_id === null) {
throw new PortalException('Pegawai ini bukan dosen.');
}
$unique = function (string $attribute, mixed $value, \Closure $fail) use ($id): void {
$nip = trim((string) $value);
if ($this->db()->table('t_pegawai')->whereRaw('upper(trim(nip)) = ?', [mb_strtoupper($nip)])->where('idpegawai', '<>', $id)->exists()) {
$fail("NIP {$nip} sudah terdaftar.");
}
};
return $this->validateFields(self::sections()[$key]['fields'], $row, $input, ['nip' => [$unique]]);
}
/**
* Simpan satu bagian. Mengembalikan bagian yang sudah diperbarui (nilai isian + teks tampil) dan banyak kolom yang berubah.
*
* @param list<int> $prodi
* @param list<int> $faculties
* @param array<string, mixed> $input
* @return array{section: array<string, mixed>, changed: int}
*/
public function update(array $prodi, array $faculties, int $id, string $key, array $input, string $actor, ?string $ip): array
{
$this->scope($prodi);
$section = self::sections()[$key] ?? throw new PortalException('Bagian biodata tidak dikenal.');
$row = $this->row($prodi, $faculties, $id) ?? throw new PortalException('Pegawai tidak ditemukan.');
if ($key === self::DOSEN && $row->dosen_id === null) {
throw new PortalException('Pegawai ini bukan dosen.');
}
$lookups = $this->lookups();
$changes = $this->changes($section['fields'], $row, $input, $lookups);
if ($changes !== []) {
$this->db()->table($key === self::DOSEN ? 't_dosen' : 't_pegawai')->where('idpegawai', $id)->update($changes + [
'cname' => ActivityTypes::APP_NAME, 'cip' => $ip ?? '', 'uname' => mb_substr($actor, 0, 15), 'tanggal' => now(),
]);
}
return [
'section' => $this->present($section, $this->row($prodi, $faculties, $id), $lookups),
'changed' => count($changes),
];
}
/**
* @param list<int> $prodi
* @param list<int> $faculties
*/
private function row(array $prodi, array $faculties, int $id): ?object
{
$columns = [];
foreach (self::sections() as $key => $section) {
foreach ($section['fields'] as $field) {
$columns[] = ($key === self::DOSEN ? 'dd.' : 'p.').$field['name'];
}
}
return $this->directory->scoped($prodi, $faculties)
->leftJoin('t_dosen as dd', 'dd.idpegawai', '=', 'p.idpegawai')
->where('p.idpegawai', $id)
->first(array_merge($columns, ['p.idjenispegawai', 'dd.idpegawai as dosen_id']));
}
/**
* Keterangan yang hanya dibaca dan angka ringkasan: jenis pegawai, jabatan aktif, mahasiswa bimbingan, kelas diampu.
*
* @return array<string, mixed>
*/
private function extra(object $row, int $id): array
{
$type = $row->idjenispegawai === null ? null : $this->db()->table('t_jenispegawai')->where('idjenispegawai', $row->idjenispegawai)->value('jenispegawai');
$positions = $this->db()->table('t_jabatanpegawai as jp')
->join('t_jabatanbagian as jb', 'jb.idjabatanbagian', '=', 'jp.idjabatanbagian')
->leftJoin('t_jenisjabatan as jj', 'jj.idjenisjabatan', '=', 'jb.idjenisjabatan')
->leftJoin('t_bagian as b', 'b.idbagian', '=', 'jb.idbagian')
->where('jp.idpegawai', $id)->where('jp.aktif', 1)->orderBy('jp.idjabatan')
->get(['jj.namajabatan', 'b.namabagian'])
->map(fn (object $p): string => trim(trim((string) $p->namajabatan).' '.trim((string) $p->namabagian)))
->filter()->values();
return [
'jenis' => filled($type) ? trim($type) : null,
'dosen' => $row->dosen_id !== null,
'jabatan' => $positions->all(),
'bimbingan' => $this->count($this->db()->table('t_mahasiswa')->where('idpa', $id)->whereIn('stataktif', StudentDirectory::STATUS['aktif'])),
'kelas' => $this->count($this->db()->table('t_jadwaldosen')->where('iddosen', $id), 'idjadwal'),
];
}
private function count(Builder $query, ?string $distinct = null): int
{
return $distinct === null ? $query->count() : $query->distinct()->count($distinct);
}
}
-6
View File
@@ -108,12 +108,6 @@ final class EmployeeDirectory
return [
'id' => (int) $p->idpegawai,
'form' => [
'nip' => $filled($p->nip) ?? '', 'nama' => trim((string) $p->nama), 'gelardepan' => trim((string) $p->gelardepan), 'gelarbelakang' => trim((string) $p->gelarbelakang),
'kelamin' => (int) $p->kelamin ?: '', 'nidn' => $filled($p->nidn) ?? '', 'hp' => $filled($p->hp) ?? '', 'telepon' => $filled($p->telepon) ?? '',
'email' => $filled($p->email) ?? '', 'status' => $p->idstatuspegawai === null ? '' : (int) $p->idstatuspegawai,
'aktif' => (int) $p->statusaktif === self::INACTIVE ? 0 : 1,
],
'nip' => $filled($p->nip),
'nama' => trim(($filled($p->gelardepan) ?? '').' '.trim($p->nama)).($suffix === null ? '' : ', '.ltrim($suffix, ', ')),
'kelamin' => [1 => 'L', 2 => 'P'][(int) $p->kelamin] ?? null,
+22 -16
View File
@@ -8,8 +8,8 @@ use Illuminate\Support\Facades\DB;
/**
* Tulis data pegawai DB lama (t_pegawai) dalam cakupan yang tampil di daftar operator (EmployeeDirectory::scoped).
* Hanya ubah data dasar dan hapus (template SATU tidak punya tombol Tambah untuk Pegawai). Akun login
* (t_account) tidak disentuh, dan pegawai yang dirujuk jabatan, jadwal, bimbingan, skripsi, atau akun tidak boleh dihapus.
* Tambah (sebagai dosen) dan hapus. Mengubah biodata dilakukan di halaman detail (EmployeeBiodata). Akun login (t_account)
* tidak disentuh, dan pegawai yang dirujuk jabatan, jadwal, bimbingan, skripsi, atau akun tidak boleh dihapus.
*/
final class EmployeeRecords
{
@@ -17,6 +17,9 @@ final class EmployeeRecords
public const array ACTIVE = [1 => 'Aktif', 0 => 'Tidak aktif'];
/** t_jenispegawai: 1 Dosen, 2 Staff. */
private const int TYPE_LECTURER = 1;
/** [tabel, kolom rujukan ke idpegawai]; baris di salah satunya menghalangi penghapusan. */
private const array DEPENDENTS = [
['t_jabatanpegawai', 'idpegawai'], ['t_mastermk', 'idpegawai'], ['t_jadwaldosen', 'iddosen'], ['t_jadwal', 'idpegperkuliahan'],
@@ -38,19 +41,26 @@ final class EmployeeRecords
}
/**
* Tambah pegawai baru sebagai dosen dengan home base salah satu prodi akun (t_dosen.idprogdi), sehingga langsung masuk
* cakupan daftar. Pegawai staf (bukan dosen) hanya tampil di daftar lewat jabatan aktif, yang tidak diatur di sini.
*
* @param list<int> $prodi
* @param list<int> $faculties
* @param array<string, mixed> $input
* @return int idpegawai baru
*/
public function update(array $prodi, array $faculties, int $id, array $input, string $actor, ?string $ip): void
public function create(array $prodi, int $homeBase, array $input, string $actor, ?string $ip): int
{
$current = $this->owned($prodi, $faculties)->where('p.idpegawai', $id)->first(['p.idpegawai', 'p.statusaktif']);
if ($current === null) {
throw new PortalException('Pegawai tidak ditemukan.');
if (! in_array($homeBase, $prodi, true)) {
throw new PortalException('Home base harus dipilih dari program studi Anda.');
}
$values = $this->values($input, $current);
$values = $this->values($input);
$this->db()->table('t_pegawai')->where('idpegawai', $id)->update($values + $this->audit($actor, $ip));
return $this->db()->transaction(function () use ($values, $homeBase, $actor, $ip): int {
$id = (int) $this->db()->table('t_pegawai')->insertGetId($values + ['idjenispegawai' => self::TYPE_LECTURER] + $this->audit($actor, $ip), 'idpegawai');
$this->db()->table('t_dosen')->insert(['idpegawai' => $id, 'idprogdi' => $homeBase] + $this->audit($actor, $ip));
return $id;
});
}
/**
@@ -109,7 +119,7 @@ final class EmployeeRecords
* @param array<string, mixed> $input
* @return array<string, mixed>
*/
private function values(array $input, ?object $current): array
private function values(array $input): array
{
$text = fn (mixed $v): ?string => ($v = trim((string) $v)) === '' ? null : $v;
$nip = trim((string) ($input['nip'] ?? ''));
@@ -117,9 +127,7 @@ final class EmployeeRecords
if ($nip === '' || $nama === '') {
throw new PortalException('NIP dan nama wajib diisi.');
}
$duplicate = $this->db()->table('t_pegawai')->whereRaw('upper(trim(nip)) = ?', [mb_strtoupper($nip)])
->when($current !== null, fn (Builder $q) => $q->where('idpegawai', '<>', $current->idpegawai))->exists();
if ($duplicate) {
if ($this->db()->table('t_pegawai')->whereRaw('upper(trim(nip)) = ?', [mb_strtoupper($nip)])->exists()) {
throw new PortalException("NIP {$nip} sudah terdaftar.");
}
$gender = filled($input['kelamin'] ?? null) ? (int) $input['kelamin'] : null;
@@ -138,8 +146,6 @@ final class EmployeeRecords
if (! isset(self::ACTIVE[$active])) {
throw new PortalException('Status aktif tidak dikenal.');
}
// Kode aktif selain 0 dan 1 (mis. 2, 3, 5, 6) tidak ada artinya di sini: dibiarkan selama tetap dianggap aktif.
$keep = $current !== null && (int) $current->statusaktif !== 0 ? (int) $current->statusaktif : 1;
return [
'nip' => $nip,
@@ -152,7 +158,7 @@ final class EmployeeRecords
'telepon' => $text($input['telepon'] ?? null),
'email' => $email,
'idstatuspegawai' => $status,
'statusaktif' => $active === 0 ? 0 : $keep,
'statusaktif' => $active,
];
}
+6 -128
View File
@@ -2,10 +2,10 @@
namespace App\Support\Legacy;
use App\Support\Legacy\Concerns\BiodataFields;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
/**
@@ -16,6 +16,8 @@ use Illuminate\Validation\ValidationException;
*/
final class StudentBiodata
{
use BiodataFields;
/** Kode pilihan tanpa tabel referensi di DB; arti kode diambil dari komentar kolom t_mahasiswa. */
private const array MARITAL = [1 => 'Belum kawin', 2 => 'Kawin'];
@@ -185,21 +187,7 @@ final class StudentBiodata
$row = $this->row($prodi, $id) ?? throw new PortalException('Mahasiswa tidak ditemukan.');
$lookups = $this->lookups();
$changes = [];
foreach ($section['fields'] as $field) {
$name = $field['name'];
if (! array_key_exists($name, $input)) {
continue;
}
$new = $this->normalize($field, $input[$name], $lookups);
if ($field['name'] === 'nama' && $new === null) {
throw new PortalException('Nama wajib diisi.');
}
if ($new !== $this->normalize($field, $row->{$name}, $lookups)) {
// Kolom wajib di DB asli (NOT NULL) tidak pernah diisi null.
$changes[$name] = $new ?? (($field['type'] ?? '') === 'select' ? 0 : null);
}
}
$changes = $this->changes($section['fields'], $row, $input, $lookups);
if ($changes !== []) {
$this->db()->table('t_mahasiswa')->where('idmahasiswa', $id)->update($changes + [
@@ -225,46 +213,6 @@ final class StudentBiodata
->first(array_merge(array_map(fn (string $c): string => 'm.'.$c, $columns), ['m.idpa', 'm.jalur_masuk', 'm.idkurikulum', 'm.stataktif', 'm.tgl_lulus']));
}
/**
* Nilai isian (untuk formulir) dan teks tampil satu bagian.
*
* @param array<string, mixed> $section
* @param array<string, array<int, string>> $lookups
* @return array{fields: list<array<string, mixed>>, values: array<string, mixed>, display: array<string, string>}
*/
private function present(array $section, object $row, array $lookups): array
{
$fields = [];
$values = [];
$display = [];
foreach ($section['fields'] as $field) {
$name = $field['name'];
$value = $this->normalize($field, $row->{$name}, $lookups);
if (($field['type'] ?? '') === 'select') {
$options = $lookups[$field['lookup']];
$current = (int) ($value ?? 0);
// Kode yang tidak ada di tabel referensi tetap tampil dan bisa dipertahankan.
$options += isset($options[$current]) ? [] : [$current => 'Kode '.$current];
$field['options'] = $options;
$values[$name] = $current;
$display[$name] = $current === 0 ? '–' : $options[$current];
} else {
$values[$name] = $value ?? '';
$display[$name] = match (true) {
$value === null => '–',
($field['type'] ?? '') === 'date' => Carbon::parse($value)->locale('id')->isoFormat('D MMMM YYYY'),
default => (string) $value,
};
}
$fields[] = $field;
}
return ['fields' => $fields, 'values' => $values, 'display' => $display];
}
/**
* Data akademik yang hanya dibaca: jalur masuk, kurikulum, dosen PA, tanggal lulus.
*
@@ -285,34 +233,7 @@ final class StudentBiodata
}
/**
* Nilai kolom dalam bentuk baku agar dua nilai bisa dibandingkan: teks dipangkas (kosong = null), tanggal Y-m-d,
* angka integer, pilihan integer (kosong = 0 pada pilihan yang punya kode 0).
*
* @param array<string, mixed> $field
* @param array<string, array<int, string>> $lookups
*/
private function normalize(array $field, mixed $value, array $lookups): string|int|null
{
$type = $field['type'] ?? 'text';
$text = is_scalar($value) ? trim((string) $value) : '';
return match ($type) {
'select' => (function () use ($text, $field, $lookups): ?int {
if ($text === '') {
return isset($lookups[$field['lookup']][0]) ? 0 : null;
}
return (int) $text;
})(),
'number' => $text === '' ? null : (int) $text,
'date' => $text === '' ? null : substr($text, 0, 10),
default => $text === '' ? null : $text,
};
}
/**
* Periksa isian satu bagian. Isian yang nilainya sama dengan yang tersimpan tidak diperiksa bentuknya (data lama
* boleh tidak seragam) dan tidak ikut dikembalikan; kolom wajib selalu diperiksa.
* Periksa isian satu bagian (hanya isian yang berubah diperiksa bentuknya; lihat BiodataFields::validateFields).
*
* @param list<int> $prodi
* @param array<string, mixed> $input
@@ -323,50 +244,7 @@ final class StudentBiodata
public function validated(array $prodi, int $id, string $key, array $input): array
{
$row = $this->row($prodi, $id) ?? throw new PortalException('Mahasiswa tidak ditemukan.');
$lookups = $this->lookups();
$rules = $this->rules($key);
foreach (self::sections()[$key]['fields'] as $field) {
$name = $field['name'];
if (! ($field['required'] ?? false) && array_key_exists($name, $input)
&& $this->normalize($field, $input[$name], $lookups) === $this->normalize($field, $row->{$name}, $lookups)) {
unset($rules[$name]);
}
}
return Validator::make($input, $rules, [], $this->attributes($key))->validate();
}
/** @return array<string, list<string>> */
private function rules(string $key): array
{
$lookups = $this->lookups();
$rules = [];
foreach (self::sections()[$key]['fields'] as $field) {
$type = $field['type'] ?? 'text';
$base = ($field['required'] ?? false) ? ['required'] : ['nullable'];
$rules[$field['name']] = array_merge($base, match (true) {
$type === 'select' => ['integer', 'in:'.implode(',', array_keys($lookups[$field['lookup']]))],
$type === 'number' => ['integer', 'min:'.($field['min'] ?? 0), 'max:'.($field['max'] ?? 99)],
$type === 'date' => ['date_format:Y-m-d', 'before_or_equal:today'],
$type === 'email' => ['string', 'email', 'max:'.$field['max']],
default => array_values(array_filter([
'string',
'max:'.$field['max'],
($field['alnum'] ?? false) ? 'regex:/^[0-9A-Za-z]+$/' : null,
($field['digits'] ?? false) ? 'regex:/^[0-9]{4}$/' : null,
])),
});
}
return $rules;
}
/** @return array<string, string> */
private function attributes(string $key): array
{
return collect(self::sections()[$key]['fields'])->mapWithKeys(fn (array $f): array => [$f['name'] => mb_strtolower($f['label'])])->all();
return $this->validateFields(self::sections()[$key]['fields'], $row, $input);
}
}