59 lines
2.3 KiB
PHP
59 lines
2.3 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Imports;
|
||
|
|
|
||
|
|
use App\Models\User;
|
||
|
|
use Illuminate\Support\Collection;
|
||
|
|
use Maatwebsite\Excel\Concerns\ToCollection;
|
||
|
|
use Maatwebsite\Excel\Concerns\WithHeadingRow;
|
||
|
|
use Illuminate\Support\Facades\Hash;
|
||
|
|
|
||
|
|
class EmployeesImport implements ToCollection, WithHeadingRow
|
||
|
|
{
|
||
|
|
public $successCount = 0;
|
||
|
|
public $failCount = 0;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Asumsi Header Excel (Baris ke-1):
|
||
|
|
* nik | nama_depan | nama_belakang | email | telepon | jenis_kelamin | department_id | position_id
|
||
|
|
*/
|
||
|
|
public function collection(Collection $rows)
|
||
|
|
{
|
||
|
|
foreach ($rows as $row) {
|
||
|
|
try {
|
||
|
|
// Validasi: Abaikan baris jika NIK, Nama Depan, atau Email kosong
|
||
|
|
if (empty($row['nik']) || empty($row['nama_depan']) || empty($row['email'])) {
|
||
|
|
$this->failCount++;
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Update jika NIK sudah ada, Create jika belum ada
|
||
|
|
$user = User::updateOrCreate(
|
||
|
|
['nik' => $row['nik']], // Pencarian berdasarkan NIK
|
||
|
|
[
|
||
|
|
'first_name' => $row['nama_depan'],
|
||
|
|
'last_name' => $row['nama_belakang'] ?? null,
|
||
|
|
'email' => $row['email'],
|
||
|
|
'phone' => $row['telepon'] ?? null,
|
||
|
|
'gender' => in_array(strtoupper($row['jenis_kelamin'] ?? ''), ['L', 'P']) ? strtoupper($row['jenis_kelamin']) : 'L',
|
||
|
|
'department_id' => $row['department_id'] ?? 1, // Fallback ID 1 jika kosong
|
||
|
|
'position_id' => $row['position_id'] ?? 1,
|
||
|
|
'password' => Hash::make('Karyawan123!'),
|
||
|
|
'is_active' => true,
|
||
|
|
'must_change_password' => true,
|
||
|
|
]
|
||
|
|
);
|
||
|
|
|
||
|
|
// Otomatis jadikan Trainee
|
||
|
|
if (!$user->hasAnyRole(['admin', 'trainer', 'trainee'])) {
|
||
|
|
$user->assignRole('trainee');
|
||
|
|
}
|
||
|
|
|
||
|
|
$this->successCount++;
|
||
|
|
} catch (\Exception $e) {
|
||
|
|
// Jika error (misal format email salah atau duplikat), masukkan ke hitungan gagal
|
||
|
|
$this->failCount++;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|