store/app/Services/Finance/PayrollService.php

344 lines
11 KiB
PHP

<?php
namespace App\Services\Finance;
use App\Enums\EmployeeAdvanceStatus;
use App\Enums\PayrollAdjustmentType;
use App\Enums\PayrollPeriodStatus;
use App\Enums\PayrollStatus;
use App\Enums\Role;
use App\Models\Employee;
use App\Models\EmployeeAdvance;
use App\Models\Payroll;
use App\Models\PayrollPeriod;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class PayrollService
{
public function __construct(
private readonly CashService $cashService,
) {}
/**
* @return Collection<int, PayrollPeriod>
*/
public function listPeriods(): Collection
{
return PayrollPeriod::query()
->orderByDesc('year')
->orderByDesc('month')
->get();
}
public function resolvePeriod(?int $periodId): ?PayrollPeriod
{
if ($periodId !== null) {
return PayrollPeriod::query()->find($periodId);
}
return PayrollPeriod::query()
->where('status', PayrollPeriodStatus::OPEN)
->orderByDesc('year')
->orderByDesc('month')
->first()
?? PayrollPeriod::query()
->orderByDesc('year')
->orderByDesc('month')
->first();
}
/**
* @return array{total_total_amount: int, total_total_amount_formatted: string, unpaid_count: int, paid_count: int}
*/
public function periodSummary(PayrollPeriod $period): array
{
$totalTotalAmount = (int) Payroll::query()
->where('payroll_period_id', $period->id)
->where('status', PayrollStatus::UNPAID)
->sum('total_amount');
$unpaidCount = Payroll::query()
->where('payroll_period_id', $period->id)
->where('status', PayrollStatus::UNPAID)
->count();
$paidCount = Payroll::query()
->where('payroll_period_id', $period->id)
->where('status', PayrollStatus::PAID)
->count();
return [
'total_total_amount' => $totalTotalAmount,
'total_total_amount_formatted' => 'Rp '.number_format($totalTotalAmount, 0, ',', '.'),
'unpaid_count' => $unpaidCount,
'paid_count' => $paidCount,
];
}
/**
* @param array{search: string, sort: string, direction: 'asc'|'desc'} $tableQuery
*/
public function paginateForPeriod(PayrollPeriod $period, array $tableQuery): LengthAwarePaginator
{
$query = Payroll::query()
->with(['employee.user.profile', 'payrollPeriod'])
->where('payroll_period_id', $period->id)
->when($tableQuery['search'] !== '', function (Builder $query) use ($tableQuery): void {
$search = $tableQuery['search'];
$query->where(function (Builder $query) use ($search): void {
$query->whereHas('employee.user.profile', fn (Builder $query) => $query->where('full_name', 'like', "%{$search}%"))
->orWhereHas('employee.user', fn (Builder $query) => $query->where('username', 'like', "%{$search}%"));
});
});
$this->applySorting($query, $tableQuery['sort'], $tableQuery['direction']);
return $query
->paginate(10)
->withQueryString();
}
public function openCurrentPeriod(?User $closedBy = null): PayrollPeriod
{
return DB::transaction(function () use ($closedBy): PayrollPeriod {
$now = now();
$year = $now->year;
$month = $now->month;
PayrollPeriod::query()
->where('status', PayrollPeriodStatus::OPEN)
->update([
'status' => PayrollPeriodStatus::CLOSED,
'closed_at' => now(),
'closed_by_id' => $closedBy?->id,
]);
$period = PayrollPeriod::query()
->where('year', $year)
->where('month', $month)
->first();
if ($period === null) {
$period = PayrollPeriod::create([
'year' => $year,
'month' => $month,
'status' => PayrollPeriodStatus::OPEN,
]);
} elseif ($period->status === PayrollPeriodStatus::CLOSED) {
$period->status = PayrollPeriodStatus::OPEN;
$period->closed_at = null;
$period->closed_by_id = null;
$period->save();
}
$this->generatePayrollsForPeriod($period);
return $period->fresh();
});
}
public function closePeriod(PayrollPeriod $period, User $user): void
{
if (! $period->isOpen()) {
throw ValidationException::withMessages([
'payroll_period' => 'Periode gaji ini sudah ditutup.',
]);
}
$unpaidCount = Payroll::query()
->where('payroll_period_id', $period->id)
->where('status', PayrollStatus::UNPAID)
->where('total_amount', '>', 0)
->count();
if ($unpaidCount > 0) {
throw ValidationException::withMessages([
'payroll_period' => 'Masih ada gaji yang belum dibayar.',
]);
}
$period->status = PayrollPeriodStatus::CLOSED;
$period->closed_at = now();
$period->closed_by_id = $user->id;
$period->save();
}
public function generatePayrollsForPeriod(PayrollPeriod $period): void
{
$employees = $this->payrollEligibleEmployees($period);
foreach ($employees as $employee) {
$exists = Payroll::query()
->where('payroll_period_id', $period->id)
->where('employee_id', $employee->id)
->exists();
if ($exists) {
continue;
}
$payroll = new Payroll([
'payroll_period_id' => $period->id,
'employee_id' => $employee->id,
'base_salary' => $employee->base_salary,
'bonus_amount' => 0,
'deduction_amount' => 0,
'total_amount' => 0,
'status' => PayrollStatus::UNPAID,
]);
$payroll->save();
$payroll->recalculateAmounts();
$payroll->save();
}
}
/**
* @param array{type: string, amount: int, description: string} $validated
*/
public function addAdjustment(Payroll $payroll, array $validated, User $user): void
{
$payroll->loadMissing('payrollPeriod');
if (! $payroll->can_adjust) {
throw ValidationException::withMessages([
'payroll' => 'Penyesuaian hanya dapat ditambahkan pada gaji yang belum dibayar di periode terbuka.',
]);
}
DB::transaction(function () use ($payroll, $validated, $user): void {
$payroll->adjustments()->create([
'type' => PayrollAdjustmentType::from($validated['type']),
'amount' => (int) $validated['amount'],
'description' => $validated['description'],
'created_by_id' => $user->id,
]);
$payroll->load('adjustments');
$payroll->recalculateAmounts();
$payroll->save();
});
}
public function pay(Payroll $payroll, User $user): void
{
$payroll->loadMissing(['payrollPeriod', 'employee.user.profile']);
if ($payroll->status !== PayrollStatus::UNPAID) {
throw ValidationException::withMessages([
'payroll' => 'Gaji ini sudah dibayar.',
]);
}
if (! $payroll->payrollPeriod?->isOpen()) {
throw ValidationException::withMessages([
'payroll' => 'Periode gaji sudah ditutup.',
]);
}
if ($payroll->total_amount <= 0) {
DB::transaction(function () use ($payroll, $user): void {
$payroll->status = PayrollStatus::PAID;
$payroll->paid_at = now();
$payroll->paid_by_id = $user->id;
$payroll->save();
$this->settleKasbonFromPayroll($payroll, $user);
});
return;
}
DB::transaction(function () use ($payroll, $user): void {
$description = sprintf(
'Pembayaran gaji: %s (%s)',
$payroll->employeeName,
$payroll->payrollPeriod->period_label,
);
$cashTransaction = $this->cashService->recordOutgoing(
$payroll,
$payroll->total_amount,
$description,
$user,
);
$payroll->cash_transaction_id = $cashTransaction->id;
$payroll->status = PayrollStatus::PAID;
$payroll->paid_at = now();
$payroll->paid_by_id = $user->id;
$payroll->save();
$this->settleKasbonFromPayroll($payroll, $user);
});
}
/**
* @return Collection<int, Employee>
*/
private function payrollEligibleEmployees(PayrollPeriod $period): Collection
{
$periodStart = Carbon::create($period->year, $period->month, 1)->startOfMonth();
return Employee::query()
->with('user.roles')
->whereHas('user', function (Builder $query): void {
$query->where('is_active', true)
->whereDoesntHave('roles', fn (Builder $query) => $query->whereIn('name', [
Role::DEVELOPER->value,
Role::OWNER->value,
]));
})
->where(function (Builder $query) use ($periodStart): void {
$query->whereNull('resign_date')
->orWhere('resign_date', '>=', $periodStart);
})
->get();
}
private function settleKasbonFromPayroll(Payroll $payroll, User $user): void
{
$remaining = (int) $payroll->deduction_amount;
if ($remaining <= 0) {
return;
}
$advances = EmployeeAdvance::query()
->where('employee_id', $payroll->employee_id)
->where('status', EmployeeAdvanceStatus::APPROVED)
->orderBy('created_at')
->get();
foreach ($advances as $advance) {
if ($remaining <= 0) {
break;
}
$advance->paid_at = now();
$advance->paid_by_id = $user->id;
$advance->status = EmployeeAdvanceStatus::PAID;
$advance->save();
$remaining -= $advance->amount;
}
}
private function applySorting(Builder $query, string $sort, string $direction): void
{
if (in_array($sort, ['base_salary', 'bonus_amount', 'deduction_amount', 'total_amount', 'status', 'created_at'], true)) {
$query->orderBy($sort, $direction);
return;
}
$query->orderBy('employee_id');
}
}