62 lines
1.8 KiB
PHP
62 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace Modules\Accounting\Services;
|
|
|
|
use App\Transaction;
|
|
use Modules\Accounting\Utils\AccountingUtil;
|
|
|
|
class PayrollTaxBridgeService
|
|
{
|
|
public function __construct(
|
|
protected AccountingUtil $accountingUtil,
|
|
protected PayrollTaxTableService $taxTableService
|
|
) {}
|
|
|
|
public function isEnabled(int $businessId): bool
|
|
{
|
|
$settings = $this->accountingUtil->getAccountingSettings($businessId);
|
|
|
|
return ! empty($settings['payroll_tax_auto_apply']);
|
|
}
|
|
|
|
public function applyToPayroll(Transaction $transaction, int $businessId): Transaction
|
|
{
|
|
if ($transaction->type !== 'payroll' || ! $this->isEnabled($businessId)) {
|
|
return $transaction;
|
|
}
|
|
|
|
$taxableIncome = (float) ($transaction->total_before_tax ?: $transaction->final_total);
|
|
$taxAmount = $this->taxTableService->calculateTax($businessId, $taxableIncome);
|
|
|
|
if ($taxAmount <= 0) {
|
|
return $transaction;
|
|
}
|
|
|
|
$deductions = json_decode($transaction->essentials_deductions ?? '[]', true);
|
|
if (! is_array($deductions)) {
|
|
$deductions = [];
|
|
}
|
|
|
|
$alreadyApplied = collect($deductions)->contains(function ($row) {
|
|
return is_array($row) && ($row['name'] ?? '') === 'Income Tax (GL)';
|
|
});
|
|
|
|
if ($alreadyApplied) {
|
|
return $transaction;
|
|
}
|
|
|
|
$deductions[] = [
|
|
'name' => 'Income Tax (GL)',
|
|
'amount' => $taxAmount,
|
|
'type' => 'fixed',
|
|
'percent' => 0,
|
|
];
|
|
|
|
$transaction->essentials_deductions = json_encode($deductions);
|
|
$transaction->final_total = max(0, (float) $transaction->final_total - $taxAmount);
|
|
$transaction->save();
|
|
|
|
return $transaction;
|
|
}
|
|
}
|