75 lines
2.2 KiB
PHP
75 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Payroll;
|
|
use App\Models\User;
|
|
use App\Support\LogHelper;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Throwable;
|
|
|
|
class GeneratePayrollCommand extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'payroll:generate {period?}';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Generate payroll for all users for a given period (YYYY-MM)';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle()
|
|
{
|
|
$periodMonth = $this->argument('period') ?? Carbon::now()->format('Y-m');
|
|
$periodMonthFormatted = Carbon::parse($periodMonth)->translatedFormat('F Y');
|
|
$users = User::with('profile')->get();
|
|
$count = 0;
|
|
|
|
try {
|
|
DB::transaction(function () use ($users, $periodMonth, &$count) {
|
|
foreach ($users as $user) {
|
|
$exists = Payroll::where('user_id', $user->id)
|
|
->where('period_month', $periodMonth)
|
|
->exists();
|
|
|
|
if (! $exists) {
|
|
$baseSalary = $user->profile?->base_salary ?? 0;
|
|
|
|
Payroll::create([
|
|
'user_id' => $user->id,
|
|
'period_month' => $periodMonth,
|
|
'base_salary' => $baseSalary,
|
|
'bonus' => 0,
|
|
'deduction' => 0,
|
|
'total_salary' => $baseSalary,
|
|
'is_paid' => false,
|
|
]);
|
|
$count++;
|
|
}
|
|
}
|
|
});
|
|
} catch (Throwable $e) {
|
|
LogHelper::logException($e, 'Payroll generate failed', [
|
|
'period' => $periodMonth,
|
|
]);
|
|
|
|
$this->info('Gagal generate data penggajian, silakan hubungi pengembang.');
|
|
|
|
return;
|
|
}
|
|
|
|
$this->info("$count data penggajian berhasil digenerate untuk periode $periodMonthFormatted.");
|
|
}
|
|
}
|