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'); } }