| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?php
- namespace App\Services;
- use App\Models\CompanyAccountReceivable;
- use Carbon\Carbon;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Validation\ValidationException;
- /**
- * Contas a Receber avulsas da matriz (franqueadora). Baixa manual.
- */
- class CompanyAccountReceivableService
- {
- public function list(array $filters = []): Collection
- {
- return CompanyAccountReceivable::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): ?CompanyAccountReceivable
- {
- return CompanyAccountReceivable::find($id);
- }
- public function createManual(array $data): CompanyAccountReceivable
- {
- return CompanyAccountReceivable::create([
- 'origin' => CompanyAccountReceivable::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(CompanyAccountReceivable $receivable, array $data): CompanyAccountReceivable
- {
- if ($receivable->status === 'paid') {
- throw ValidationException::withMessages(['status' => 'Este recebível já está pago.']);
- }
- if ($receivable->status === 'cancelled') {
- throw ValidationException::withMessages([
- 'status' => 'Este recebível está cancelado e não pode receber baixa.',
- ]);
- }
- $discount = isset($data['discount']) ? (float) $data['discount'] : (float) $receivable->discount;
- $fine = isset($data['fine']) ? (float) $data['fine'] : (float) $receivable->fine;
- $paidValue = isset($data['paid_value'])
- ? (float) $data['paid_value']
- : round((float) $receivable->value - $discount + $fine, 2);
- $receivable->update([
- 'status' => 'paid',
- 'discount' => $discount,
- 'fine' => $fine,
- 'paid_value' => $paidValue,
- 'payment_date' => $data['payment_date'] ?? Carbon::today()->format('Y-m-d'),
- ]);
- return $receivable->fresh('planAccount:id,code,description');
- }
- public function reopen(CompanyAccountReceivable $receivable): CompanyAccountReceivable
- {
- if ($receivable->status !== 'paid') {
- throw ValidationException::withMessages([
- 'status' => 'Só é possível reabrir recebíveis que estão pagos.',
- ]);
- }
- $receivable->update([
- 'status' => 'pending',
- 'paid_value' => 0,
- 'payment_date' => null,
- ]);
- return $receivable->fresh('planAccount:id,code,description');
- }
- }
|