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 { if ($payable->status !== 'paid') { throw ValidationException::withMessages([ 'status' => 'Só é possível reabrir contas que estão pagas.', ]); } $payable->update([ 'status' => 'pending', 'paid_value' => 0, 'payment_date' => null, ]); return $payable->fresh('planAccount:id,code,description'); } }