The personal finance app for everyone (by everyone)
Ruby
Add Hosted usage overview and daily web preview event (#3939)
Juan José Mata2f17d7c6ad4c
diff --git a/app/controllers/admin/system_health_controller.rb b/app/controllers/admin/system_health_controller.rbindex fd548ecfec..0be21768f3 100644--- a/app/controllers/admin/system_health_controller.rb+++ b/app/controllers/admin/system_health_controller.rb@@ -3,6 +3,8 @@module Adminclass SystemHealthController < Admin::BaseControllerbefore_action :require_hosted_push, only: :send_test_push+ before_action :require_hosted_usage, only: :hosted_usage+ skip_before_action :sync_family, only: :hosted_usage# Bypass the per-request memo / cross-request cache that the layout# banner uses. An operator landing on this page (often right after@@ -10,7 +12,9 @@ module Admin# snapshot up to `SidekiqHealth::CACHE_TTL` old. Also makes the page# work in managed mode, where `current_sidekiq_health` is nil.def show+ @hosted_usage_available = hosted_usage_available?tabs = %w[background_jobs ai]+ tabs << "hosted_usage" if @hosted_usage_available@active_tab = params[:tab].presence_in(tabs) || "background_jobs"if Apns::Client.hosted?@push_notification_test = PushNotificationTest.new(Current.user)@@ -31,6 +35,12 @@ module Adminrender layout: falseend+ # Keep the bounded database snapshot out of the initial health-page load.+ def hosted_usage+ @hosted_usage = HostedUsage.new+ render layout: false+ end+# Queues an asynchronous worker-side verification (see# WorkerAiHealthCheckJob) and returns immediately -- the result appears# in the AI status tab once whichever worker process dequeues it@@ -47,6 +57,19 @@ module Adminendprivate+ def require_hosted_usage+ head :not_found unless hosted_usage_available?+ end++ def hosted_usage_available?+ # Rails may derive request.host from X-Forwarded-Host. Require the+ # original Host header too, so another deployment cannot expose this+ # report through a forwarded-host override.+ original_host = request.get_header("HTTP_HOST").to_s+ original_host.match?(/\A#{Regexp.escape(request.host)}(?::[0-9]+)?\z/) &&+ HostedUsage.available?(request_host: request.host)+ end+def require_hosted_pushhead :not_found unless Apns::Client.hosted?enddiff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rbindex 384b7ae6ab..0e31860588 100644--- a/app/controllers/admin/users_controller.rb+++ b/app/controllers/admin/users_controller.rb@@ -43,10 +43,6 @@ module Admin@families = Family.order(:name, :created_at)@unused_families = Family.left_joins(:users).where(users: { id: nil }).order(:name, :created_at)- @trials_expiring_in_7_days = Subscription- .where(status: :trialing)- .where(trial_ends_at: Time.current..7.days.from_now)- .count@sso_identity_blocks = SsoIdentityBlock.order(created_at: :desc)# Used by the view to hide the "remove" action for the sole remainingdiff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rbindex 65ed5888bf..06645dbd40 100644--- a/app/controllers/application_controller.rb+++ b/app/controllers/application_controller.rb@@ -5,6 +5,7 @@ class ApplicationController < ActionController::BasePreviewGateableinclude Pundit::Authorizationinclude CodespacesForgeryProtection+ include DailyWebUsageTrackinginclude Pagy::Backenddiff --git a/app/controllers/concerns/daily_web_usage_tracking.rb b/app/controllers/concerns/daily_web_usage_tracking.rbnew file mode 100644index 0000000000..7608b43c7e--- /dev/null+++ b/app/controllers/concerns/daily_web_usage_tracking.rb@@ -0,0 +1,43 @@+module DailyWebUsageTracking+ extend ActiveSupport::Concern++ included do+ after_action :capture_daily_web_usage+ end++ private+ def capture_daily_web_usage+ return unless Current.user && request.get? && response.status == 200 && response.media_type == "text/html"+ return if controller_path.start_with?("api/")+ return if request.xhr? || turbo_frame_request?+ return if %w[Purpose Sec-Purpose X-Sec-Purpose].any? { |header| request.headers[header].to_s.match?(/prefetch|prerender/i) }+ return unless helpers.posthog_enabled? && Rails.configuration.x.posthog.feedback_enabled && $posthog_feedback+ return if Rails.cache.is_a?(ActiveSupport::Cache::NullStore)++ # A daily pseudonym supports counting without sending an account ID or+ # creating a lasting person profile. Resolve the configured family zone+ # after authentication, rather than relying on callback ordering.+ day = Time.current.in_time_zone(resolved_timezone).to_date+ key = Rails.application.key_generator.generate_key("daily-web-usage")+ daily_id = OpenSSL::HMAC.hexdigest("SHA256", key, "#{Current.user.id}:#{day.iso8601}")++ # Atomic in the shared Redis cache: requests from different sessions or+ # web workers share one attempt per user/day. Cache loss can permit repeats.+ return unless Rails.cache.write([ "daily-web-usage", daily_id ], true, expires_in: 2.days, unless_exist: true)++ $posthog_feedback.capture(+ distinct_id: daily_id,+ event: "web_ui_served_daily",+ properties: {+ preview_features_enabled: Current.user.preview_features_enabled?,+ sure_version: Sure.version.to_s,+ "$process_person_profile" => false,+ "$geoip_disable" => false,+ "$ip" => request.remote_ip+ }+ )+ rescue StandardError => error+ # Analytics is best effort; a cache/SDK failure must not fail the UI.+ Rails.logger.debug("Daily web usage capture skipped: #{error.class}")+ end+enddiff --git a/app/models/hosted_usage.rb b/app/models/hosted_usage.rbnew file mode 100644index 0000000000..f5ad19281f--- /dev/null+++ b/app/models/hosted_usage.rb@@ -0,0 +1,142 @@+# frozen_string_literal: true++# A retained-data snapshot for the two project-operated installations. It does+# not contact Stripe, run cleanup, enqueue jobs, or reconstruct deleted history.+class HostedUsage+ HOSTS = %w[app.sure.am demo.sure.am].freeze+ ROW_LIMIT = 100++ Trial = Data.define(+ :family_id, :family_name, :recorded_at, :trial_ends_at, :status,+ :member_count, :retained_sessions_count, :sessions_created_in_window_count,+ :latest_session_created_at, :cleanup_eligible, :synthetic_demo+ )+ CleanupCandidate = Data.define(+ :family_id, :family_name, :status, :trial_ends_at, :reason, :synthetic_demo+ )++ # Request headers alone cannot enable this feature on another installation.+ # Do not accept URLs, ports, suffix matches, forwarded values, or wildcards+ # from APP_DOMAIN: it must be the exact trusted deployment hostname.+ def self.available?(request_host:)+ configured_host = ENV["APP_DOMAIN"]+ HOSTS.include?(configured_host) && request_host == configured_host+ end++ attr_reader :as_of, :window_start, :expiring_window_end++ def initialize+ @as_of = Time.current+ @window_start = 30.days.ago(as_of)+ @expiring_window_end = 7.days.from_now(as_of)+ end++ def row_limit+ ROW_LIMIT+ end++ def cleanup_enabled?+ Rails.application.config.app_mode.managed?+ end++ def summary+ snapshot.fetch(:summary)+ end++ def trials+ snapshot.fetch(:trials)+ end++ def cleanup_candidates+ snapshot.fetch(:cleanup_candidates)+ end++ def supporter_status_counts+ snapshot.fetch(:supporter_status_counts)+ end++ private+ def snapshot+ @snapshot ||= ActiveRecord::Base.while_preventing_writes { build_snapshot }+ end++ def build_snapshot+ # Conversion updates the same row. Keep converted trials in this cohort,+ # but label created_at as the retained record date, not a paid-start date+ # or a durable historical trial-start event.+ trial_scope = Subscription.joins(:family)+ .where.not(trial_ends_at: nil)+ .where(created_at: window_start..as_of)+ cleanup_scope = Family.inactive_trial_for_cleanup+ supporter_scope = Subscription.joins(:family)+ .where("subscriptions.stripe_id ~ ?", "^sub_[A-Za-z0-9]+$")+ .where("families.stripe_customer_id ~ ?", "^cus_[A-Za-z0-9]+$")++ {+ summary: {+ trial_households_count: trial_scope.count,+ trial_members_count: User.where(family_id: trial_scope.select(:family_id)).count,+ cleanup_eligible_count: cleanup_scope.count,+ active_supporter_households_count: supporter_scope.where(status: :active).distinct.count(:family_id),+ supporter_subscription_count: supporter_scope.count,+ trials_expiring_soon_count: Subscription.where(status: :trialing)+ .where(trial_ends_at: as_of..expiring_window_end).count+ },+ trials: trial_rows(trial_scope, cleanup_scope),+ cleanup_candidates: cleanup_rows(cleanup_scope),+ supporter_status_counts: status_counts(supporter_scope)+ }+ end++ def status_counts(scope)+ counts = Subscription.statuses.keys.index_with(0)+ scope.group(:status).count.each do |status, count|+ key = counts.key?(status) ? status : "unknown"+ counts[key] = counts.fetch(key, 0) + count+ end+ counts+ end++ def trial_rows(scope, cleanup_scope)+ rows = scope.order(created_at: :desc, id: :desc).limit(row_limit).pluck(+ :family_id, "families.name", "subscriptions.created_at",+ :trial_ends_at, :status, :stripe_id+ )+ family_ids = rows.map(&:first)+ return [] if family_ids.empty?++ members = User.where(family_id: family_ids).group(:family_id).count+ # Match authentication eligibility for enabled users, but do not claim+ # these retained login credentials represent people currently online.+ sessions = Session.joins(:user).where(users: { family_id: family_ids, active: true })+ retained = sessions.group("users.family_id").count+ recent = sessions.where(created_at: window_start..as_of).group("users.family_id").count+ latest = sessions.group("users.family_id").maximum("sessions.created_at")+ eligible = cleanup_scope.where(id: family_ids).pluck(:id).to_set++ rows.map do |family_id, family_name, created_at, trial_ends_at, status, stripe_id|+ Trial.new(+ family_id:, family_name:, recorded_at: created_at, trial_ends_at:, status:,+ member_count: members.fetch(family_id, 0),+ retained_sessions_count: retained.fetch(family_id, 0),+ sessions_created_in_window_count: recent.fetch(family_id, 0),+ latest_session_created_at: latest[family_id],+ cleanup_eligible: eligible.include?(family_id),+ synthetic_demo: stripe_id == Subscription::DEMO_STRIPE_ID+ )+ end+ end++ def cleanup_rows(scope)+ scope.left_joins(:subscription).order(created_at: :asc, id: :asc).limit(row_limit).pluck(+ "families.id", "families.name", "subscriptions.id",+ "subscriptions.status", "subscriptions.trial_ends_at", "subscriptions.stripe_id"+ ).map do |family_id, family_name, subscription_id, status, trial_ends_at, stripe_id|+ CleanupCandidate.new(+ family_id:, family_name:, status:, trial_ends_at:,+ reason: subscription_id ? :expired_trial_grace_elapsed : :no_subscription_grace_elapsed,+ synthetic_demo: stripe_id == Subscription::DEMO_STRIPE_ID+ )+ end+ end+enddiff --git a/app/views/admin/system_health/_hosted_usage_household.html.erb b/app/views/admin/system_health/_hosted_usage_household.html.erbnew file mode 100644index 0000000000..5689717fb1--- /dev/null+++ b/app/views/admin/system_health/_hosted_usage_household.html.erb@@ -0,0 +1,4 @@+<span class="font-mono text-xs"><%= row.family_id %></span>+<% if row.synthetic_demo %>+ <%= render DS::Pill.new(label: t("admin.system_health.hosted_usage.synthetic_demo"), tone: :warning, marker: false) %>+<% end %>diff --git a/app/views/admin/system_health/hosted_usage.html.erb b/app/views/admin/system_health/hosted_usage.html.erbnew file mode 100644index 0000000000..0cc3a47c52--- /dev/null+++ b/app/views/admin/system_health/hosted_usage.html.erb@@ -0,0 +1,89 @@+<%= turbo_frame_tag "hosted_usage" do %>+ <div class="space-y-4" data-testid="hosted-usage-report">+ <%= render DS::Card.new(class: "gap-4") do %>+ <div>+ <h2 class="text-lg font-semibold text-primary"><%= t(".title") %></h2>+ <p class="mt-1 text-sm text-secondary"><%= t(".snapshot", time: l(@hosted_usage.as_of, format: :long)) %></p>+ </div>+ <dl class="grid grid-cols-1 xl:grid-cols-2 gap-x-8 gap-y-4">+ <% @hosted_usage.summary.each do |metric, count| %>+ <%= render DS::DetailRow.new(+ label: t(".summary.#{metric}"), value: number_with_delimiter(count),+ class: "[&>dt]:min-w-0 [&>dt]:shrink", value_class: "font-medium tabular-nums shrink-0",+ data: { testid: "hosted-usage-#{metric}" }+ ) %>+ <% end %>+ </dl>+ <p class="text-sm text-secondary"><%= t(".summary_help") %></p>+ <% end %>++ <%= render DS::Alert.new(title: t(".limitations_title"), message: t(".limitations"), variant: :info) %>++ <%= render DS::Card.new(class: "gap-4", data: { testid: "hosted-usage-trials" }) do %>+ <div>+ <h2 class="text-lg font-semibold text-primary"><%= t(".trials.title") %></h2>+ <p class="mt-1 text-sm text-secondary"><%= t(".trials.description", date: l(@hosted_usage.window_start.to_date, format: :long), limit: @hosted_usage.row_limit) %></p>+ <p class="mt-1 text-sm text-secondary"><%= t(".trials.sessions_help") %></p>+ </div>+ <% if @hosted_usage.trials.empty? %>+ <%= render DS::EmptyState.new(icon: "users", title: t(".trials.empty")) %>+ <% else %>+ <%= render DS::Table.new(rows: @hosted_usage.trials, inset: true, label: t(".trials.title")) do |table| %>+ <% table.with_column(t(".columns.household")) do |trial| %>+ <%= render "hosted_usage_household", row: trial %>+ <% end %>+ <% table.with_column(t(".columns.recorded_at")) { |trial| l(trial.recorded_at.to_date, format: :long) } %>+ <% table.with_column(t(".columns.trial_ends_at")) { |trial| l(trial.trial_ends_at.to_date, format: :long) } %>+ <% table.with_column(t(".columns.status")) { |trial| t(".statuses.#{trial.status || :unknown}") } %>+ <% table.with_column(t(".columns.members"), numeric: true) { |trial| number_with_delimiter(trial.member_count) } %>+ <% table.with_column(t(".columns.retained_sessions"), numeric: true) { |trial| number_with_delimiter(trial.retained_sessions_count) } %>+ <% table.with_column(t(".columns.recent_sessions"), numeric: true) { |trial| number_with_delimiter(trial.sessions_created_in_window_count) } %>+ <% table.with_column(t(".columns.latest_session")) do |trial| %>+ <%= trial.latest_session_created_at ? l(trial.latest_session_created_at, format: :long) : t(".not_recorded") %>+ <% end %>+ <% table.with_column(t(".columns.cleanup_eligible")) { |trial| t(trial.cleanup_eligible ? ".eligible" : ".not_eligible") } %>+ <% end %>+ <% end %>+ <% end %>++ <%= render DS::Card.new(class: "gap-4", data: { testid: "hosted-usage-cleanup" }) do %>+ <div>+ <h2 class="text-lg font-semibold text-primary"><%= t(".cleanup.title") %></h2>+ <p class="mt-1 text-sm text-secondary"><%= t(".cleanup.description", limit: @hosted_usage.row_limit) %></p>+ <p class="mt-1 text-sm text-secondary"><%= t(".cleanup.eligibility_help") %></p>+ </div>+ <% unless @hosted_usage.cleanup_enabled? %>+ <%= render DS::Alert.new(message: t(".cleanup.disabled"), variant: :warning) %>+ <% end %>+ <% if @hosted_usage.cleanup_candidates.empty? %>+ <%= render DS::EmptyState.new(icon: "archive", title: t(".cleanup.empty")) %>+ <% else %>+ <%= render DS::Table.new(rows: @hosted_usage.cleanup_candidates, inset: true, label: t(".cleanup.title")) do |table| %>+ <% table.with_column(t(".columns.household")) do |candidate| %>+ <%= render "hosted_usage_household", row: candidate %>+ <% end %>+ <% table.with_column(t(".columns.status")) { |candidate| t(".statuses.#{candidate.status || :no_subscription}") } %>+ <% table.with_column(t(".columns.trial_ends_at")) do |candidate| %>+ <%= candidate.trial_ends_at ? l(candidate.trial_ends_at.to_date, format: :long) : t(".not_recorded") %>+ <% end %>+ <% table.with_column(t(".columns.cleanup_reason")) { |candidate| t(".cleanup.reasons.#{candidate.reason}") } %>+ <% end %>+ <% end %>+ <% end %>++ <%= render DS::Card.new(class: "gap-4", data: { testid: "hosted-usage-supporters" }) do %>+ <div>+ <h2 class="text-lg font-semibold text-primary"><%= t(".supporters.title") %></h2>+ <p class="mt-1 text-sm text-secondary"><%= t(".supporters.description") %></p>+ </div>+ <% if @hosted_usage.supporter_status_counts.values.sum.zero? %>+ <%= render DS::EmptyState.new(icon: "heart", title: t(".supporters.empty")) %>+ <% else %>+ <%= render DS::Table.new(rows: @hosted_usage.supporter_status_counts, inset: true, label: t(".supporters.title")) do |table| %>+ <% table.with_column(t(".columns.status")) { |(status, _count)| t(".statuses.#{status}") } %>+ <% table.with_column(t(".columns.subscription_rows"), numeric: true) { |(_status, count)| number_with_delimiter(count) } %>+ <% end %>+ <% end %>+ <% end %>+ </div>+<% end %>diff --git a/app/views/admin/system_health/show.html.erb b/app/views/admin/system_health/show.html.erbindex 58ac30a0eb..3032669ed6 100644--- a/app/views/admin/system_health/show.html.erb+++ b/app/views/admin/system_health/show.html.erb@@ -8,6 +8,9 @@<% tabs.with_nav do |nav| %><% nav.with_btn(id: "background_jobs", label: t(".tabs.background_jobs")) %><% nav.with_btn(id: "ai", label: t(".tabs.ai")) %>+ <% if @hosted_usage_available %>+ <% nav.with_btn(id: "hosted_usage", label: t(".tabs.hosted_usage")) %>+ <% end %><% end %><% tabs.with_panel(tab_id: "background_jobs") do %>@@ -28,4 +31,14 @@<%= render "entries/loading", message: t(".ai.loading") %><% end %><% end %>++ <% if @hosted_usage_available %>+ <% tabs.with_panel(tab_id: "hosted_usage") do %>+ <%= turbo_frame_tag "hosted_usage",+ src: hosted_usage_admin_system_health_path(locale: locale_from_param),+ loading: :lazy, target: "_top", refresh: :morph do %>+ <%= render "entries/loading", message: t("admin.system_health.hosted_usage.loading") %>+ <% end %>+ <% end %>+ <% end %><% end %>diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erbindex 977c4c6567..69f3328994 100644--- a/app/views/admin/users/index.html.erb+++ b/app/views/admin/users/index.html.erb@@ -32,17 +32,6 @@<% end %></div>- <!-- Summary: trials expiring in next 7 days -->- <div class="grid grid-cols-1 md:grid-cols-4 gap-4">- <div class="bg-container-inset rounded-lg p-4">- <div class="flex items-center gap-2 mb-2">- <%= icon "calendar-clock", class: "w-5 h-5 text-secondary" %>- <p class="text-xs font-medium text-secondary uppercase"><%= t(".summary.trials_expiring_7_days") %></p>- </div>- <p class="text-2xl font-semibold text-primary"><%= @trials_expiring_in_7_days %></p>- </div>- </div>-<!-- Families/Groups & Users --><div><h2 class="text-lg font-semibold text-primary mb-3"><%= t(".section_title") %></h2>diff --git a/config/initializers/posthog.rb b/config/initializers/posthog.rbindex 3e899723d8..43d5a5a1d3 100644--- a/config/initializers/posthog.rb+++ b/config/initializers/posthog.rb@@ -1,12 +1,12 @@require "posthog"Rails.configuration.x.posthog = ActiveSupport::OrderedOptions.new-# Explicit opt-in for local browser testing; production behavior is unchanged.+# Explicit opt-in for local analytics testing; production remains enabled.Rails.configuration.x.posthog.development_enabled = ActiveModel::Type::Boolean.new.cast(ENV.fetch("POSTHOG_DEVELOPMENT_ENABLED", "false"))Rails.configuration.x.posthog.api_key = ENV["POSTHOG_KEY"].presenceRails.configuration.x.posthog.host = ENV.fetch("POSTHOG_HOST", "https://us.i.posthog.com")Rails.configuration.x.posthog.feedback_enabled = ActiveModel::Type::Boolean.new.cast(ENV.fetch("POSTHOG_FEEDBACK_ENABLED", "true"))-# Public client configuration for the shared self-hosted feedback project.+# Public client configuration for shared feedback, including self-hosted Sankey.# This write-only project token is safe to distribute; it is not an admin key.# https://posthog.com/docs/apiRails.configuration.x.posthog.self_hosted_feedback_project = {@@ -30,3 +30,14 @@ if (api_key = Rails.configuration.x.posthog.api_key).present?on_error: Proc.new { |status, msg| puts "PostHog error: #{status} - #{msg}" }})end++# Daily UI usage shares the bundled feedback destination, independently of any+# installation-owned analytics project. Capture also checks these gates.+feedback_config = Rails.configuration.x.posthog+if feedback_config.feedback_enabled && (Rails.env.production? || (Rails.env.development? && feedback_config.development_enabled))+ $posthog_feedback = PostHog::Client.new(+ feedback_config.self_hosted_feedback_project.merge(+ on_error: Proc.new { |status, _msg| Rails.logger.debug("PostHog feedback capture failed (status #{status})") }+ )+ )+enddiff --git a/config/locales/views/admin/system_health/de.yml b/config/locales/views/admin/system_health/de.ymlindex a31175a3c8..78d623a214 100644--- a/config/locales/views/admin/system_health/de.yml+++ b/config/locales/views/admin/system_health/de.yml@@ -2,6 +2,65 @@de:admin:system_health:+ hosted_usage:+ loading: "Hosting-Nutzung wird geladen…"+ title: "Hosting-Nutzung"+ snapshot: "Schreibgeschützter Datenbankstand vom %{time}"+ summary:+ trial_households_count: "Testhaushalte (letzte 30 Tage)"+ trial_members_count: "Aktuelle Test-Mitgliedskonten"+ trials_expiring_soon_count: "Testphasen enden in 7 Tagen"+ cleanup_eligible_count: "Haushalte im Bereinigungsumfang"+ active_supporter_households_count: "Aktive Unterstützerhaushalte (lokal)"+ supporter_subscription_count: "Abonnementzeilen mit Stripe-Verknüpfung"+ summary_help: "Testzahlen beziehen sich auf in den letzten 30 Tagen erfasste Abonnements. Die Zahlen für bald endende Testphasen, Bereinigung und Unterstützung umfassen alle passenden aktuellen Zeilen, ohne Tabellenlimit."+ limitations_title: "Was diese Zahlen aussagen"+ limitations: "Die aktuellen Tabellen enthalten keinen vollständigen Verlauf von Testphasen, Zahlungen oder Sitzungsaktivität. Das Erstellungsdatum kann aus einem Import stammen. Mitgliedskonten sind keine nachgewiesenen Einzelpersonen. Diese Ansicht ändert keine Haushalts- oder Abonnementdaten. Zurücksetzungen der gemeinsamen Demo entfernen alte Haushalte und Sitzungen; der Besucherverlauf lässt sich daher nicht rekonstruieren."+ trials:+ title: "Kürzlich erfasste Testhaushalte"+ description: "Seit dem %{date} erfasste Abonnements mit gespeichertem Testende, einschließlich umgewandelter Testphasen. Höchstens %{limit} Haushalte werden angezeigt."+ sessions_help: "Sitzungen sind gespeicherte Anmeldungen aktivierter Nutzer, keine aktuell online befindlichen Nutzer oder Besuche. Abmelden löscht den Eintrag. Das letzte Erstellungsdatum ist kein Zeitpunkt der letzten Aktivität."+ empty: "Keine Testhaushalte in diesem Zeitraum erfasst"+ cleanup:+ title: "Bereinigungsberechtigung"+ description: "Entspricht dem bestehenden Bereinigungsumfang: pausiertes oder Testabonnement seit mehr als 14 Tagen abgelaufen, oder kein Abonnement und Haushalt älter als 45 + 14 Tage. Höchstens %{limit} Haushalte werden angezeigt."+ eligibility_help: "Kürzliche Anmeldungen verhindern keine Übereinstimmung. Die Berechtigung bestätigt keine Löschung; 90 Tage sind die Archivaufbewahrung, nicht die Bereinigungsschwelle für Testphasen."+ disabled: "Die geplante Testbereinigung ist außerhalb des verwalteten Modus deaktiviert. Hier werden nur passende Datensätze angezeigt."+ empty: "Keine Haushalte im Bereinigungsumfang"+ reasons:+ expired_trial_grace_elapsed: "Testphase beendet; 14 Tage Kulanz abgelaufen"+ no_subscription_grace_elapsed: "Kein Abonnement; 45 + 14 Tage abgelaufen"+ supporters:+ title: "Lokaler Unterstützerstatus"+ description: "Aktuelle lokale Abonnementzeilen mit Kunden- und Abonnement-IDs im Stripe-Format; das synthetische Demoabonnement ist ausgeschlossen. Der Status bestätigt weder Zahlungseingänge noch Erstzahlungsdaten. Es erfolgt keine Stripe-Anfrage."+ empty: "Keine Abonnementzeilen mit Stripe-Verknüpfung"+ columns:+ household: "Haushalts-ID"+ recorded_at: "Abonnement erfasst"+ trial_ends_at: "Testende"+ status: "Aktueller Status"+ members: "Mitgliedskonten"+ retained_sessions: "Gespeicherte Anmeldesitzungen"+ recent_sessions: "Gespeicherte Sitzungen der letzten 30 Tage"+ latest_session: "Letzte gespeicherte Anmeldung"+ cleanup_eligible: "Bereinigung möglich"+ cleanup_reason: "Grund"+ subscription_rows: "Abonnementzeilen"+ statuses:+ unknown: "Unbekannt"+ incomplete: "Unvollständig"+ incomplete_expired: "Unvollständig, abgelaufen"+ trialing: "Testphase"+ active: "Aktiv"+ past_due: "Überfällig"+ canceled: "Gekündigt"+ unpaid: "Unbezahlt"+ paused: "Pausiert"+ no_subscription: "Kein Abonnement"+ not_recorded: "Nicht erfasst"+ eligible: "Berechtigt"+ not_eligible: "Nicht berechtigt"+ synthetic_demo: "Synthetische Demo"push_notifications:send_test: "Testbenachrichtigung senden"queueing: "Wird eingereiht…"@@ -49,6 +108,7 @@ de:show:title: Systemstatustabs:+ hosted_usage: "Hosting-Nutzung"background_jobs: Hintergrundaufgabenai: KI-Statusalert:diff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.ymlindex 498cf75e50..1d8e8792f7 100644--- a/config/locales/views/admin/system_health/en.yml+++ b/config/locales/views/admin/system_health/en.yml@@ -2,6 +2,65 @@en:admin:system_health:+ hosted_usage:+ loading: "Loading hosted usage…"+ title: "Hosted usage"+ snapshot: "Read-only database snapshot as of %{time}"+ summary:+ trial_households_count: "Trial households (last 30 days)"+ trial_members_count: "Current trial member accounts"+ trials_expiring_soon_count: "Trials expiring in next 7 days"+ cleanup_eligible_count: "Cleanup-eligible households"+ active_supporter_households_count: "Active supporter households (local)"+ supporter_subscription_count: "Stripe-linked subscription rows"+ summary_help: "Trial totals cover subscriptions recorded in the last 30 days. Expiring-trial, cleanup and supporter totals cover all matching current rows, without the table limits."+ limitations_title: "What these numbers can tell us"+ limitations: "Current tables do not retain full trial, payment or session-activity history. Subscription creation can reflect imports. Member accounts are not verified unique people. This view changes no household or subscription data. Shared-demo resets remove old households and sessions, so visitor history cannot be reconstructed."+ trials:+ title: "Recent trial households"+ description: "Subscriptions recorded since %{date} that retain a trial end date, including converted trials. Showing up to %{limit} households."+ sessions_help: "Sessions are retained sign-in records for enabled users, not currently online users or visits. Signing out deletes a record. The latest creation time is not a last-seen time."+ empty: "No trial households recorded in this window"+ cleanup:+ title: "Cleanup eligibility"+ description: "Matches the existing cleanup scope: a paused or trialing subscription ended more than 14 days ago, or no subscription and a household older than 45 + 14 days. Showing up to %{limit} households."+ eligibility_help: "Recent logins do not prevent a match. Eligibility does not confirm deletion; 90 days is archive retention, not the trial-cleanup threshold."+ disabled: "Scheduled trial cleanup is disabled outside managed mode. These are scope matches only."+ empty: "No households match the cleanup scope"+ reasons:+ expired_trial_grace_elapsed: "Trial ended; 14-day grace elapsed"+ no_subscription_grace_elapsed: "No subscription; 45 + 14 days elapsed"+ supporters:+ title: "Local supporter status"+ description: "Current local subscription rows with Stripe-shaped customer and subscription IDs; the synthetic demo subscription is excluded. Statuses do not verify payments received or first-payment dates. No Stripe request is made."+ empty: "No Stripe-linked subscription rows"+ columns:+ household: "Household ID"+ recorded_at: "Subscription recorded"+ trial_ends_at: "Trial ends"+ status: "Current status"+ members: "Member accounts"+ retained_sessions: "Retained sign-in sessions"+ recent_sessions: "Retained sessions created in last 30 days"+ latest_session: "Latest retained sign-in"+ cleanup_eligible: "Cleanup eligible"+ cleanup_reason: "Reason"+ subscription_rows: "Subscription rows"+ statuses:+ unknown: "Unknown"+ incomplete: "Incomplete"+ incomplete_expired: "Incomplete, expired"+ trialing: "Trialing"+ active: "Active"+ past_due: "Past due"+ canceled: "Canceled"+ unpaid: "Unpaid"+ paused: "Paused"+ no_subscription: "No subscription"+ not_recorded: "Not recorded"+ eligible: "Eligible"+ not_eligible: "Not eligible"+ synthetic_demo: "Synthetic demo"push_notifications:send_test: "Send test push notification"queueing: "Queueing…"@@ -49,6 +108,7 @@ en:show:title: System healthtabs:+ hosted_usage: "Hosted usage"background_jobs: Background jobsai: AI statusalert:diff --git a/config/locales/views/admin/system_health/fr.yml b/config/locales/views/admin/system_health/fr.ymlindex 5a6ecef5e5..035040e596 100644--- a/config/locales/views/admin/system_health/fr.yml+++ b/config/locales/views/admin/system_health/fr.yml@@ -2,6 +2,65 @@fr:admin:system_health:+ hosted_usage:+ loading: "Chargement de l’usage hébergé…"+ title: "Usage hébergé"+ snapshot: "État de la base en lecture seule au %{time}"+ summary:+ trial_households_count: "Foyers en essai (30 derniers jours)"+ trial_members_count: "Comptes membres actuels des essais"+ trials_expiring_soon_count: "Essais expirant sous 7 jours"+ cleanup_eligible_count: "Foyers éligibles au nettoyage"+ active_supporter_households_count: "Foyers contributeurs actifs (local)"+ supporter_subscription_count: "Lignes d’abonnement liées à Stripe"+ summary_help: "Les totaux d’essais concernent les abonnements enregistrés sur les 30 derniers jours. Les totaux d’expiration, de nettoyage et de contribution couvrent toutes les lignes actuelles correspondantes, sans la limite des tableaux."+ limitations_title: "Ce que ces chiffres permettent de savoir"+ limitations: "Les tables actuelles ne conservent pas l’historique complet des essais, paiements ou activités des sessions. La création d’un abonnement peut provenir d’un import. Les comptes membres ne sont pas des personnes uniques vérifiées. Cette vue ne modifie aucune donnée de foyer ou d’abonnement. Les réinitialisations de la démo partagée suppriment les anciens foyers et sessions ; l’historique des visiteurs ne peut donc pas être reconstitué."+ trials:+ title: "Foyers d’essai récents"+ description: "Abonnements enregistrés depuis le %{date} conservant une date de fin d’essai, y compris les essais convertis. Affichage limité à %{limit} foyers."+ sessions_help: "Les sessions sont des connexions conservées pour les utilisateurs activés, pas des utilisateurs actuellement en ligne ni des visites. Se déconnecter supprime une session. La dernière création n’indique pas la dernière activité."+ empty: "Aucun foyer d’essai enregistré sur cette période"+ cleanup:+ title: "Éligibilité au nettoyage"+ description: "Périmètre existant du nettoyage : abonnement en pause ou en essai terminé depuis plus de 14 jours, ou aucun abonnement et foyer âgé de plus de 45 + 14 jours. Affichage limité à %{limit} foyers."+ eligibility_help: "Les connexions récentes n’empêchent pas l’éligibilité. Celle-ci ne confirme pas une suppression ; les 90 jours correspondent à la conservation des archives, pas au seuil de nettoyage des essais."+ disabled: "Le nettoyage planifié des essais est désactivé hors du mode géré. Seules les correspondances au périmètre sont affichées."+ empty: "Aucun foyer ne correspond au périmètre de nettoyage"+ reasons:+ expired_trial_grace_elapsed: "Essai terminé ; délai de grâce de 14 jours écoulé"+ no_subscription_grace_elapsed: "Aucun abonnement ; 45 + 14 jours écoulés"+ supporters:+ title: "État local des contributeurs"+ description: "Lignes d’abonnement locales actuelles avec des identifiants client et abonnement au format Stripe ; l’abonnement de démonstration synthétique est exclu. Les statuts ne vérifient ni les paiements reçus ni les dates de premier paiement. Aucune requête Stripe n’est effectuée."+ empty: "Aucune ligne d’abonnement liée à Stripe"+ columns:+ household: "Identifiant du foyer"+ recorded_at: "Abonnement enregistré"+ trial_ends_at: "Fin de l’essai"+ status: "État actuel"+ members: "Comptes membres"+ retained_sessions: "Sessions de connexion conservées"+ recent_sessions: "Sessions conservées créées sur 30 jours"+ latest_session: "Dernière connexion conservée"+ cleanup_eligible: "Éligible au nettoyage"+ cleanup_reason: "Motif"+ subscription_rows: "Lignes d’abonnement"+ statuses:+ unknown: "Inconnu"+ incomplete: "Incomplet"+ incomplete_expired: "Incomplet, expiré"+ trialing: "En essai"+ active: "Actif"+ past_due: "En retard"+ canceled: "Annulé"+ unpaid: "Impayé"+ paused: "En pause"+ no_subscription: "Aucun abonnement"+ not_recorded: "Non enregistré"+ eligible: "Éligible"+ not_eligible: "Non éligible"+ synthetic_demo: "Démo synthétique"push_notifications:send_test: "Envoyer une notification de test"queueing: "Mise en file…"@@ -244,6 +303,7 @@ fr:status_section_description: État actuel du worker en arrière-plan qui assure les synchronisations, les soldes et les calculs de patrimoine net.status_section_title: Statut de Sidekiqtabs:+ hosted_usage: "Usage hébergé"ai: Statut de l'IAbackground_jobs: Tâches en arrière-plantitle: Santé du systèmediff --git a/config/locales/views/admin/system_health/pt-PT.yml b/config/locales/views/admin/system_health/pt-PT.ymlindex 922c2931fc..8e467e14a9 100644--- a/config/locales/views/admin/system_health/pt-PT.yml+++ b/config/locales/views/admin/system_health/pt-PT.yml@@ -2,6 +2,65 @@pt-PT:admin:system_health:+ hosted_usage:+ loading: "A carregar a utilização alojada…"+ title: "Utilização alojada"+ snapshot: "Estado da base de dados só de leitura em %{time}"+ summary:+ trial_households_count: "Agregados em teste (últimos 30 dias)"+ trial_members_count: "Contas de membros atuais dos testes"+ trials_expiring_soon_count: "Testes a terminar nos próximos 7 dias"+ cleanup_eligible_count: "Agregados elegíveis para limpeza"+ active_supporter_households_count: "Agregados apoiantes ativos (local)"+ supporter_subscription_count: "Registos de subscrição ligados ao Stripe"+ summary_help: "Os totais de testes abrangem subscrições registadas nos últimos 30 dias. Os totais de expiração, limpeza e apoio abrangem todos os registos atuais correspondentes, sem os limites das tabelas."+ limitations_title: "O que estes números permitem saber"+ limitations: "As tabelas atuais não guardam o histórico completo de testes, pagamentos ou atividade das sessões. A criação de subscrições pode resultar de importações. As contas de membros não são pessoas únicas verificadas. Esta vista não altera dados de agregados ou subscrições. As reposições da demo partilhada removem agregados e sessões antigos, pelo que não é possível reconstruir o histórico de visitantes."+ trials:+ title: "Agregados de teste recentes"+ description: "Subscrições registadas desde %{date} que conservam uma data de fim de teste, incluindo testes convertidos. São apresentados até %{limit} agregados."+ sessions_help: "As sessões são registos de início de sessão conservados para utilizadores ativados, não utilizadores atualmente online nem visitas. Terminar a sessão elimina o registo. A última criação não indica a última atividade."+ empty: "Nenhum agregado de teste registado neste período"+ cleanup:+ title: "Elegibilidade para limpeza"+ description: "Corresponde ao âmbito de limpeza existente: subscrição em pausa ou em teste terminada há mais de 14 dias, ou sem subscrição e agregado com mais de 45 + 14 dias. São apresentados até %{limit} agregados."+ eligibility_help: "Inícios de sessão recentes não impedem a elegibilidade. Esta não confirma a eliminação; os 90 dias são o prazo de retenção de arquivos, não o limiar de limpeza de testes."+ disabled: "A limpeza agendada de testes está desativada fora do modo gerido. Estes são apenas registos correspondentes ao âmbito."+ empty: "Nenhum agregado corresponde ao âmbito de limpeza"+ reasons:+ expired_trial_grace_elapsed: "Teste terminado; prazo de 14 dias decorrido"+ no_subscription_grace_elapsed: "Sem subscrição; 45 + 14 dias decorridos"+ supporters:+ title: "Estado local dos apoiantes"+ description: "Registos locais atuais de subscrição com IDs de cliente e subscrição no formato Stripe; a subscrição de demonstração sintética é excluída. Os estados não confirmam pagamentos recebidos nem datas do primeiro pagamento. Não é efetuado qualquer pedido ao Stripe."+ empty: "Nenhum registo de subscrição ligado ao Stripe"+ columns:+ household: "ID do agregado"+ recorded_at: "Subscrição registada"+ trial_ends_at: "Fim do teste"+ status: "Estado atual"+ members: "Contas de membros"+ retained_sessions: "Sessões de acesso conservadas"+ recent_sessions: "Sessões conservadas criadas em 30 dias"+ latest_session: "Último acesso conservado"+ cleanup_eligible: "Elegível para limpeza"+ cleanup_reason: "Motivo"+ subscription_rows: "Registos de subscrição"+ statuses:+ unknown: "Desconhecido"+ incomplete: "Incompleta"+ incomplete_expired: "Incompleta, expirada"+ trialing: "Em teste"+ active: "Ativa"+ past_due: "Em atraso"+ canceled: "Cancelada"+ unpaid: "Não paga"+ paused: "Em pausa"+ no_subscription: "Sem subscrição"+ not_recorded: "Não registado"+ eligible: "Elegível"+ not_eligible: "Não elegível"+ synthetic_demo: "Demo sintética"push_notifications:send_test: "Enviar notificação de teste"queueing: "A colocar em fila…"@@ -47,6 +106,7 @@ pt-PT:show:title: Estado do sistematabs:+ hosted_usage: "Utilização alojada"background_jobs: Tarefas em segundo planoai: Estado da IAalert:diff --git a/config/locales/views/admin/users/ca.yml b/config/locales/views/admin/users/ca.ymlindex 90a6a7da7d..cd9ba0e8d4 100644--- a/config/locales/views/admin/users/ca.yml+++ b/config/locales/views/admin/users/ca.yml@@ -40,8 +40,6 @@ ca:member: Membresuper_admin: Super administradorsection_title: Famílies / Grups- summary:- trials_expiring_7_days: Proves que caduquen en els pròxims 7 diestable:family_accounts: Comptes familiarsfamily_transactions: Transaccions familiarsdiff --git a/config/locales/views/admin/users/de.yml b/config/locales/views/admin/users/de.ymlindex e1fdc90a08..48cfd18520 100644--- a/config/locales/views/admin/users/de.yml+++ b/config/locales/views/admin/users/de.yml@@ -18,8 +18,6 @@ de:trial_expiring_soon: "Läuft in 7 Tagen ab"trial_trialing: "In Testphase"submit: "Filtern"- summary:- trials_expiring_7_days: "Testversionen laufen in den nächsten 7 Tagen ab"table:user: "Benutzer"trial_ends_at: "Testversion endet"diff --git a/config/locales/views/admin/users/en.yml b/config/locales/views/admin/users/en.ymlindex 88b433fddf..baea4f3192 100644--- a/config/locales/views/admin/users/en.yml+++ b/config/locales/views/admin/users/en.yml@@ -21,8 +21,6 @@ en:trial_expiring_soon: "Expiring in 7 days"trial_trialing: "On trial"submit: "Filter"- summary:- trials_expiring_7_days: "Trials expiring in next 7 days"table:user: "User"trial_ends_at: "Trial ends"diff --git a/config/locales/views/admin/users/es.yml b/config/locales/views/admin/users/es.ymlindex 291f8c5262..559d7469e3 100644--- a/config/locales/views/admin/users/es.yml+++ b/config/locales/views/admin/users/es.yml@@ -21,8 +21,6 @@ es:trial_expiring_soon: Caduca en 7 díastrial_trialing: En periodo de pruebasubmit: Filtrar- summary:- trials_expiring_7_days: Pruebas que caducan en los próximos 7 díastable:user: Usuariotrial_ends_at: La prueba finalizadiff --git a/config/locales/views/admin/users/fr.yml b/config/locales/views/admin/users/fr.ymlindex 7ff9eeee39..bdf04b66f8 100644--- a/config/locales/views/admin/users/fr.yml+++ b/config/locales/views/admin/users/fr.yml@@ -82,8 +82,6 @@ fr:member: Membresuper_admin: Super Administrateursection_title: Familles / Groupes- summary:- trials_expiring_7_days: Essais expirant dans les 7 prochains jourstable:actions: Actionscreate_new_family_option: "+ Créer une famille / un groupe"diff --git a/config/locales/views/admin/users/hu.yml b/config/locales/views/admin/users/hu.ymlindex ee4719c300..7ea8d442a7 100644--- a/config/locales/views/admin/users/hu.yml+++ b/config/locales/views/admin/users/hu.yml@@ -21,8 +21,6 @@ hu:trial_expiring_soon: "7 napon belül lejár"trial_trialing: "Próbaidőn"submit: "Szűrés"- summary:- trials_expiring_7_days: "A következő 7 napban lejáró próbaidők"table:user: "Felhasználó"trial_ends_at: "Próbaidő vége"diff --git a/config/locales/views/admin/users/it.yml b/config/locales/views/admin/users/it.ymlindex 995c166dc2..87cf69583b 100644--- a/config/locales/views/admin/users/it.yml+++ b/config/locales/views/admin/users/it.yml@@ -21,8 +21,6 @@ it:trial_expiring_soon: "In scadenza in 7 giorni"trial_trialing: "In prova"submit: "Filtra"- summary:- trials_expiring_7_days: "Prove in scadenza nei prossimi 7 giorni"table:user: "Utente"trial_ends_at: "Prova scade"diff --git a/config/locales/views/admin/users/pl.yml b/config/locales/views/admin/users/pl.ymlindex 68306d50ea..7b751e1032 100644--- a/config/locales/views/admin/users/pl.yml+++ b/config/locales/views/admin/users/pl.yml@@ -91,8 +91,6 @@ pl:member: Członeksuper_admin: Superadministratorsection_title: Rodziny / Grupy- summary:- trials_expiring_7_days: Okresy próbne wygasające w ciągu 7 dnitable:actions: Akcjecreate_new_family_option: "+ Utwórz nową rodzinę/grupę"diff --git a/config/locales/views/admin/users/pt-BR.yml b/config/locales/views/admin/users/pt-BR.ymlindex 591a60b6fd..5b81a22f13 100644--- a/config/locales/views/admin/users/pt-BR.yml+++ b/config/locales/views/admin/users/pt-BR.yml@@ -21,8 +21,6 @@ pt-BR:trial_expiring_soon: "Expira em 7 dias"trial_trialing: "Em teste"submit: "Filtro"- summary:- trials_expiring_7_days: "Testes expiram nos próximos 7 dias"table:user: "Usuário"trial_ends_at: "Fim do teste"diff --git a/config/locales/views/admin/users/pt-PT.yml b/config/locales/views/admin/users/pt-PT.ymlindex 061a464e41..6dce42eeb7 100644--- a/config/locales/views/admin/users/pt-PT.yml+++ b/config/locales/views/admin/users/pt-PT.yml@@ -21,8 +21,6 @@ pt-PT:trial_expiring_soon: "Expira em 7 dias"trial_trialing: "Em período experimental"submit: "Filtrar"- summary:- trials_expiring_7_days: "Períodos experimentais que expiram nos próximos 7 dias"table:user: "Utilizador"trial_ends_at: "Fim do período experimental"diff --git a/config/locales/views/admin/users/ru.yml b/config/locales/views/admin/users/ru.ymlindex 4717cf091c..9ee5562fd4 100644--- a/config/locales/views/admin/users/ru.yml+++ b/config/locales/views/admin/users/ru.yml@@ -39,8 +39,6 @@ ru:member: Участникsuper_admin: Суперадминистраторsection_title: Семьи / Группы- summary:- trials_expiring_7_days: Пробные периоды истекают в течение 7 днейtable:family_accounts: Семейные счетаfamily_transactions: Семейные операцииdiff --git a/config/locales/views/admin/users/tr.yml b/config/locales/views/admin/users/tr.ymlindex 83c97c02a1..9514809720 100644--- a/config/locales/views/admin/users/tr.yml+++ b/config/locales/views/admin/users/tr.yml@@ -38,8 +38,6 @@ tr:member: Üyesuper_admin: Süper Yöneticisection_title: Aileler / Gruplar- summary:- trials_expiring_7_days: Önümüzdeki 7 gün içinde sona erecek denemelertable:family_accounts: Aile hesaplarıfamily_transactions: Aile işlemleridiff --git a/config/locales/views/admin/users/uk.yml b/config/locales/views/admin/users/uk.ymlindex 3df5e08118..c0d5067665 100644--- a/config/locales/views/admin/users/uk.yml+++ b/config/locales/views/admin/users/uk.yml@@ -21,8 +21,6 @@ uk:trial_expiring_soon: "Закінчується через 7 днів"trial_trialing: "На пробному періоді"submit: "Фільтрувати"- summary:- trials_expiring_7_days: "Пробні періоди, що закінчуються в найближчі 7 днів"table:user: "Користувач"trial_ends_at: "Пробний період закінчується"diff --git a/config/locales/views/admin/users/vi.yml b/config/locales/views/admin/users/vi.ymlindex 0e1c2a2c0e..67d03185ea 100644--- a/config/locales/views/admin/users/vi.yml+++ b/config/locales/views/admin/users/vi.yml@@ -21,8 +21,6 @@ vi:trial_expiring_soon: "Hết hạn trong 7 ngày"trial_trialing: "Đang dùng thử"submit: "Lọc"- summary:- trials_expiring_7_days: "Các bản dùng thử hết hạn trong 7 ngày tới"table:user: "Người dùng"trial_ends_at: "Kết thúc dùng thử"diff --git a/config/locales/views/admin/users/zh-CN.yml b/config/locales/views/admin/users/zh-CN.ymlindex 5338a611d8..cab9f88f19 100644--- a/config/locales/views/admin/users/zh-CN.yml+++ b/config/locales/views/admin/users/zh-CN.yml@@ -21,8 +21,6 @@ zh-CN:trial_expiring_soon: 7 天内到期trial_trialing: 试用中submit: 筛选- summary:- trials_expiring_7_days: 未来 7 天内到期的试用table:user: 用户trial_ends_at: 试用结束diff --git a/config/locales/views/admin/users/zh-TW.yml b/config/locales/views/admin/users/zh-TW.ymlindex 23bf19eac9..ce401d4b50 100644--- a/config/locales/views/admin/users/zh-TW.yml+++ b/config/locales/views/admin/users/zh-TW.yml@@ -21,8 +21,6 @@ zh-TW:trial_expiring_soon: 7 天內到期trial_trialing: 試用中submit: 篩選- summary:- trials_expiring_7_days: 未來 7 天內到期的試用table:user: 使用者trial_ends_at: 試用結束diff --git a/config/routes.rb b/config/routes.rbindex 5fb0acf03d..b548a61af8 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -1015,6 +1015,7 @@ Rails.application.routes.draw do# so name it explicitly.resource :system_health, only: :show, controller: "system_health" doget :ai_status+ get :hosted_usagepost :verify_worker_aipost :send_test_pushenddiff --git a/docs/hosting/preview-feedback.md b/docs/hosting/preview-feedback.mdindex 51f54ba98d..cdf63fce40 100644--- a/docs/hosting/preview-feedback.md+++ b/docs/hosting/preview-feedback.md@@ -138,6 +138,58 @@ usage: blocked or opted-out analytics are absent. The self-hosted client uses anin-memory anonymous identity, so distinct IDs are not reliable counts of returningpeople or installations across visits.+## Daily web preview adoption++`web_ui_served_daily` records whether Rails served an authenticated user a+successful full HTML UI response with `preview_features_enabled` true or false. It+does not claim that the browser displayed the response or that someone was+actively using it. Normal web visits and installed PWAs use the same UI route;+API/JSON requests, AJAX/Turbo-frame requests, non-GET requests, redirects/errors,+and prefetch/prerender requests are excluded. No browser script, storage marker, mobile API, or+background-job hook is added.++The server event uses the bundled shared feedback project, the same destination+as self-hosted Sankey feedback, in both managed and self-hosted deployments.+It does not require `POSTHOG_KEY` / `POSTHOG_HOST` or duplicate the event to an+installation's normal analytics project. `POSTHOG_FEEDBACK_ENABLED=false`+disables it. Collection requires production or the existing explicit development+opt-in (`POSTHOG_DEVELOPMENT_ENABLED=true`); automated tests remain disabled.+Browser SDK opt-outs stored in localStorage and ad blockers cannot suppress this+server-side event; Rails cannot read that browser-only state.++Sankey's browser capture and routing remain unchanged: managed Sankey events use+their configured normal analytics project, while self-hosted Sankey events use+the shared feedback project. Browser and server events have different identities+and opt-out behavior. The shared destination and GeoIP support aggregate location+cohorts, not matching people or sessions between the two event streams.++An atomic cache claim limits capture to one attempt per authenticated user per+calendar day in the family's configured timezone (or the app timezone when+unset/invalid), across browsers and sign-ins. The+first claimed response supplies that day's preview state and IP; later preference+or network changes do not add another event that day. A shared Redis cache provides this+deduplication across web workers; other cache stores can race or limit counting+only within one process. Null-cache configurations skip capture; cache+clearing/eviction can permit repeats, and cache/SDK failures can omit a day.+SDK queue acceptance does not guarantee delivery. A qualifying full UI response+can still be requested by a background tab or automation; browser-cached opens+that never reach Rails cannot count.++The event includes the Boolean preview state, `sure_version`, and the visitor IP+that Rails resolves through `request.remote_ip`, sent as `$ip`. GeoIP enrichment+is explicitly allowed with `$geoip_disable: false`, subject to the destination+project's settings. Correct visitor geography depends on the deployment's proxy+headers and Rails trusted-proxy configuration; a proxy, VPN, or shared network+can affect the result. The event uses Rails' resolved address, not an unparsed+forwarding header. This change does not modify proxy trust settings.++The required distinct identifier is an application-keyed digest of the user and+date: it is stable only for that user/day and contains no raw user ID. Person+profiles remain disabled. However, an IP address can identify or correlate people,+so the event is not anonymous. No names, emails, financial values, or URLs are+added. Tests use synthetic addresses and an offline client and never submit live+events.+## Privacy and extending the implementationUsage properties must exclude amounts, account/category names or IDs, date@@ -145,10 +197,10 @@ ranges, server URLs, and graph payloads. Ask users to omit private financialdetails from voluntary text. The feature and feedback form are excluded fromautocapture and session recording.-Managed deployments retain their existing SDK metadata. The dedicated self-hosted-client disables automatic tracking, pageviews, session recording, and person+Managed Sankey events retain their existing SDK metadata. The dedicated self-hosted+browser client disables automatic tracking, pageviews, session recording, and personprofiles; it strips incidental URL, referrer, and device metadata. Opting out of-either client suppresses capture. GeoIP enrichment is enabled using the browser+either browser client suppresses Sankey capture. GeoIP enrichment is enabled using the browserconnection's IP address, allowing PostHog to add approximate location propertiesto these events without creating person profiles. The destination project must also allow GeoIP enrichment.diff --git a/test/controllers/admin/system_health_hosted_usage_test.rb b/test/controllers/admin/system_health_hosted_usage_test.rbnew file mode 100644index 0000000000..67a1a20cac--- /dev/null+++ b/test/controllers/admin/system_health_hosted_usage_test.rb@@ -0,0 +1,242 @@+require "test_helper"++class Admin::SystemHealthHostedUsageControllerTest < ActionDispatch::IntegrationTest+ include ActiveJob::TestHelper++ setup do+ host! "app.sure.am"+ @user = users(:sure_support_staff)+ @user.update!(locale: "en")+ sign_in @user+ stub_healthy_sidekiq+ end++ test "both exact hosted domains expose only a lazy report frame on the health page" do+ HostedUsage.expects(:new).never++ %w[app.sure.am demo.sure.am].each do |domain|+ host! domain+ sign_in @user+ ClimateControl.modify("APP_DOMAIN" => domain) do+ %w[background_jobs ai hosted_usage].each do |tab|+ get admin_system_health_path(tab: tab)++ assert_response :success+ assert_select "button[role='tab'][data-id='hosted_usage']", text: "Hosted usage"+ assert_select "button[role='tab'][aria-selected='true'][data-id='#{tab}']"+ assert_select "turbo-frame#hosted_usage[loading='lazy'][src='#{hosted_usage_admin_system_health_path}']"+ assert_select "[data-testid='hosted-usage-report']", count: 0+ end+ end+ end+ end++ test "unapproved domains hide the tab and reject the direct endpoint before loading data" do+ HostedUsage.expects(:new).never++ [ nil, "localhost", "sure.onrender.com", "sub.app.sure.am", "app.sure.am.example.com", "https://app.sure.am", "demo.sure.am" ].each do |configured_domain|+ ClimateControl.modify("APP_DOMAIN" => configured_domain) do+ get admin_system_health_path(tab: "hosted_usage")+ assert_response :success+ assert_select "button[role='tab'][data-id='hosted_usage']", count: 0+ assert_select "turbo-frame#hosted_usage", count: 0+ assert_select "button[role='tab'][aria-selected='true'][data-id='background_jobs']"++ get hosted_usage_admin_system_health_path+ assert_response :not_found+ end+ end+ end++ test "an onrender request cannot access a report configured for an allowed domain" do+ host! "sure.onrender.com"+ sign_in @user+ HostedUsage.expects(:new).never++ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ get admin_system_health_path(tab: "hosted_usage")+ assert_response :success+ assert_select "button[role='tab'][data-id='hosted_usage']", count: 0++ get hosted_usage_admin_system_health_path+ assert_response :not_found+ end+ end++ test "the report inherits super admin and authentication requirements" do+ HostedUsage.expects(:new).never++ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ sign_in users(:family_admin)+ get hosted_usage_admin_system_health_path+ assert_redirected_to root_path++ reset!+ host! "app.sure.am"+ get hosted_usage_admin_system_health_path+ assert_redirected_to new_session_path+ end+ end++ test "forwarded host cannot expose hosted usage on an onrender host" do+ host! "sure-app.onrender.com"+ sign_in @user+ HostedUsage.expects(:new).never++ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ headers = { "X-Forwarded-Host" => "app.sure.am" }+ get admin_system_health_path(tab: "hosted_usage"), headers: headers+ assert_response :success+ assert_select "button[role='tab'][data-id='hosted_usage']", count: 0++ get hosted_usage_admin_system_health_path, headers: headers+ assert_response :not_found+ end+ end++ test "the exact hosted hostname accepts an explicit numeric port" do+ host! "app.sure.am:443"+ sign_in @user++ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ get hosted_usage_admin_system_health_path+ end++ assert_response :success+ assert_select "turbo-frame#hosted_usage"+ end++ test "report renders trial sessions cleanup supporters and the relocated expiring trial summary" do+ subscriptions(:trialing).update!(created_at: 2.days.ago, trial_ends_at: 3.days.from_now)+ subscriptions(:active).update!(stripe_id: "sub_supporter")+ families(:dylan_family).update!(stripe_customer_id: "cus_supporter")++ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ get hosted_usage_admin_system_health_path+ end++ assert_response :success+ assert_select "turbo-frame#hosted_usage"+ assert_select "[data-testid='hosted-usage-trials_expiring_soon_count'] dd", text: "1"+ assert_select "[data-testid='hosted-usage-active_supporter_households_count'] dd", text: "1"+ assert_select "[data-testid='hosted-usage-trials']" do+ assert_select "td", text: families(:empty).id+ assert_select "th", text: "Retained sign-in sessions"+ assert_select "th", text: "Retained sessions created in last 30 days"+ assert_select "td", text: "Trialing"+ end+ assert_select "[role='region'][aria-label='Recent trial households']"+ assert_select "[role='region'][aria-label='Cleanup eligibility']"+ assert_select "[role='region'][aria-label='Local supporter status']"+ assert_match "not currently online users or visits", response.body+ assert_match "Signing out deletes a record", response.body+ assert_match "Member accounts are not verified unique people", response.body+ assert_match "Recent logins do not prevent a match", response.body+ assert_match "90 days is archive retention", response.body+ assert_match "do not verify payments received", response.body+ assert_select "form, button, a[data-turbo-method]", count: 0+ assert_no_match(/#{Regexp.escape(@user.email)}|#{Regexp.escape(families(:empty).name)}/, response.body)+ end++ test "report GET makes no database writes and cannot enqueue auto sync or contact providers" do+ Admin::SystemHealthController.any_instance.stubs(:family_needs_auto_sync?).returns(true)+ Admin::SystemHealthController.any_instance.expects(:sync_family).never+ Provider::Registry.expects(:get_provider).never++ queries = []+ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ assert_no_enqueued_jobs do+ queries = capture_sql_queries { get hosted_usage_admin_system_health_path }+ end+ end++ assert_response :success+ assert_empty queries.grep(/\A(?:INSERT|UPDATE|DELETE)\b/i)+ end++ test "report renders empty states without inventing missing activity" do+ report = OpenStruct.new(+ as_of: Time.current, window_start: 30.days.ago, row_limit: 100,+ summary: { trial_households_count: 0, trials_expiring_soon_count: 0 },+ trials: [], cleanup_candidates: [],+ supporter_status_counts: Subscription.statuses.keys.index_with(0), cleanup_enabled?: true+ )+ HostedUsage.stubs(:new).returns(report)++ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ get hosted_usage_admin_system_health_path+ end++ assert_response :success+ assert_match "No trial households recorded in this window", response.body+ assert_match "No households match the cleanup scope", response.body+ assert_match "No Stripe-linked subscription rows", response.body+ assert_select "table", count: 0+ end++ test "synthetic demo rows are marked and disabled cleanup is clearly scoped" do+ subscriptions(:active).update!(stripe_id: "sub_demo_123", trial_ends_at: 2.days.from_now, created_at: 1.day.ago)+ Rails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)++ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ get hosted_usage_admin_system_health_path+ end++ assert_response :success+ assert_match "Synthetic demo", response.body+ assert_match "Scheduled trial cleanup is disabled outside managed mode", response.body+ end++ test "the hosted frame preserves valid locale overrides and drops invalid ones" do+ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ get admin_system_health_path(tab: "hosted_usage", locale: "de")+ assert_select "button[role='tab'][aria-selected='true']", text: "Hosting-Nutzung"+ assert_select "turbo-frame#hosted_usage[src='#{hosted_usage_admin_system_health_path(locale: "de")}']"++ [ "xx", { "x" => "de" } ].each do |locale|+ get admin_system_health_path(tab: "hosted_usage", locale: locale)+ assert_response :success+ assert_select "turbo-frame#hosted_usage[src='#{hosted_usage_admin_system_health_path}']"+ end+ end+ end++ test "all hosted usage labels have translations in the supported health locales" do+ keys = I18n.t("admin.system_health.hosted_usage", locale: :en, fallback: false, raise: true)+ %i[en de fr pt-PT].each do |locale|+ assert_kind_of String, I18n.t("admin.system_health.show.tabs.hosted_usage", locale: locale, fallback: false, raise: true)+ assert_translations(keys, "admin.system_health.hosted_usage", locale)++ ClimateControl.modify("APP_DOMAIN" => "app.sure.am") do+ get hosted_usage_admin_system_health_path(locale: locale)+ end+ assert_response :success+ assert_select "h2", text: I18n.t("admin.system_health.hosted_usage.title", locale: locale)+ assert_no_match(/translation missing/i, response.body)+ end+ end++ private+ def assert_translations(keys, prefix, locale)+ keys.each do |key, value|+ path = "#{prefix}.#{key}"+ if value.is_a?(Hash)+ assert_translations(value, path, locale)+ else+ assert_kind_of String, I18n.t(path, locale: locale, fallback: false, raise: true, time: "2026-10-01", date: "2026-09-01", limit: 100)+ end+ end+ end++ def stub_healthy_sidekiq+ SidekiqHealth.any_instance.stubs(:healthy?).returns(true)+ SidekiqHealth.any_instance.stubs(:processes_count).returns(1)+ SidekiqHealth.any_instance.stubs(:last_heartbeat_at).returns(Time.current)+ SidekiqHealth.any_instance.stubs(:max_queue_latency).returns(0.0)+ SidekiqHealth.any_instance.stubs(:enqueued_count).returns(0)+ SidekiqHealth.any_instance.stubs(:retry_count).returns(0)+ SidekiqHealth.any_instance.stubs(:failed_count).returns(0)+ SidekiqHealth.any_instance.stubs(:processed_count).returns(42)+ SidekiqHealth.any_instance.stubs(:queue_breakdown).returns([])+ end+enddiff --git a/test/controllers/admin/users_controller_test.rb b/test/controllers/admin/users_controller_test.rbindex 5601d349c2..346a4d6d02 100644--- a/test/controllers/admin/users_controller_test.rb+++ b/test/controllers/admin/users_controller_test.rb@@ -7,6 +7,14 @@ class Admin::UsersControllerTest < ActionDispatch::IntegrationTestsign_in users(:sure_support_staff)end+ test "index leaves the expiring trial summary to hosted system health" do+ get admin_users_url++ assert_response :success+ assert_no_match I18n.t("admin.system_health.hosted_usage.summary.trials_expiring_soon_count", raise: true), response.body+ assert_select "select[name='trial_status'] option[value='expiring_soon']"+ end+test "index groups users by family sorted by transaction count" dofamily_with_more = users(:family_admin).familyfamily_with_fewer = users(:empty).familydiff --git a/test/controllers/daily_web_usage_test.rb b/test/controllers/daily_web_usage_test.rbnew file mode 100644index 0000000000..91edb3e4be--- /dev/null+++ b/test/controllers/daily_web_usage_test.rb@@ -0,0 +1,226 @@+require "test_helper"++class DailyWebUsageTest < ActionDispatch::IntegrationTest+ setup do+ travel_to Time.utc(2026, 10, 2, 12)+ @user = users(:family_admin)+ @user.family.update!(timezone: "Etc/UTC")+ @previous_client = $posthog_feedback+ @previous_normal_client = $posthog+ events = @events = []+ @client = Object.new+ @client.define_singleton_method(:capture) { |event| events << event; true }+ $posthog_feedback = @client+ $posthog = mock("normal analytics client")+ $posthog.expects(:capture).never+ @cache = ActiveSupport::Cache::MemoryStore.new+ Rails.stubs(:cache).returns(@cache)+ Rails.env.stubs(:production?).returns(true)+ @config = Rails.configuration.x.posthog+ @config.stubs(:api_key).returns(nil)+ @config.stubs(:feedback_enabled).returns(true)+ sign_in @user+ end++ teardown do+ $posthog_feedback = @previous_client+ $posthog = @previous_normal_client+ travel_back+ end++ test "successful UI responses capture the first preview state once per user and day" do+ get settings_preferences_url, headers: { "REMOTE_ADDR" => "203.0.113.42" }+ assert_response :success+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))+ get settings_preferences_url++ assert_equal 1, @events.size+ event = @events.first+ assert_equal "web_ui_served_daily", event[:event]+ assert_equal({ preview_features_enabled: false, sure_version: Sure.version.to_s,+ "$process_person_profile" => false, "$geoip_disable" => false,+ "$ip" => "203.0.113.42" }, event[:properties])+ assert_match(/\A[0-9a-f]{64}\z/, event[:distinct_id])+ assert_not_includes event.to_json, @user.id+ assert_not_includes event.to_json, @user.email+ end++ test "GeoIP uses the client address Rails resolves through trusted proxies" do+ [+ { forwarded: "198.51.100.9, 203.0.113.42, 10.0.0.1", remote: "10.0.0.2", expected: "203.0.113.42" },+ { forwarded: "2001:db8::123, fd00::1", remote: "::1", expected: "2001:db8::123" }+ ].each do |example|+ @cache.clear+ get settings_preferences_url, headers: { "X-Forwarded-For" => example[:forwarded], "REMOTE_ADDR" => example[:remote] }++ assert_response :success+ assert_equal example[:expected], @events.last[:properties]["$ip"]+ assert_equal false, @events.last[:properties]["$geoip_disable"]+ end+ end++ test "another browser session for the same user shares the daily claim" do+ get settings_preferences_url+ browser = open_session+ browser.post sessions_url, params: { email: @user.email, password: user_password_test }+ browser.get settings_preferences_url++ assert_equal 1, @events.size+ end++ test "different users have independent daily claims and opaque identifiers" do+ get settings_preferences_url+ other = users(:family_member)+ other.update!(preferences: other.preferences.merge("preview_features_enabled" => true))+ sign_in other+ get settings_preferences_url++ assert_equal [ false, true ], @events.map { |event| event[:properties][:preview_features_enabled] }+ assert_not_equal @events.first[:distinct_id], @events.last[:distinct_id]+ end++ test "the next family-local calendar day records the new preference" do+ @user.family.update!(timezone: "America/Los_Angeles")+ travel_to Time.utc(2026, 10, 2, 6, 59)+ get settings_preferences_url+ @user.update!(preferences: @user.preferences.merge("preview_features_enabled" => true))+ travel_to Time.utc(2026, 10, 2, 7)+ get settings_preferences_url++ assert_equal [ false, true ], @events.map { |event| event[:properties][:preview_features_enabled] }+ assert_not_equal @events.first[:distinct_id], @events.last[:distinct_id]+ end++ test "the daily identifier remains stable if the cache is cleared" do+ get settings_preferences_url+ @cache.clear+ get settings_preferences_url++ assert_equal 2, @events.size+ assert_equal @events.first[:distinct_id], @events.last[:distinct_id]+ end++ test "HEAD requests redirects errors and logged-out pages do not count" do+ head settings_preferences_url+ assert_response :success+ get insights_url+ assert_response :redirect+ get account_url(SecureRandom.uuid)+ assert_response :not_found+ delete session_url(Current.session)+ get new_session_url+ assert_response :success++ assert_empty @events+ end++ test "browser and Turbo prefetch or prerender requests do not count" do+ %w[Purpose Sec-Purpose X-Sec-Purpose].each do |header|+ get settings_preferences_url, headers: { header => "prefetch;prerender" }+ assert_response :success+ end++ assert_empty @events+ end++ test "authenticated API JSON and non-GET UI requests do not count" do+ api_key = @user.api_keys.create!(name: "Usage test", scopes: [ "read" ],+ source: "web", display_key: "usage-test-#{SecureRandom.hex(8)}")+ get "/api/v1/accounts", headers: { "X-Api-Key" => api_key.display_key, "Accept" => "text/html" }+ assert_response :success+ assert_equal "application/json", response.media_type+ patch settings_preferences_url, params: { user: { preview_features_enabled: "1" } }+ assert_response :redirect++ assert_empty @events+ end++ test "AJAX and Turbo frame requests do not count as full UI responses" do+ get settings_preferences_url, headers: { "X-Requested-With" => "XMLHttpRequest" }+ assert_response :success+ get settings_preferences_url, headers: { "Turbo-Frame" => "drawer" }+ assert_response :success++ assert_empty @events+ end++ test "both hosting modes send only to shared feedback without operator analytics configuration" do+ %w[managed self_hosted].each do |mode|+ @cache.clear+ Rails.configuration.stubs(:app_mode).returns(mode.inquiry)+ get settings_preferences_url+ assert_response :success+ end++ assert_equal 2, @events.size+ end++ test "shared feedback opt-out or missing server client skips capture" do+ @config.stubs(:feedback_enabled).returns(false)+ get settings_preferences_url+ @config.stubs(:feedback_enabled).returns(true)+ $posthog_feedback = nil+ get settings_preferences_url++ assert_empty @events+ end++ test "configured operator analytics does not receive a duplicate" do+ @config.stubs(:api_key).returns("public-test-key")+ get settings_preferences_url++ assert_response :success+ assert_equal 1, @events.size+ end++ test "the existing environment gate requires explicit development opt-in" do+ Rails.env.stubs(:production?).returns(false)+ Rails.env.stubs(:development?).returns(true)+ @config.stubs(:development_enabled).returns(false)+ get settings_preferences_url+ assert_empty @events+ @config.stubs(:development_enabled).returns(true)+ get settings_preferences_url+ assert_equal 1, @events.size+ end++ test "null cache and unsuccessful cache claims skip capture" do+ Rails.stubs(:cache).returns(ActiveSupport::Cache::NullStore.new)+ get settings_preferences_url+ Rails.stubs(:cache).returns(@cache)+ @cache.stubs(:write).returns(false)+ get settings_preferences_url++ assert_response :success+ assert_empty @events+ end++ test "a cache claim failure cannot fail the UI response" do+ original_write = @cache.method(:write)+ @cache.define_singleton_method(:write) do |key, *args, **options|+ raise IOError, "cache unavailable" if key.is_a?(Array) && key.first == "daily-web-usage"+ original_write.call(key, *args, **options)+ end+ get settings_preferences_url++ assert_response :success+ assert_empty @events+ end++ test "SDK rejection or failure consumes one attempt without failing the UI" do+ [ false, StandardError.new("SDK unavailable") ].each do |result|+ @cache.clear+ calls = 0+ @client.define_singleton_method(:capture) do |_event|+ calls += 1+ raise result if result.is_a?(Exception)+ result+ end+ 2.times do+ get settings_preferences_url+ assert_response :success+ end+ assert_equal 1, calls+ end+ end+enddiff --git a/test/initializers/posthog_test.rb b/test/initializers/posthog_test.rbnew file mode 100644index 0000000000..414f76d1da--- /dev/null+++ b/test/initializers/posthog_test.rb@@ -0,0 +1,76 @@+require "test_helper"++class PosthogTest < ActiveSupport::TestCase+ setup do+ @previous_config = Rails.configuration.x.posthog+ @previous_normal_client = $posthog+ @previous_feedback_client = $posthog_feedback+ $posthog = $posthog_feedback = nil+ Rails.env.stubs(:production?).returns(false)+ Rails.env.stubs(:development?).returns(false)+ end++ teardown do+ Rails.configuration.x.posthog = @previous_config+ $posthog = @previous_normal_client+ $posthog_feedback = @previous_feedback_client+ end++ test "production feedback uses the bundled project independently of operator analytics" do+ Rails.env.stubs(:production?).returns(true)+ normal_client = mock("normal analytics")+ feedback_client = mock("shared feedback")+ PostHog::Client.expects(:new).with(has_entries(api_key: "operator-test-key", host: "https://analytics.example.test")).returns(normal_client)+ PostHog::Client.expects(:new).with(has_entries(@previous_config.self_hosted_feedback_project)).returns(feedback_client)++ load_initializer(POSTHOG_KEY: "operator-test-key", POSTHOG_HOST: "https://analytics.example.test")++ assert_same normal_client, $posthog+ assert_same feedback_client, $posthog_feedback+ end++ test "feedback opt-out does not initialize the shared client" do+ Rails.env.stubs(:production?).returns(true)+ PostHog::Client.expects(:new).never++ load_initializer(POSTHOG_FEEDBACK_ENABLED: "false")++ assert_nil $posthog_feedback+ end++ test "development requires explicit opt-in" do+ Rails.env.stubs(:development?).returns(true)+ PostHog::Client.expects(:new).never++ load_initializer++ assert_nil $posthog_feedback+ end++ test "development opt-in uses the shared project without operator configuration" do+ Rails.env.stubs(:development?).returns(true)+ feedback_client = mock("shared feedback")+ PostHog::Client.expects(:new).with(has_entries(@previous_config.self_hosted_feedback_project)).returns(feedback_client)++ load_initializer(POSTHOG_DEVELOPMENT_ENABLED: "true")++ assert_same feedback_client, $posthog_feedback+ assert_nil $posthog+ end++ test "development opt-in does not initialize feedback in automated tests" do+ PostHog::Client.expects(:new).never++ load_initializer(POSTHOG_DEVELOPMENT_ENABLED: "true")++ assert_nil $posthog_feedback+ end++ private+ def load_initializer(**overrides)+ with_env_overrides({ POSTHOG_KEY: nil, POSTHOG_HOST: nil, POSTHOG_FEEDBACK_ENABLED: "true",+ POSTHOG_DEVELOPMENT_ENABLED: "false" }.merge(overrides)) do+ load Rails.root.join("config/initializers/posthog.rb")+ end+ end+enddiff --git a/test/models/hosted_usage_test.rb b/test/models/hosted_usage_test.rbnew file mode 100644index 0000000000..28b981256b--- /dev/null+++ b/test/models/hosted_usage_test.rb@@ -0,0 +1,203 @@+require "test_helper"++class HostedUsageTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper++ setup do+ travel_to Time.zone.local(2026, 10, 1, 12)+ # Existing fixtures should not look like newly recorded trials in this test.+ Subscription.update_all(created_at: 60.days.ago)+ end++ teardown do+ travel_back+ end++ test "availability requires the exact trusted deployment and matching request host" do+ %w[app.sure.am demo.sure.am].each do |host|+ with_env_overrides("APP_DOMAIN" => host) do+ assert HostedUsage.available?(request_host: host)+ refute HostedUsage.available?(request_host: "sure-app.onrender.com")+ refute HostedUsage.available?(request_host: "#{host}.example.com")+ refute HostedUsage.available?(request_host: "#{host}.")+ end+ end++ [ nil, "", "sure-app.onrender.com", "example.com", "https://app.sure.am",+ "app.sure.am:443", "*.sure.am", "APP.SURE.AM", " app.sure.am" ].each do |configured|+ with_env_overrides("APP_DOMAIN" => configured) do+ refute HostedUsage.available?(request_host: "app.sure.am"), configured.inspect+ refute HostedUsage.available?(request_host: "demo.sure.am"), configured.inspect+ end+ end+ with_env_overrides("APP_DOMAIN" => "app.sure.am") do+ refute HostedUsage.available?(request_host: "demo.sure.am")+ end+ end++ test "recent trial records include window boundaries and converted trials without claiming people" do+ lower = trial_family(created_at: 30.days.ago)+ current = trial_family(created_at: Time.current)+ converted = trial_family(created_at: 3.days.ago, status: "active", stripe_id: "sub_Converted")+ trial_family(created_at: 30.days.ago - 1.second)+ trial_family(created_at: Time.current + 1.second)+ Family.create!.create_subscription!(status: "active", stripe_id: "sub_NoTrial", created_at: 2.days.ago)+ create_user(lower)+ create_user(lower)+ create_user(current)+ create_user(converted)++ usage = HostedUsage.new++ assert_equal 3, usage.summary.fetch(:trial_households_count)+ assert_equal 4, usage.summary.fetch(:trial_members_count)+ assert_equal [ lower.id, current.id, converted.id ].sort, usage.trials.map(&:family_id).sort+ assert_equal "active", usage.trials.find { |row| row.family_id == converted.id }.status+ assert_equal 30.days.ago, usage.window_start+ assert_equal Time.current, usage.as_of+ end++ test "sessions are retained rows for enabled members with a separate creation window" do+ family = trial_family+ enabled = create_user(family)+ disabled = create_user(family)+ disabled.update_column(:active, false)+ enabled.sessions.create!(created_at: 40.days.ago)+ enabled.sessions.create!(created_at: 30.days.ago)+ enabled.sessions.create!(created_at: Time.current)+ disabled.sessions.create!(created_at: 1.day.ago)+ removed = enabled.sessions.create!(created_at: 2.days.ago)+ removed.destroy!++ row = HostedUsage.new.trials.find { |trial| trial.family_id == family.id }++ assert_equal 2, row.member_count+ assert_equal 3, row.retained_sessions_count+ assert_equal 2, row.sessions_created_in_window_count+ assert_equal Time.current, row.latest_session_created_at+ end++ test "cleanup matches the existing scope including strict grace boundaries" do+ expired = trial_family(trial_ends_at: 14.days.ago - 1.second, status: "paused")+ boundary = trial_family(trial_ends_at: 14.days.ago, status: "paused")+ old_empty = Family.create!(created_at: 59.days.ago - 1.second)+ boundary_empty = Family.create!(created_at: 59.days.ago)+ active = trial_family(trial_ends_at: 30.days.ago, status: "active", stripe_id: "sub_Active")+ # Recent login does not remove a family from the application's actual scope.+ create_user(expired).sessions.create!++ usage = HostedUsage.new+ candidates = usage.cleanup_candidates.index_by(&:family_id)++ assert_equal Family.inactive_trial_for_cleanup.count, usage.summary.fetch(:cleanup_eligible_count)+ assert_equal :expired_trial_grace_elapsed, candidates.fetch(expired.id).reason+ assert_equal :no_subscription_grace_elapsed, candidates.fetch(old_empty.id).reason+ refute candidates.key?(boundary.id)+ refute candidates.key?(boundary_empty.id)+ refute candidates.key?(active.id)+ assert usage.trials.find { |row| row.family_id == expired.id }.cleanup_eligible+ with_self_hosting { refute usage.cleanup_enabled? }+ end++ test "supporters require both Stripe-shaped links and preserve every local status" do+ active = trial_family(status: "active", stripe_id: "sub_ActiveSupport")+ active.update!(stripe_customer_id: "cus_ActiveSupport")+ canceled = trial_family(status: "canceled", stripe_id: "sub_CanceledSupport")+ canceled.update!(stripe_customer_id: "cus_CanceledSupport")+ trial_family(status: "active", stripe_id: "sub_MissingCustomer")+ demo = trial_family(status: "active", stripe_id: "sub_demo_123")+ demo.update!(stripe_customer_id: "cus_Demo")+ trial_family++ usage = HostedUsage.new++ assert_equal 1, usage.summary.fetch(:active_supporter_households_count)+ assert_equal 2, usage.summary.fetch(:supporter_subscription_count)+ assert_equal 1, usage.supporter_status_counts.fetch("active")+ assert_equal 1, usage.supporter_status_counts.fetch("canceled")+ assert_equal 0, usage.supporter_status_counts.fetch("past_due")+ assert usage.trials.find { |row| row.family_id == demo.id }.synthetic_demo+ end++ test "expiring soon matches the indicator moved from Users admin" do+ baseline = Subscription.where(status: :trialing).where(trial_ends_at: Time.current..7.days.from_now).count+ trial_family(trial_ends_at: Time.current)+ trial_family(trial_ends_at: 7.days.from_now)+ trial_family(trial_ends_at: 7.days.from_now + 1.second)+ trial_family(trial_ends_at: 1.second.ago)+ trial_family(trial_ends_at: 1.day.from_now, status: "paused")++ usage = HostedUsage.new++ assert_equal baseline + 2, usage.summary.fetch(:trials_expiring_soon_count)+ assert_equal 7.days.from_now, usage.expiring_window_end+ end++ test "detail is bounded while summary includes all recent trials" do+ 3.times { trial_family }+ usage = HostedUsage.new+ usage.stubs(:row_limit).returns(2)++ assert_equal 3, usage.summary.fetch(:trial_households_count)+ assert_equal 2, usage.trials.length+ end++ test "empty trial cohorts have empty detail and zero member counts" do+ usage = HostedUsage.new++ assert_equal 0, usage.summary.fetch(:trial_households_count)+ assert_equal 0, usage.summary.fetch(:trial_members_count)+ assert_empty usage.trials+ end++ test "all supported local Stripe statuses remain visible" do+ Subscription.statuses.each_key do |status|+ family = trial_family(status:, stripe_id: "sub_Status#{status.delete('_')}")+ family.update!(stripe_customer_id: "cus_Status#{status.delete('_')}")+ end++ assert_equal Subscription.statuses.keys.index_with(1), HostedUsage.new.supporter_status_counts+ end++ test "cleanup detail is independently bounded while its count uses the full scope" do+ 3.times { Family.create!(created_at: 60.days.ago) }+ usage = HostedUsage.new+ usage.stubs(:row_limit).returns(2)++ assert_equal Family.inactive_trial_for_cleanup.count, usage.summary.fetch(:cleanup_eligible_count)+ assert_operator usage.summary.fetch(:cleanup_eligible_count), :>=, 3+ assert_equal 2, usage.cleanup_candidates.length+ end++ test "snapshot uses bounded grouped queries and performs no writes or provider calls" do+ 3.times { create_user(trial_family).sessions.create! }+ Provider::Registry.expects(:get_provider).never+ DestroyJob.expects(:perform_later).never+ InactiveFamilyCleanerJob.expects(:perform_later).never++ usage = HostedUsage.new+ queries = capture_sql_queries do+ assert_no_enqueued_jobs do+ usage.summary+ usage.trials+ usage.cleanup_candidates+ usage.supporter_status_counts+ end+ end++ assert queries.all? { |query| query.start_with?("SELECT") }, queries.join("\n")+ assert_operator queries.length, :<=, 14+ assert_empty capture_sql_queries { usage.summary; usage.trials; usage.cleanup_candidates; usage.supporter_status_counts }+ end++ private+ def trial_family(created_at: 1.day.ago, trial_ends_at: 44.days.from_now, status: "trialing", stripe_id: nil)+ family = Family.create!(name: "Usage test", created_at: created_at)+ family.create_subscription!(created_at:, trial_ends_at:, status:, stripe_id:)+ family+ end++ def create_user(family)+ User.create!(family:, email: "usage-#{SecureRandom.uuid}@example.com", password: "testpassword123", role: :admin)+ end+enddiff --git a/test/system/admin/system_health_hosted_usage_test.rb b/test/system/admin/system_health_hosted_usage_test.rbnew file mode 100644index 0000000000..cc7c12492c--- /dev/null+++ b/test/system/admin/system_health_hosted_usage_test.rb@@ -0,0 +1,87 @@+require "application_system_test_case"++class Admin::SystemHealthHostedUsageTest < ApplicationSystemTestCase+ setup do+ sign_in users(:sure_support_staff)+ # Host/deployment combinations are exercised by integration tests. The+ # browser here reaches Capybara's local server, not the production domains.+ HostedUsage.stubs(:available?).returns(true)+ stub_healthy_sidekiq+ end++ test "hosted usage loads when selected and stays read only at desktop and mobile widths" do+ label_screenshot_fixtures+ subscriptions(:trialing).update!(created_at: 2.days.ago, trial_ends_at: 3.days.from_now)+ subscriptions(:active).update!(stripe_id: "sub_supporter")+ families(:dylan_family).update!(stripe_customer_id: "cus_supporter")++ visit admin_system_health_path+ assert_selector "turbo-frame#hosted_usage[loading='lazy']:not([complete])", visible: :all+ click_button "Hosted usage"++ assert_current_path admin_system_health_path(tab: "hosted_usage")+ assert_selector "button[role='tab'][aria-selected='true']", text: "Hosted usage"+ within "turbo-frame#hosted_usage" do+ assert_text "Recent trial households"+ assert_text(/Retained sign-in sessions/i)+ assert_text "Local supporter status"+ assert_text "not currently online users or visits"+ assert_selector "[data-testid='hosted-usage-trials_expiring_soon_count'] dd", text: "1"+ assert_no_selector "form, button, a[data-turbo-method]"+ end+ page.save_screenshot(Rails.root.join("tmp", "system-health-hosted-usage.png"))++ page.current_window.resize_to(390, 844)+ within "turbo-frame#hosted_usage" do+ assert_selector "[role='region'][aria-label='Recent trial households'][tabindex='0']"+ assert_no_selector "form, button, a[data-turbo-method]"+ end+ assert page.evaluate_script("document.documentElement.scrollWidth <= window.innerWidth"), "The report must not overflow the mobile page"+ page.save_screenshot(Rails.root.join("tmp", "system-health-hosted-usage-mobile.png"))+ end++ test "Users page no longer shows the trial expiry summary" do+ label_screenshot_fixtures+ visit admin_users_path++ assert_no_text I18n.t("admin.system_health.hosted_usage.summary.trials_expiring_soon_count", raise: true)+ assert_selector "h1", text: I18n.t("admin.users.index.title")+ page.save_screenshot(Rails.root.join("tmp", "admin-users-without-trial-summary.png"))+ end++ test "unavailable installations omit the tab even when requested in the URL" do+ HostedUsage.stubs(:available?).returns(false)+ HostedUsage.expects(:new).never++ visit admin_system_health_path(tab: "hosted_usage")++ assert_selector "button[role='tab'][aria-selected='true']", text: "Background jobs"+ assert_no_selector "button[role='tab']", text: "Hosted usage"+ assert_no_selector "turbo-frame#hosted_usage", visible: :all+ end++ private+ # Screenshots may be shared in the PR. Use obviously synthetic labels even+ # though this database contains only the repository's test fixtures.+ def label_screenshot_fixtures+ Family.order(:id).each_with_index do |family, index|+ family.update_columns(name: "Fixture household #{index + 1}")+ end+ User.order(:id).each_with_index do |user, index|+ user.update_columns(first_name: "Fixture", last_name: "Member #{index + 1}",+ email: "fixture-member-#{index + 1}@example.invalid")+ end+ end++ def stub_healthy_sidekiq+ SidekiqHealth.any_instance.stubs(:healthy?).returns(true)+ SidekiqHealth.any_instance.stubs(:processes_count).returns(1)+ SidekiqHealth.any_instance.stubs(:last_heartbeat_at).returns(Time.current)+ SidekiqHealth.any_instance.stubs(:max_queue_latency).returns(0.0)+ SidekiqHealth.any_instance.stubs(:enqueued_count).returns(0)+ SidekiqHealth.any_instance.stubs(:retry_count).returns(0)+ SidekiqHealth.any_instance.stubs(:failed_count).returns(0)+ SidekiqHealth.any_instance.stubs(:processed_count).returns(42)+ SidekiqHealth.any_instance.stubs(:queue_breakdown).returns([])+ end+end