Statistics: member stats independent of fee type

This commit is contained in:
Moritz 2026-02-12 17:42:30 +01:00 committed by moritz
parent 98af2b77ee
commit 490dced8c8
3 changed files with 272 additions and 147 deletions

View file

@ -121,9 +121,14 @@ defmodule Mv.Statistics do
MembershipFeeCycle MembershipFeeCycle
|> Ash.Query.filter(expr(cycle_start >= ^first_day and cycle_start <= ^last_day)) |> Ash.Query.filter(expr(cycle_start >= ^first_day and cycle_start <= ^last_day))
opts_with_domain = Keyword.put(opts, :domain, MembershipFees) query = maybe_filter_by_fee_type(query, opts)
# Only pass actor and domain to Ash.read; fee_type_id is only for our filter above
opts_for_read =
opts
|> Keyword.drop([:fee_type_id])
|> Keyword.put(:domain, MembershipFees)
case Ash.read(query, opts_with_domain) do case Ash.read(query, opts_for_read) do
{:ok, cycles} -> cycle_totals_from_cycles(cycles) {:ok, cycles} -> cycle_totals_from_cycles(cycles)
{:error, _} -> zero_cycle_totals() {:error, _} -> zero_cycle_totals()
end end
@ -158,6 +163,24 @@ defmodule Mv.Statistics do
} }
end end
defp maybe_filter_by_fee_type(query, opts) do
case Keyword.get(opts, :fee_type_id) do
nil ->
query
id when is_binary(id) ->
# Only apply filter for valid UUID strings (e.g. from form/URL)
if Ecto.UUID.cast(id) != :error do
Ash.Query.filter(query, expr(membership_fee_type_id == ^id))
else
query
end
id ->
Ash.Query.filter(query, expr(membership_fee_type_id == ^id))
end
end
@doc """ @doc """
Returns the sum of amount for all cycles with status :unpaid. Returns the sum of amount for all cycles with status :unpaid.
""" """
@ -167,9 +190,14 @@ defmodule Mv.Statistics do
MembershipFeeCycle MembershipFeeCycle
|> Ash.Query.filter(expr(status == :unpaid)) |> Ash.Query.filter(expr(status == :unpaid))
opts_with_domain = Keyword.put(opts, :domain, MembershipFees) query = maybe_filter_by_fee_type(query, opts)
case Ash.read(query, opts_with_domain) do opts_for_read =
opts
|> Keyword.drop([:fee_type_id])
|> Keyword.put(:domain, MembershipFees)
case Ash.read(query, opts_for_read) do
{:ok, cycles} -> {:ok, cycles} ->
Enum.reduce(cycles, Decimal.new(0), fn c, acc -> Decimal.add(acc, c.amount) end) Enum.reduce(cycles, Decimal.new(0), fn c, acc -> Decimal.add(acc, c.amount) end)

View file

