Adiciona dotacoes e reservas orcamentais por empresa
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Budget;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\CostCenter;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class BudgetController extends Controller
|
||||
{
|
||||
private function access(Request $request): void
|
||||
{
|
||||
abort_unless(in_array($request->user()->purchasing_role, [PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||
}
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$this->access($request);
|
||||
|
||||
return Inertia::render('budgets/index', ['centers' => CostCenter::query()->orderBy('code')->get(), 'budgets' => Budget::query()->latest('id')->get()->map(function (Budget $budget) {
|
||||
$entries = BudgetEntry::query()->where('budget_id', $budget->id);
|
||||
$reserved = (int) (clone $entries)->sum('reserved_minor');
|
||||
$committed = (int) $entries->sum('committed_minor');
|
||||
|
||||
return [...$budget->toArray(), 'reserved_minor' => $reserved, 'committed_minor' => $committed, 'available_minor' => $budget->amount_minor - $reserved - $committed];
|
||||
})]);
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$this->access($request);
|
||||
$data = $request->validate(['cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $request->user()->tenant_id)], 'year' => 'required|integer|min:2026|max:2100', 'includes_tax' => 'required|boolean', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'reason' => 'required|string|max:4000']);
|
||||
DB::transaction(function () use ($request, $data) {
|
||||
app(ConflictGuard::class)->lockCompany($request->user());
|
||||
abort_if(Budget::query()->where('cost_center_id', $data['cost_center_id'])->where('year', $data['year'])->exists(), 409, 'Já existe dotação para este centro e exercício.');
|
||||
$budget = Budget::query()->create(['tenant_id' => $request->user()->tenant_id, 'created_by' => $request->user()->id, 'cost_center_id' => $data['cost_center_id'], 'year' => $data['year'], 'includes_tax' => $data['includes_tax'], 'amount_minor' => BigDecimal::of($data['amount'])->multipliedBy(100)->toInt(), 'reason' => $data['reason']]);
|
||||
app(RequisitionWorkflow::class)->audit($request->user(), 'budget.created', null, null, $budget->toArray());
|
||||
});
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function approve(Request $request, Budget $budget): RedirectResponse
|
||||
{
|
||||
$this->access($request);
|
||||
DB::transaction(function () use ($request, $budget) {
|
||||
app(ConflictGuard::class)->lockCompany($request->user());
|
||||
$budget = Budget::query()->lockForUpdate()->findOrFail($budget->id);
|
||||
abort_if($budget->created_by === $request->user()->id, 403);
|
||||
if ($budget->approved_by) {
|
||||
return;
|
||||
}
|
||||
$budget->update(['approved_by' => $request->user()->id, 'approved_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($request->user(), 'budget.approved', null, null, $budget->toArray());
|
||||
});
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/** @property int $id
|
||||
* @property int $amount_minor
|
||||
* @property int $created_by
|
||||
* @property int|null $approved_by
|
||||
*/
|
||||
class Budget extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['includes_tax' => 'boolean'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\AppendOnlyInventoryRecord;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class BudgetEntry extends Model
|
||||
{
|
||||
use AppendOnlyInventoryRecord, BelongsToTenant;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Budget;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class BudgetWorkflow
|
||||
{
|
||||
/** Called inside the procurement transaction, after the company lock.
|
||||
* @return array<string,int>|null
|
||||
*/
|
||||
public function record(User $user, Requisition $request, string $kind, int $amount = 0, ?int $subtotal = null): ?array
|
||||
{
|
||||
$existing = BudgetEntry::query()->where('requisition_id', $request->id)->orderBy('id')->first();
|
||||
$budget = $existing
|
||||
? Budget::query()->lockForUpdate()->findOrFail($existing->budget_id)
|
||||
: Budget::query()->where('cost_center_id', $request->cost_center_id)->where('year', now()->year)->lockForUpdate()->first();
|
||||
// Unconfigured legacy processes remain development documents, explicitly unchecked.
|
||||
if (! $budget) {
|
||||
return null;
|
||||
}
|
||||
if (! $budget->approved_by || ($kind !== 'release' && (int) $budget->year !== now()->year)) {
|
||||
throw ValidationException::withMessages(['budget' => 'Dotação pendente de aprovação ou exercício encerrado.']);
|
||||
}
|
||||
if (! $budget->includes_tax && in_array($kind, ['reserve', 'award', 'commit'])) {
|
||||
$amount = $subtotal ?? throw new \LogicException('Subtotal necessário para a base sem IVA.');
|
||||
}
|
||||
if (BudgetEntry::query()->where('requisition_id', $request->id)->where('kind', $kind)->exists()) {
|
||||
return ['budget_id' => $budget->id, 'year' => (int) $budget->year];
|
||||
}
|
||||
$own = BudgetEntry::query()->where('requisition_id', $request->id);
|
||||
$reserved = (int) (clone $own)->sum('reserved_minor');
|
||||
$committed = (int) $own->sum('committed_minor');
|
||||
if ($committed !== 0 || ($kind !== 'reserve' && ! $existing)) {
|
||||
throw ValidationException::withMessages(['budget' => 'Processo sem reserva válida ou já comprometido.']);
|
||||
}
|
||||
[$reserveDelta, $commitDelta] = match ($kind) {
|
||||
'reserve', 'award' => [$amount - $reserved, 0],
|
||||
'release' => [-$reserved, 0],
|
||||
'commit' => [-$reserved, $amount],
|
||||
default => throw new \LogicException('Movimento orçamental inválido.'),
|
||||
};
|
||||
$ledger = BudgetEntry::query()->where('budget_id', $budget->id);
|
||||
$used = (int) (clone $ledger)->sum('reserved_minor') + (int) $ledger->sum('committed_minor');
|
||||
if ($used + $reserveDelta + $commitDelta > $budget->amount_minor) {
|
||||
throw ValidationException::withMessages(['budget' => 'Saldo orçamental insuficiente. Não são permitidos excessos.']);
|
||||
}
|
||||
BudgetEntry::query()->create(['tenant_id' => $user->tenant_id, 'budget_id' => $budget->id, 'requisition_id' => $request->id, 'created_by' => $user->id, 'kind' => $kind, 'reserved_minor' => $reserveDelta, 'committed_minor' => $commitDelta, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($user, 'budget.'.$kind, $request, null, ['budget_id' => $budget->id, 'reserved_minor' => $reserveDelta, 'committed_minor' => $commitDelta]);
|
||||
|
||||
return ['budget_id' => $budget->id, 'year' => (int) $budget->year];
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ class PurchaseWorkflow
|
||||
$this->sourceApproved($requisition, $rules);
|
||||
$quote = Quotation::query()->where('requisition_id', $requisition->id)->lockForUpdate()->findOrFail($data['quotation_id']);
|
||||
$result = $this->checkComparison($user, $requisition, $quote);
|
||||
app(BudgetWorkflow::class)->record($user, $requisition, 'award', $quote->total_minor, $quote->subtotal_minor);
|
||||
$award = PurchaseAward::query()->create([
|
||||
'tenant_id' => $user->tenant_id, 'requisition_id' => $requisition->id, 'quotation_id' => $quote->id,
|
||||
'created_by' => $user->id, 'justification' => $data['justification'], 'delivery_date' => $data['delivery_date'],
|
||||
@@ -80,6 +81,9 @@ class PurchaseWorkflow
|
||||
$step->update(['decision' => $decision, 'approver_id' => $user->id, 'comment' => $comment, 'decided_at' => now()]);
|
||||
$status = $decision === 'rejected' ? 'rejected' : ($award->approvals()->where('decision', 'pending')->exists() ? 'pending' : 'approved');
|
||||
$award->update(['status' => $status]);
|
||||
if ($decision === 'rejected') {
|
||||
app(BudgetWorkflow::class)->record($user, $requisition, 'release');
|
||||
}
|
||||
$this->audit->audit($user, 'award.'.$decision, $requisition, ['status' => 'pending'], ['award_id' => $award->id, 'status' => $status, 'approval' => $step->toArray()]);
|
||||
});
|
||||
}
|
||||
@@ -125,6 +129,7 @@ class PurchaseWorkflow
|
||||
}
|
||||
$snapshot = [
|
||||
'development_only' => true, 'budget_checked' => false,
|
||||
'budget_control' => app(BudgetWorkflow::class)->record($user, $requisition, 'commit', $quote->total_minor, $quote->subtotal_minor),
|
||||
'company' => Tenant::query()->findOrFail($user->tenant_id)->only(['id', 'name']),
|
||||
'requisition' => $requisition->only(['id', 'number', 'justification']),
|
||||
'department' => $requisition->department->only(['id', 'name']),
|
||||
|
||||
@@ -81,6 +81,7 @@ class RequisitionWorkflow
|
||||
throw ValidationException::withMessages(['submission' => 'Actualize a data de entrega antes de submeter.']);
|
||||
}
|
||||
$tenant = Tenant::query()->findOrFail($user->tenant_id);
|
||||
app(BudgetWorkflow::class)->record($user, $requisition, 'reserve', $requisition->total_minor, $requisition->subtotal_minor);
|
||||
$amount = $tenant->approval_includes_tax ? $requisition->total_minor : $requisition->subtotal_minor;
|
||||
$roles = ['department_head'];
|
||||
if ($amount > $tenant->first_limit_minor) {
|
||||
@@ -113,6 +114,9 @@ class RequisitionWorkflow
|
||||
$step->update(['decision' => $decision, 'approver_id' => $user->id, 'comment' => $comment, 'decided_at' => now()]);
|
||||
$status = $decision === 'rejected' ? 'rejected' : ($requisition->steps()->where('decision', 'pending')->exists() ? 'pending' : 'approved');
|
||||
$requisition->update(['status' => $status]);
|
||||
if ($decision === 'rejected') {
|
||||
app(BudgetWorkflow::class)->record($user, $requisition, 'release');
|
||||
}
|
||||
$this->audit($user, 'approval.'.$decision, $requisition, ['status' => 'pending'], ['status' => $status, 'step_id' => $step->id, 'role' => $step->role, 'comment' => $comment]);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user