CompanyAccountPayableService.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Services;
  3. use App\Models\CompanyAccountPayable;
  4. use Carbon\Carbon;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Validation\ValidationException;
  7. /**
  8. * Contas a Pagar da matriz (franqueadora). Lançamentos manuais com baixa manual.
  9. */
  10. class CompanyAccountPayableService
  11. {
  12. public function list(array $filters = []): Collection
  13. {
  14. return CompanyAccountPayable::with('planAccount:id,code,description')
  15. ->when(
  16. isset($filters['status']),
  17. fn ($q) => $q->where('status', $filters['status']),
  18. )
  19. ->orderBy('due_date')
  20. ->get();
  21. }
  22. public function findById(int $id): ?CompanyAccountPayable
  23. {
  24. return CompanyAccountPayable::find($id);
  25. }
  26. public function createManual(array $data): CompanyAccountPayable
  27. {
  28. return CompanyAccountPayable::create([
  29. 'origin' => CompanyAccountPayable::ORIGIN_MANUAL,
  30. 'financial_plan_account_id' => $data['financial_plan_account_id'] ?? null,
  31. 'history' => $data['history'],
  32. 'value' => $data['value'],
  33. 'due_date' => $data['due_date'],
  34. 'obs' => $data['obs'] ?? null,
  35. 'paid_value' => 0,
  36. 'discount' => 0,
  37. 'fine' => 0,
  38. 'status' => 'pending',
  39. ])->load('planAccount:id,code,description');
  40. }
  41. public function settle(CompanyAccountPayable $payable, array $data): CompanyAccountPayable
  42. {
  43. if ($payable->status === 'paid') {
  44. throw ValidationException::withMessages(['status' => 'Esta conta já está paga.']);
  45. }
  46. if ($payable->status === 'cancelled') {
  47. throw ValidationException::withMessages([
  48. 'status' => 'Esta conta está cancelada e não pode receber baixa.',
  49. ]);
  50. }
  51. $discount = isset($data['discount']) ? (float) $data['discount'] : (float) $payable->discount;
  52. $fine = isset($data['fine']) ? (float) $data['fine'] : (float) $payable->fine;
  53. $paidValue = isset($data['paid_value'])
  54. ? (float) $data['paid_value']
  55. : round((float) $payable->value - $discount + $fine, 2);
  56. $payable->update([
  57. 'status' => 'paid',
  58. 'discount' => $discount,
  59. 'fine' => $fine,
  60. 'paid_value' => $paidValue,
  61. 'payment_date' => $data['payment_date'] ?? Carbon::today()->format('Y-m-d'),
  62. ]);
  63. return $payable->fresh('planAccount:id,code,description');
  64. }
  65. public function reopen(CompanyAccountPayable $payable): CompanyAccountPayable
  66. {
  67. throw ValidationException::withMessages([
  68. 'status' => 'Uma conta paga não pode voltar para um status anterior.',
  69. ]);
  70. }
  71. }