@ -8,23 +8,49 @@ defmodule MvWeb.StatisticsLive do
import MvWeb.LiveHelpers, only: [current_actor: 1] import MvWeb.LiveHelpers, only: [current_actor: 1]
alias Mv.Statistics alias Mv.Statistics
alias Mv.MembershipFees.MembershipFeeType
alias MvWeb.Helpers.MembershipFeeHelpers alias MvWeb.Helpers.MembershipFeeHelpers
@impl true @impl true
def mount(_params, _session, socket) do def mount(_params, _session, socket) do
socket = socket =
socket socket
|> load_statistics()
|> assign(:page_title, gettext("Statistics")) |> assign(:page_title, gettext("Statistics"))
|> assign(:selected_fee_type_id, nil)
|> load_fee_types()
|> load_statistics()
{:ok, socket} {:ok, socket}
end end
@impl true @impl true
def handle_params(_params, _uri, socket) do def handle_params(params, uri, socket) do
{:noreply, load_statistics(socket)} # Query params: after push_patch, params may not include query string in some cases;
# always derive from URI as well so fee_type_id is reliable.
uri_query = if uri, do: URI.decode_query(URI.parse(uri).query || ""), else: %{}
fee_type_id = params["fee_type_id"] || uri_query["fee_type_id"]
fee_type_id = normalize_fee_type_id(fee_type_id)
socket =
socket
|> assign(:selected_fee_type_id, fee_type_id)
|> load_statistics()
{:noreply, socket}
end end
defp normalize_fee_type_id(nil), do: nil
defp normalize_fee_type_id(""), do: nil
defp normalize_fee_type_id(id) when is_binary(id) do
case String.trim(id) do
"" -> nil
trimmed -> trimmed
end
end
defp normalize_fee_type_id(_), do: nil
@impl true @impl true
def render(assigns) do def render(assigns) do
~H""" ~H"""
@ -34,94 +60,104 @@ defmodule MvWeb.StatisticsLive do
<:subtitle>{gettext("Overview from first membership to today")}</:subtitle> <:subtitle>{gettext("Overview from first membership to today")}</:subtitle>
</.header> </.header>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8"> <section class="mb-8" aria-labelledby="members-heading">
<div class="card bg-base-200 shadow-md border border-base-300"> <h2 id="members-heading" class="text-xl font-semibold mb-4">{gettext("Members")}</h2>
<div class="card-body p-5"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6">
<h2 class="card-title text-sm font-medium text-base-content/80"> <div class="card bg-base-200 shadow-md border border-base-300">
{gettext("Active members")} <div class="card-body p-5">
</h2> <h3 class="card-title text-sm font-medium text-base-content/80">
<p {gettext("Active members")}
class="text-3xl font-bold tabular-nums" </h3>
aria-label={gettext("Active members") <> ": " <> to_string(@active_count)} <p
> class="text-3xl font-bold tabular-nums"
{@active_count} aria-label={gettext("Active members") <> ": " <> to_string(@active_count)}
</p> >
{@active_count}
</p>
</div>
</div>
<div class="card bg-base-200 shadow-md border border-base-300">
<div class="card-body p-5">
<h3 class="card-title text-sm font-medium text-base-content/80">
{gettext("Inactive members")}
</h3>
<p
class="text-3xl font-bold tabular-nums"
aria-label={gettext("Inactive members") <> ": " <> to_string(@inactive_count)}
>
{@inactive_count}
</p>
</div>
</div> </div>
</div> </div>
<div class="card bg-base-200 shadow-md border border-base-300"> <div class="card bg-base-200 shadow-md border border-base-300">
<div class="card-body p-5"> <div class="card-body">
<h2 class="card-title text-sm font-medium text-base-content/80"> <h3 class="card-title text-lg mb-4">{gettext("Member numbers by year")}</h3>
{gettext("Inactive members")} <p class="text-sm text-base-content/70 mb-4">
</h2> {gettext("From %{first} to %{last} (relevant years with membership data)",
<p first: @years |> List.last() |> to_string(),
class="text-3xl font-bold tabular-nums" last: @years |> List.first() |> to_string()
aria-label={gettext("Inactive members") <> ": " <> to_string(@inactive_count)} )}
>
{@inactive_count}
</p> </p>
<.member_numbers_table joins_exits_by_year={@joins_exits_by_year} />
</div> </div>
</div> </div>
<div class="card bg-base-200 shadow-md border border-base-300">
<div class="card-body p-5">
<h2 class="card-title text-sm font-medium text-base-content/80">
{gettext("Open amount")}
</h2>
<p
class="text-3xl font-bold tabular-nums"
aria-label={gettext("Open amount") <> ": " <> MembershipFeeHelpers.format_currency(@open_amount_total)}
>
{MembershipFeeHelpers.format_currency(@open_amount_total)}
</p>
</div>
</div>
</div>
<section
class="card bg-base-200 shadow-md border border-base-300 mb-8"
aria-labelledby="joins-exits-heading"
>
<div class="card-body">
<h2 id="joins-exits-heading" class="card-title text-lg mb-4">
{gettext("Joins and exits by year")}
</h2>
<p class="text-sm text-base-content/70 mb-4">
{gettext("From %{first} to %{last} (relevant years with membership data)",
first: @years |> List.last() |> to_string(),
last: @years |> List.first() |> to_string()
)}
</p>
<.joins_exits_bars joins_exits_by_year={@joins_exits_by_year} />
</div>
</section> </section>
<section <section class="mb-8" aria-labelledby="contributions-heading">
class="card bg-base-200 shadow-md border border-base-300 mb-8" <h2 id="contributions-heading" class="text-xl font-semibold mb-4">
aria-labelledby="contributions-heading" {gettext("Contributions")}
> </h2>
<div class="card-body"> <div class="flex flex-wrap items-end gap-4 mb-6">
<h2 id="contributions-heading" class="card-title text-lg mb-4"> <div class="flex items-center gap-2">
{gettext("Contributions by year")} <form id="fee-type-form" phx-change="change_fee_type" class="flex items-center gap-2">
</h2> <label for="fee-type-filter" class="text-sm font-medium text-base-content/80">
<div class="flex flex-col gap-8 items-start"> {gettext("Fee type")}:
<div class="w-full"> </label>
<.contributions_bars_by_year <select
contributions_by_year={@contributions_by_year} id="fee-type-filter"
totals_over_all_years={@totals_over_all_years} name="fee_type_id"
/> class="select select-bordered select-sm min-w-[10rem]"
</div> >
<div class="w-full flex flex-col items-center pt-6 mt-2 border-t border-base-300"> <option value="" selected={@selected_fee_type_id in [nil, ""]}>
<h3 class="text-sm font-semibold mb-3">{gettext("All years combined (pie)")}</h3> {gettext("All")}
<.contributions_pie cycle_totals={@totals_over_all_years} /> </option>
<p class="text-xs text-base-content/70 mt-2"> <%= for ft <- @membership_fee_types do %>
<span class="inline-block w-2 h-2 rounded-full bg-success align-middle mr-1"></span> <option
{gettext("Paid")} value={ft.id}
<span class="inline-block w-2 h-2 rounded-full bg-warning align-middle mx-2 mr-1"> selected={to_string(@selected_fee_type_id) == to_string(ft.id)}
</span> >
{gettext("Unpaid")} {ft.name}
<span class="inline-block w-2 h-2 rounded-full bg-base-content/20 align-middle mx-2 mr-1"> </option>
</span> <% end %>
{gettext("Suspended")} </select>
</p> </form>
</div>
</div>
<div class="card bg-base-200 shadow-md border border-base-300">
<div class="card-body">
<h3 class="card-title text-lg mb-4">{gettext("Contributions by year")}</h3>
<div class="flex flex-col gap-8 items-start">
<div class="w-full">
<.contributions_bars_by_year
contributions_by_year={@contributions_by_year}
totals_over_all_years={@totals_over_all_years}
/>
</div>
<div class="w-full flex flex-col items-center pt-6 mt-2 border-t border-base-300">
<h4 class="text-sm font-semibold mb-3">{gettext("All years combined (pie)")}</h4>
<.contributions_pie cycle_totals={@totals_over_all_years} />
<p class="text-xs text-base-content/70 mt-2">
<span class="inline-block w-2 h-2 rounded-full bg-success align-middle mr-1"></span>
{gettext("Paid")}
<span class="inline-block w-2 h-2 rounded-full bg-warning align-middle mx-2 mr-1">
</span>
{gettext("Unpaid")}
<span class="inline-block w-2 h-2 rounded-full bg-base-content/20 align-middle mx-2 mr-1">
</span>
{gettext("Suspended")}
</p>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -130,70 +166,117 @@ defmodule MvWeb.StatisticsLive do
""" """
end end
@impl true
def handle_event("change_fee_type", %{"fee_type_id" => ""}, socket) do
{:noreply, push_patch(socket, to: ~p"/statistics")}
end
def handle_event("change_fee_type", %{"fee_type_id" => id}, socket) do
{:noreply, push_patch(socket, to: ~p"/statistics?fee_type_id=#{id}")}
end
attr :joins_exits_by_year, :list, required: true attr :joins_exits_by_year, :list, required: true
defp joins_exits_bars(assigns) do defp member_numbers_table(assigns) do
join_values = Enum.map(assigns.joins_exits_by_year, & &1.joins) rows = assigns.joins_exits_by_year
exit_values = Enum.map(assigns.joins_exits_by_year, & &1.exits) total_activity = Enum.map(rows, fn r -> r.joins + r.exits end)
max_joins = max((join_values != [] && Enum.max(join_values)) || 0, 1) max_total = (total_activity != [] && Enum.max(total_activity)) || 1
max_exits = max((exit_values != [] && Enum.max(exit_values)) || 0, 1)
assigns = assign(assigns, :max_joins, max_joins) rows_with_pct =
assigns = assign(assigns, :max_exits, max_exits) Enum.map(rows, fn row ->
sum = row.joins + row.exits
bar_pct =
if max_total > 0 and sum > 0, do: Float.round(sum / max_total * 100, 1), else: 0
seg_scale = max(sum, 1)
joins_pct = row.joins / seg_scale * 100
exits_pct = row.exits / seg_scale * 100
%{
year: row.year,
joins: row.joins,
exits: row.exits,
bar_pct: bar_pct,
joins_pct: Float.round(joins_pct, 1),
exits_pct: Float.round(exits_pct, 1)
}
end)
assigns = assign(assigns, :rows, rows_with_pct)
~H""" ~H"""
<div <div
class="space-y-4" class="overflow-x-auto"
role="img" role="img"
aria-label={gettext("Joins and exits by year as horizontal bar chart")} aria-label={gettext("Member numbers by year as table with bars")}
> >
<div class="flex gap-4 text-sm mb-2"> <table class="table table-sm w-full">
<span class="flex items-center gap-2"> <thead class="bg-base-300">
<span class="inline-block w-4 h-3 rounded bg-success" aria-hidden="true"></span> <tr>
{gettext("Joins")} <th scope="col" class="text-base-content font-semibold w-20">{gettext("Year")}</th>
</span> <th scope="col" class="text-base-content font-semibold">{gettext("Joins")}</th>
<span class="flex items-center gap-2"> <th scope="col" class="text-base-content font-semibold">{gettext("Exits")}</th>
<span class="inline-block w-4 h-3 rounded bg-error" aria-hidden="true"></span> </tr>
{gettext("Exits")} </thead>
</span> <tbody>
</div> <%= for row <- @rows do %>
<div class="space-y-3"> <tr>
<%= for item <- @joins_exits_by_year do %> <td
<div class="flex flex-col sm:flex-row sm:items-center gap-2"> rowspan="2"
<span class="w-12 font-mono text-sm shrink-0" id={"year-#{item.year}"}>{item.year}</span> class="font-mono align-middle border-b-0"
<div class="flex-1 min-w-0 space-y-1"> >
<div class="flex items-center gap-2"> {row.year}
<span class="text-xs w-8 shrink-0">{item.joins}</span> </td>
<div <td colspan="2" class="align-top p-1 pb-0 border-b-0">
class="h-6 bg-base-300 rounded overflow-hidden flex min-w-[4rem]" <div class="h-6 rounded overflow-hidden bg-base-300 relative min-w-[4rem]">
role="presentation"
>
<div <div
class="h-full bg-success transition-all min-w-[2px]" class="flex h-full absolute left-0 top-0 bottom-0 min-w-0 rounded"
style={"width: #{max(0, min(100, Float.round(item.joins / @max_joins * 100, 1)))}%"} style={"width: #{max(0, row.bar_pct)}%"}
aria-hidden="true"
> >
<div
class="h-full bg-success min-w-0 rounded-l"
style={"width: #{row.joins_pct}%"}
title={gettext("Joins")}
>
</div>
<div
class="h-full bg-error min-w-0 rounded-r"
style={"width: #{row.exits_pct}%"}
title={gettext("Exits")}
>
</div>
</div> </div>
</div> </div>
</div> </td>
<div class="flex items-center gap-2"> </tr>
<span class="text-xs w-8 shrink-0">{item.exits}</span> <tr>
<div <td class="align-middle text-xs font-mono text-base-content whitespace-nowrap pt-0">
class="h-6 bg-base-300 rounded overflow-hidden flex min-w-[4rem]" <span class="inline-flex items-center gap-1.5">
role="presentation" {row.joins}
> <span
<div class="inline-block w-2 h-2 rounded-full bg-success shrink-0"
class="h-full bg-error transition-all min-w-[2px]"
style={"width: #{max(0, min(100, Float.round(item.exits / @max_exits * 100, 1)))}%"}
aria-hidden="true" aria-hidden="true"
title={gettext("Joins")}
> >
</div> </span>
</div> </span>
</div> </td>
</div> <td class="align-middle text-xs font-mono text-base-content whitespace-nowrap pt-0">
</div> <span class="inline-flex items-center gap-1.5">
<% end %> {row.exits}
</div> <span
class="inline-block w-2 h-2 rounded-full bg-error shrink-0"
aria-hidden="true"
title={gettext("Exits")}
>
</span>
</span>
</td>
</tr>
<% end %>
</tbody>
</table>
</div> </div>
""" """
end end
@ -426,26 +509,40 @@ defmodule MvWeb.StatisticsLive do
""" """
end end
defp load_fee_types(socket) do
actor = current_actor(socket)
fee_types =
MembershipFeeType
|> Ash.Query.sort(name: :asc)
|> Ash.read!(domain: Mv.MembershipFees, actor: actor)
assign(socket, :membership_fee_types, fee_types)
end
defp load_statistics(socket) do defp load_statistics(socket) do
actor = current_actor(socket) actor = current_actor(socket)
opts = [actor: actor] fee_type_id = socket.assigns[:selected_fee_type_id]
# Member stats must never depend on fee type (only contributions do)
opts_member = [actor: actor]
opts_contributions =
[actor: actor] ++ if fee_type_id, do: [fee_type_id: fee_type_id], else: []
current_year = Date.utc_today().year current_year = Date.utc_today().year
first_year = Statistics.first_join_year(opts) || current_year first_year = Statistics.first_join_year(opts_member) || current_year
years = first_year..current_year |> Enum.to_list() |> Enum.reverse() years = first_year..current_year |> Enum.to_list() |> Enum.reverse()
active_count = Statistics.active_member_count(opts) active_count = Statistics.active_member_count(opts_member)
inactive_count = Statistics.inactive_member_count(opts) inactive_count = Statistics.inactive_member_count(opts_member)
open_amount_total = Statistics.open_amount_total(opts) joins_exits_by_year = build_joins_exits_by_year(years, opts_member)
joins_exits_by_year = build_joins_exits_by_year(years, opts) contributions_by_year = build_contributions_by_year(years, opts_contributions)
contributions_by_year = build_contributions_by_year(years, opts)
totals_over_all_years = sum_cycle_totals(contributions_by_year) totals_over_all_years = sum_cycle_totals(contributions_by_year)
assign(socket, assign(socket,
years: years, years: years,
active_count: active_count, active_count: active_count,
inactive_count: inactive_count, inactive_count: inactive_count,
open_amount_total: open_amount_total,
joins_exits_by_year: joins_exits_by_year, joins_exits_by_year: joins_exits_by_year,
contributions_by_year: contributions_by_year, contributions_by_year: contributions_by_year,
totals_over_all_years: totals_over_all_years totals_over_all_years: totals_over_all_years

View file

@ -15,9 +15,9 @@ defmodule MvWeb.StatisticsLiveTest do
assert html =~ "Statistics" assert html =~ "Statistics"
assert html =~ "Active members" assert html =~ "Active members"
assert html =~ "Open amount" assert html =~ "Unpaid"
assert html =~ "Contributions by year" assert html =~ "Contributions by year"
assert html =~ "Joins and exits by year" assert html =~ "Member numbers by year"
end end
test "page shows overview of all relevant years without year selector", %{conn: conn} do test "page shows overview of all relevant years without year selector", %{conn: conn} do