| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace App\Services;
- use App\Models\CompanyAccountPayable;
- use Carbon\Carbon;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Validation\ValidationException;
- /**
- * Contas a Pagar da matriz (franqueadora). Lançamentos manuais com baixa manual.
- */
- class CompanyAccountPayableService
- {
- public function list(array $filters = []): Collection
- {
- return CompanyAccountPayable::with('planAccount:id,code,description')
- ->when(
- isset($filters['status']),
- fn ($q) => $q->where('status', $filters['status']),
- )
- ->orderBy('due_date')
- ->get();
- }
- public function findById(int $id): ?CompanyAccountPayable
- {
- return CompanyAccountPayable::find($id);
- }
- public function createManual(array $data): CompanyAccountPayable
- {
- return CompanyAccountPayable::create([
- 'origin' => CompanyAccountPayable::ORIGIN_MANUAL,
- 'financial_plan_account_id' => $data['financial_plan_account_id'] ?? null,
- 'history' => $data['history'],
- 'value' => $data['value'],
- 'due_date' => $data['due_date'],
- 'obs' => $data['obs'] ?? null,
- 'paid_value' => 0,
- 'discount' => 0,
- 'fine' => 0,
- 'status' => 'pending',
- ])->load('planAccount:id,code,description');
- }
- public function settle(CompanyAccountPayable $payable, array $data): CompanyAccountPayable
- {
- if ($payable->status === 'paid') {
- throw ValidationException::withMessages(['status' => 'Esta conta já está paga.']);
- }
- if ($payable->status === 'cancelled') {
- throw ValidationException::withMessages([
- 'status' => 'Esta conta está cancelada e não pode receber baixa.',
- ]);
- }
- $discount = isset($data['discount']) ? (float) $data['discount'] : (float) $payable->discount;
- $fine = isset($data['fine']) ? (float) $data['fine'] : (float) $payable->fine;
- $paidValue = isset($data['paid_value'])
- ? (float) $data['paid_value']
- : round((float) $payable->value - $discount + $fine, 2);
- $payable->update([
- 'status' => 'paid',
- 'discount' => $discount,
- 'fine' => $fine,
- 'paid_value' => $paidValue,
- 'payment_date' => $data['payment_date'] ?? Carbon::today()->format('Y-m-d'),
- ]);
- return $payable->fresh('planAccount:id,code,description');
- }
- public function reopen(CompanyAccountPayable $payable): CompanyAccountPayable
- {
- throw ValidationException::withMessages([
- 'status' => 'Uma conta paga não pode voltar para um status anterior.',
- ]);
- }
- }
|