# frozen_string_literal: true require "rails_helper" RSpec.describe Admin::CostAnalytics do let!(:coach) do User.create!(email: "cost-coach@test.it", name: "Coach", password: "Password123", role: "coach") end let!(:club) { Club.create!(name: "Tigers Club", sport: "volleyball") } let!(:team) { club.teams.create!(name: "Tigers U16", sport_key: "pallavolo") } let!(:match) { team.matches.create!(opponent_name: "Rival", sport_key: "pallavolo") } let(:month) { Date.new(2024, 3, 1) } before do PlatformCostEntry.delete_all PlatformCostEntry.create!( month: month, label: "Hetzner", amount_cents: 10_000 ) StreamSession.create!( match: match, user: coach, platform: "matchlivetv", status: "ended", started_at: month + 1.day + 10.hours, ended_at: month + 1.day + 11.hours, total_duration_secs: 3600 ) Billing::Payment.create!( club: club, amount_cents: 5_900, currency: "EUR", status: "paid", provider: "stripe", paid_at: month + 2.days ) end it "calcola KPI e allocazione per società" do analytics = Admin::CostAnalytics.new(month: month) summary = analytics.summary expect(summary[:cost_cents]).to eq(10_000) expect(summary[:sessions]).to eq(1) expect(summary[:hours]).to eq(1.0) expect(summary[:revenue_cents]).to eq(5_900) expect(summary[:margin_cents]).to eq(-4_100) expect(summary[:cost_per_hour_cents]).to eq(10_000) clubs = analytics.club_breakdown expect(clubs.size).to eq(1) expect(clubs.first[:club_name]).to eq("Tigers Club") expect(clubs.first[:allocated_cost_cents]).to eq(10_000) expect(clubs.first[:revenue_cents]).to eq(5_900) end it "ricalcola dopo modifica delle voci di costo" do PlatformCostEntry.create!(month: month, label: "S3", amount_cents: 2_000) summary = Admin::CostAnalytics.new(month: month).summary expect(summary[:cost_cents]).to eq(12_000) expect(summary[:cost_per_session_cents]).to eq(12_000) end end