refactor: reduce complexity in global pricing validation

Extract validation logic into separate functions to reduce:
- Cyclomatic complexity from 12 to acceptable levels
- Nesting depth from 3 to 2

Improves code maintainability and passes Credo checks.
This commit is contained in:
Graham McIntire 2026-03-06 14:44:33 -06:00
parent c110832b42
commit 100245975a
No known key found for this signature in database
2 changed files with 41 additions and 36 deletions

View file

@ -211,47 +211,52 @@ defmodule ToweropsWeb.Admin.OrgLive.Index do
end
defp validate_global_pricing_params(params) do
errors = []
[]
|> validate_free_devices(params)
|> validate_price_per_device(params)
end
errors =
case Map.get(params, "default_free_devices") do
nil ->
errors
defp validate_free_devices(errors, params) do
case Map.get(params, "default_free_devices") do
nil -> errors
value -> validate_free_devices_value(errors, value)
end
end
value ->
case Integer.parse(value) do
{int, _} when int > 0 and int < 10_000 ->
errors
defp validate_free_devices_value(errors, value) do
case Integer.parse(value) do
{int, _} when int > 0 and int < 10_000 ->
errors
_ ->
[
{:default_free_devices, {"must be greater than 0 and less than 10,000", []}}
| errors
]
end
end
_ ->
[{:default_free_devices, {"must be greater than 0 and less than 10,000", []}} | errors]
end
end
errors =
case Map.get(params, "default_price_per_device") do
nil ->
errors
defp validate_price_per_device(errors, params) do
case Map.get(params, "default_price_per_device") do
nil -> errors
value -> validate_price_per_device_value(errors, value)
end
end
value ->
case Decimal.parse(value) do
{decimal, _} ->
if Decimal.compare(decimal, "0.01") in [:gt, :eq] and
Decimal.compare(decimal, "999.99") in [:lt, :eq] do
errors
else
[{:default_price_per_device, {"must be between 0.01 and 999.99", []}} | errors]
end
defp validate_price_per_device_value(errors, value) do
case Decimal.parse(value) do
{decimal, _} -> validate_price_range(errors, decimal)
:error -> [{:default_price_per_device, {"must be a valid decimal", []}} | errors]
end
end
:error ->
[{:default_price_per_device, {"must be a valid decimal", []}} | errors]
end
end
defp validate_price_range(errors, decimal) do
valid_range? =
Decimal.compare(decimal, "0.01") in [:gt, :eq] and
Decimal.compare(decimal, "999.99") in [:lt, :eq]
errors
if valid_range? do
errors
else
[{:default_price_per_device, {"must be between 0.01 and 999.99", []}} | errors]
end
end
defp count_active_subscriptions do

View file

@ -4,8 +4,8 @@
<h1 class="text-2xl font-bold text-gray-900 dark:text-white">{t("All Organizations")}</h1>
<p class="text-gray-600 dark:text-gray-400">{t_admin("Manage organizations")}</p>
</div>
<!-- Global Billing Defaults Card -->
<!-- Global Billing Defaults Card -->
<div
class="rounded-lg border border-slate-200 bg-white p-6 dark:border-slate-700 dark:bg-slate-800"
data-test="global-defaults-card"