Compare commits
61 Commits
3d3420cc4a
...
feature/na
| Author | SHA1 | Date | |
|---|---|---|---|
| f3ff657fc2 | |||
| 68b4390282 | |||
| 499aee8988 | |||
| 854738b46d | |||
| 1058c644bd | |||
| 3ef3c59d94 | |||
| 61bb22ce44 | |||
| 10fff7ffcb | |||
| d835bce148 | |||
| 4c7be615f1 | |||
| fde1213ca5 | |||
| 841e99c775 | |||
| 02ff1de0f6 | |||
| 8263475146 | |||
| bac655aca8 | |||
| d08cd36527 | |||
| 2c5f4f82eb | |||
| 2ccbfea75e | |||
| 1d67459bbe | |||
| 9fd4d865b3 | |||
| 70e704827e | |||
| fd7a5c2c8e | |||
| 8139d84d88 | |||
| ab9cb02083 | |||
| fd225fbadd | |||
| 565bc2c548 | |||
| 1f273f849d | |||
| a87cda156b | |||
| 1bd81d84af | |||
| 8882e7854f | |||
| 422d8848f6 | |||
| 787161807c | |||
| 1677df7f86 | |||
| 1fb5cd5aa2 | |||
| 6ac4db98bb | |||
| 92c0058085 | |||
| 9b40deeb61 | |||
| 82ff1972a0 | |||
| 566104aff4 | |||
| 2cb267f991 | |||
| d051d60415 | |||
| cd8e97243f | |||
| 71eaf9cf56 | |||
| 462f050977 | |||
| d0552e1aaa | |||
| 994c1e3c09 | |||
| 1a84d6ae42 | |||
| 2b8f842752 | |||
| 964e3f472c | |||
| b073ded6c1 | |||
| ef805984ee | |||
| 15e57cddee | |||
| cf06acf24d | |||
| 1901fcce68 | |||
| 62d86d16ec | |||
| a5e781729c | |||
| 148402a97c | |||
| f4b7be0f80 | |||
| 4083bc5dee | |||
| 471291b2c4 | |||
| 3a5649f482 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -20,6 +20,9 @@ infra/certs/
|
|||||||
infra/recordings/
|
infra/recordings/
|
||||||
infra/.env
|
infra/.env
|
||||||
infra/.env.production.generated
|
infra/.env.production.generated
|
||||||
|
infra/garage/dev-credentials.env
|
||||||
|
infra/garage/prod-credentials.env
|
||||||
|
infra/garage/garage.prod.toml
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|||||||
21
README.md
21
README.md
@@ -2,13 +2,13 @@
|
|||||||
|
|
||||||
Piattaforma mobile-first per streaming di partite sportive giovanili — MVP su **Match Live TV** (HLS sul nostro sito); YouTube/Facebook/Twitch come integrazioni premium.
|
Piattaforma mobile-first per streaming di partite sportive giovanili — MVP su **Match Live TV** (HLS sul nostro sito); YouTube/Facebook/Twitch come integrazioni premium.
|
||||||
|
|
||||||
**Slogan:** *Lo streaming che non muore*
|
**Slogan:** *Ogni partita, ogni evento, per i tuoi tifosi.*
|
||||||
|
|
||||||
## Struttura monorepo
|
## Struttura monorepo
|
||||||
|
|
||||||
```
|
```
|
||||||
├── backend/ # Rails 7.2 API + Action Cable + Sidekiq
|
├── backend/ # Rails 7.2 API + Action Cable + Sidekiq
|
||||||
├── mobile/ # Flutter app (Camera + Regia)
|
├── native/android/ # App Android nativa (Kotlin + Compose)
|
||||||
├── infra/ # Docker Compose, MediaMTX, Nginx, Kamal
|
├── infra/ # Docker Compose, MediaMTX, Nginx, Kamal
|
||||||
└── docs/ # Documentazione
|
└── docs/ # Documentazione
|
||||||
```
|
```
|
||||||
@@ -45,15 +45,16 @@ email: coach@matchlivetv.test
|
|||||||
password: password123
|
password: password123
|
||||||
```
|
```
|
||||||
|
|
||||||
## Mobile
|
## App Android nativa
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd mobile
|
./scripts/build_native_android_apk_prod.sh
|
||||||
flutter pub get
|
adb install -r native/android/app/build/outputs/apk/release/app-release.apk
|
||||||
flutter run
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Configura `API_BASE_URL` in `lib/core/config.dart` (default `http://10.0.2.2:3000` per emulatore Android).
|
API produzione: `https://www.matchlivetv.it` (override con `-PAPI_BASE_URL=...` in Gradle).
|
||||||
|
|
||||||
|
Vedi [native/android/README.md](native/android/README.md).
|
||||||
|
|
||||||
## Architettura
|
## Architettura
|
||||||
|
|
||||||
@@ -62,9 +63,9 @@ Configura `API_BASE_URL` in `lib/core/config.dart` (default `http://10.0.2.2:300
|
|||||||
- Controllo: Phone ↔ Action Cable ↔ Rails ↔ PostgreSQL
|
- Controllo: Phone ↔ Action Cable ↔ Rails ↔ PostgreSQL
|
||||||
- Disconnessioni: MediaMTX `alwaysAvailable` slate + timeout 5 min (Sidekiq)
|
- Disconnessioni: MediaMTX `alwaysAvailable` slate + timeout 5 min (Sidekiq)
|
||||||
|
|
||||||
### Mobile produzione
|
### App Android produzione
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./scripts/run_mobile_android_prod.sh
|
./scripts/build_native_android_apk_prod.sh
|
||||||
# API: https://matchlivetv.eminux.it
|
# API: https://www.matchlivetv.it
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
FROM ruby:3.3-bookworm
|
FROM ruby:3.3-bookworm
|
||||||
|
|
||||||
RUN apt-get update -qq && \
|
RUN apt-get update -qq && \
|
||||||
apt-get install -y --no-install-recommends build-essential libpq-dev curl ffmpeg && \
|
apt-get install -y --no-install-recommends build-essential libpq-dev curl ffmpeg librsvg2-bin fonts-dejavu-core && \
|
||||||
rm -rf /var/lib/apt/lists/*
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ gem "attr_encrypted"
|
|||||||
gem "google-apis-youtube_v3"
|
gem "google-apis-youtube_v3"
|
||||||
gem "faraday"
|
gem "faraday"
|
||||||
gem "stripe"
|
gem "stripe"
|
||||||
|
gem "aws-sdk-s3", "~> 1.0", require: false
|
||||||
gem "kamal", require: false
|
gem "kamal", require: false
|
||||||
|
|
||||||
group :development, :test do
|
group :development, :test do
|
||||||
|
|||||||
@@ -81,6 +81,25 @@ GEM
|
|||||||
ast (2.4.3)
|
ast (2.4.3)
|
||||||
attr_encrypted (4.2.0)
|
attr_encrypted (4.2.0)
|
||||||
encryptor (~> 3.0.0)
|
encryptor (~> 3.0.0)
|
||||||
|
aws-eventstream (1.4.0)
|
||||||
|
aws-partitions (1.1256.0)
|
||||||
|
aws-sdk-core (3.251.0)
|
||||||
|
aws-eventstream (~> 1, >= 1.3.0)
|
||||||
|
aws-partitions (~> 1, >= 1.992.0)
|
||||||
|
aws-sigv4 (~> 1.9)
|
||||||
|
base64
|
||||||
|
bigdecimal
|
||||||
|
jmespath (~> 1, >= 1.6.1)
|
||||||
|
logger
|
||||||
|
aws-sdk-kms (1.129.0)
|
||||||
|
aws-sdk-core (~> 3, >= 3.248.0)
|
||||||
|
aws-sigv4 (~> 1.5)
|
||||||
|
aws-sdk-s3 (1.225.0)
|
||||||
|
aws-sdk-core (~> 3, >= 3.248.0)
|
||||||
|
aws-sdk-kms (~> 1)
|
||||||
|
aws-sigv4 (~> 1.5)
|
||||||
|
aws-sigv4 (1.12.1)
|
||||||
|
aws-eventstream (~> 1, >= 1.0.2)
|
||||||
base64 (0.3.0)
|
base64 (0.3.0)
|
||||||
bcrypt (3.1.22)
|
bcrypt (3.1.22)
|
||||||
bcrypt_pbkdf (1.1.2)
|
bcrypt_pbkdf (1.1.2)
|
||||||
@@ -158,6 +177,7 @@ GEM
|
|||||||
prism (>= 1.3.0)
|
prism (>= 1.3.0)
|
||||||
rdoc (>= 4.0.0)
|
rdoc (>= 4.0.0)
|
||||||
reline (>= 0.4.2)
|
reline (>= 0.4.2)
|
||||||
|
jmespath (1.6.2)
|
||||||
json (2.19.5)
|
json (2.19.5)
|
||||||
jwt (3.2.0)
|
jwt (3.2.0)
|
||||||
base64
|
base64
|
||||||
@@ -416,6 +436,7 @@ PLATFORMS
|
|||||||
DEPENDENCIES
|
DEPENDENCIES
|
||||||
aasm
|
aasm
|
||||||
attr_encrypted
|
attr_encrypted
|
||||||
|
aws-sdk-s3 (~> 1.0)
|
||||||
bcrypt (~> 3.1.7)
|
bcrypt (~> 3.1.7)
|
||||||
bootsnap
|
bootsnap
|
||||||
brakeman
|
brakeman
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
module ApplicationCable
|
module ApplicationCable
|
||||||
class Connection < ActionCable::Connection::Base
|
class Connection < ActionCable::Connection::Base
|
||||||
identified_by :current_user
|
identified_by :current_user, :regia_session
|
||||||
|
|
||||||
def connect
|
def connect
|
||||||
|
if (regia_token = request.params[:regia_token].presence)
|
||||||
|
self.regia_session = Sessions::RegiaAccess.find_session_by_token(regia_token)
|
||||||
|
reject_unauthorized_connection unless regia_session
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
payload = JsonWebToken.decode(token_from_header)
|
payload = JsonWebToken.decode(token_from_header)
|
||||||
self.current_user = User.find_by(id: payload[:user_id]) if payload
|
self.current_user = User.find_by(id: payload[:user_id]) if payload
|
||||||
reject_unauthorized_connection unless current_user
|
reject_unauthorized_connection unless current_user
|
||||||
|
|||||||
@@ -1,19 +1,31 @@
|
|||||||
class SessionChannel < ApplicationCable::Channel
|
class SessionChannel < ApplicationCable::Channel
|
||||||
include CableBroadcastable
|
include CableBroadcastable
|
||||||
def subscribed
|
def subscribed
|
||||||
session = StreamSession.joins(match: :team)
|
session = resolve_session
|
||||||
.merge(current_user.teams)
|
reject unless session && session.id.to_s == params[:session_id].to_s
|
||||||
.find(params[:session_id])
|
|
||||||
stream_for session
|
stream_for session
|
||||||
session.device_states.find_or_create_by!(device_role: params[:device_role] || "controller")
|
session.device_states.find_or_create_by!(device_role: params[:device_role] || "controller")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def resolve_session
|
||||||
|
if connection.regia_session
|
||||||
|
connection.regia_session
|
||||||
|
else
|
||||||
|
StreamSession.joins(match: :team)
|
||||||
|
.merge(connection.current_user.manageable_teams)
|
||||||
|
.find_by(id: params[:session_id])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def unsubscribed
|
def unsubscribed
|
||||||
stop_all_streams
|
stop_all_streams
|
||||||
end
|
end
|
||||||
|
|
||||||
def receive(data)
|
def receive(data)
|
||||||
session = StreamSession.find(params[:session_id])
|
session = resolve_session
|
||||||
|
return unless session
|
||||||
|
|
||||||
handle_message(session, data)
|
handle_message(session, data)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -41,20 +53,13 @@ class SessionChannel < ApplicationCable::Channel
|
|||||||
Sessions::Stop.new(session).call
|
Sessions::Stop.new(session).call
|
||||||
when "pause_stream"
|
when "pause_stream"
|
||||||
Sessions::Pause.new(session).call
|
Sessions::Pause.new(session).call
|
||||||
|
when "resume_stream"
|
||||||
|
Sessions::Resume.new(session).call
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def update_score(session, data)
|
def update_score(session, data)
|
||||||
score = session.score_state || session.create_score_state!
|
Scoring::SyncState.new(session: session, payload: data).call
|
||||||
score.update!(
|
|
||||||
home_sets: data["home_sets"] || score.home_sets,
|
|
||||||
away_sets: data["away_sets"] || score.away_sets,
|
|
||||||
home_points: data["home_points"] || score.home_points,
|
|
||||||
away_points: data["away_points"] || score.away_points,
|
|
||||||
current_set: data["current_set"] || score.current_set,
|
|
||||||
set_partials: data.key?("set_partials") ? data["set_partials"] : score.set_partials
|
|
||||||
)
|
|
||||||
SessionChannel.broadcast_message(session, score.as_cable_payload)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def update_timeout(session, data)
|
def update_timeout(session, data)
|
||||||
|
|||||||
25
backend/app/controllers/admin/auth_controller.rb
Normal file
25
backend/app/controllers/admin/auth_controller.rb
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
module Admin
|
||||||
|
class AuthController < Admin::BaseController
|
||||||
|
skip_before_action :require_admin_login, only: %i[new create]
|
||||||
|
|
||||||
|
def new
|
||||||
|
redirect_to admin_root_path if admin_logged_in?
|
||||||
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
account = AdminAccount.find_by(username: params[:username]&.strip)
|
||||||
|
if account&.authenticate(params[:password])
|
||||||
|
session[:admin_account_id] = account.id
|
||||||
|
redirect_to session.delete(:admin_return_to) || admin_root_path, notice: "Accesso effettuato"
|
||||||
|
else
|
||||||
|
flash.now[:alert] = "Username o password non validi"
|
||||||
|
render :new, status: :unauthorized
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def destroy
|
||||||
|
reset_session
|
||||||
|
redirect_to admin_login_path, notice: "Disconnesso"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,6 +1,30 @@
|
|||||||
module Admin
|
module Admin
|
||||||
class BaseController < ActionController::Base
|
class BaseController < ActionController::Base
|
||||||
layout "admin"
|
layout "admin"
|
||||||
protect_from_forgery with: :null_session
|
protect_from_forgery with: :exception
|
||||||
|
|
||||||
|
before_action :require_admin_login
|
||||||
|
|
||||||
|
include ::AdminHelper
|
||||||
|
helper_method :current_admin_account, :admin_logged_in?
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def require_admin_login
|
||||||
|
return if admin_logged_in?
|
||||||
|
|
||||||
|
session[:admin_return_to] = request.fullpath unless request.path == admin_login_path
|
||||||
|
redirect_to admin_login_path, alert: "Accedi per continuare"
|
||||||
|
end
|
||||||
|
|
||||||
|
def current_admin_account
|
||||||
|
return unless session[:admin_account_id]
|
||||||
|
|
||||||
|
@current_admin_account ||= AdminAccount.find_by(id: session[:admin_account_id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def admin_logged_in?
|
||||||
|
current_admin_account.present?
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
33
backend/app/controllers/admin/billing_controller.rb
Normal file
33
backend/app/controllers/admin/billing_controller.rb
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
module Admin
|
||||||
|
class BillingController < BaseController
|
||||||
|
def index
|
||||||
|
@pending_payments = pending_scope.recent
|
||||||
|
@completed_payments = Billing::Payment.with_invoice_pdf.includes(:club, :invoice).recent.limit(40)
|
||||||
|
@filter_club = Club.find_by(id: params[:club_id]) if params[:club_id].present?
|
||||||
|
@clubs = Club.order(:name)
|
||||||
|
end
|
||||||
|
|
||||||
|
def attach_pdf
|
||||||
|
payment = Billing::Payment.find(params[:payment_id])
|
||||||
|
Billing::AttachPaymentInvoice.call(payment: payment, pdf: params[:pdf])
|
||||||
|
redirect_to admin_billing_path(billing_redirect_params(payment)),
|
||||||
|
notice: "Fattura caricata e inviata a #{payment.club.billing_email}."
|
||||||
|
rescue Billing::AttachPaymentInvoice::Error, Billing::IssueInvoice::Error => e
|
||||||
|
payment ||= Billing::Payment.find_by(id: params[:payment_id])
|
||||||
|
redirect_to admin_billing_path(payment ? billing_redirect_params(payment) : {}),
|
||||||
|
alert: e.message
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def pending_scope
|
||||||
|
scope = Billing::Payment.awaiting_invoice_pdf.includes(:club, invoice: { pdf_attachment: :blob })
|
||||||
|
scope = scope.where(club_id: params[:club_id]) if params[:club_id].present?
|
||||||
|
scope
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing_redirect_params(payment)
|
||||||
|
{ club_id: payment.club_id, anchor: "payment-#{payment.id}" }.compact
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
84
backend/app/controllers/admin/billing_invoices_controller.rb
Normal file
84
backend/app/controllers/admin/billing_invoices_controller.rb
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
module Admin
|
||||||
|
class BillingInvoicesController < BaseController
|
||||||
|
before_action :set_club
|
||||||
|
before_action :set_invoice, only: %i[edit update]
|
||||||
|
|
||||||
|
def index
|
||||||
|
redirect_to admin_billing_path(club_id: @club.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
def new
|
||||||
|
redirect_to admin_billing_path(club_id: @club.id), alert: "Carica il PDF dalla lista «Pagamenti da fatturare»."
|
||||||
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
@invoice = @club.billing_invoices.build(invoice_params)
|
||||||
|
@invoice.source = "manual"
|
||||||
|
@invoice.status = "draft"
|
||||||
|
|
||||||
|
if @invoice.save
|
||||||
|
redirect_to edit_admin_club_billing_invoice_path(@club, @invoice),
|
||||||
|
notice: "Bozza creata. Carica il PDF dalla pagina Fatturazione o qui sotto."
|
||||||
|
else
|
||||||
|
@payment = @invoice.billing_payment
|
||||||
|
flash.now[:alert] = @invoice.errors.full_messages.join(", ")
|
||||||
|
render :new, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def edit
|
||||||
|
@payment = @invoice.billing_payment
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
@invoice.assign_attributes(invoice_params.except(:pdf))
|
||||||
|
|
||||||
|
if issuing?
|
||||||
|
Billing::IssueInvoice.call(invoice: @invoice, pdf: params.dig(:billing_invoice, :pdf))
|
||||||
|
redirect_to admin_billing_path(club_id: @club.id),
|
||||||
|
notice: "Fattura #{@invoice.number} emessa e inviata a #{@club.billing_email}."
|
||||||
|
elsif @invoice.save
|
||||||
|
redirect_to admin_billing_path(club_id: @club.id), notice: "Fattura #{@invoice.number} aggiornata."
|
||||||
|
else
|
||||||
|
@payment = @invoice.billing_payment
|
||||||
|
flash.now[:alert] = @invoice.errors.full_messages.join(", ")
|
||||||
|
render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
rescue Billing::IssueInvoice::Error => e
|
||||||
|
@payment = @invoice.billing_payment
|
||||||
|
flash.now[:alert] = e.message
|
||||||
|
render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_club
|
||||||
|
@club = Club.find(params[:club_id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_invoice
|
||||||
|
@invoice = @club.billing_invoices.find(params[:id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def issuing?
|
||||||
|
params[:commit].to_s == "Emetti e invia via email"
|
||||||
|
end
|
||||||
|
|
||||||
|
def invoice_params
|
||||||
|
params.require(:billing_invoice).permit(
|
||||||
|
:number,
|
||||||
|
:issued_on,
|
||||||
|
:amount_cents,
|
||||||
|
:amount_euros,
|
||||||
|
:currency,
|
||||||
|
:billing_payment_id,
|
||||||
|
:notes,
|
||||||
|
:pdf
|
||||||
|
).tap do |p|
|
||||||
|
if p[:amount_euros].present?
|
||||||
|
p[:amount_cents] = (p.delete(:amount_euros).to_f * 100).round
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
46
backend/app/controllers/admin/clubs_controller.rb
Normal file
46
backend/app/controllers/admin/clubs_controller.rb
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
module Admin
|
||||||
|
class ClubsController < BaseController
|
||||||
|
before_action :set_club, only: %i[show grant_comped revoke_comped]
|
||||||
|
|
||||||
|
def index
|
||||||
|
@clubs = Club.includes(:teams, subscription: %i[plan admin_comped_by])
|
||||||
|
.order(:name)
|
||||||
|
end
|
||||||
|
|
||||||
|
def show
|
||||||
|
@subscription = @club.subscription || @club.build_subscription(plan: Plan["free"], status: "active")
|
||||||
|
@plans = Plan.ordered.reject { |p| p.slug == "free" }
|
||||||
|
@teams = @club.teams.order(:name)
|
||||||
|
end
|
||||||
|
|
||||||
|
def grant_comped
|
||||||
|
Billing::AdminCompedSubscription.grant(
|
||||||
|
club: @club,
|
||||||
|
plan_slug: params.require(:plan_slug),
|
||||||
|
reason: params[:reason],
|
||||||
|
admin: current_admin_account
|
||||||
|
)
|
||||||
|
redirect_back_or_club notice: "Abbonamento omaggio #{Plan[params[:plan_slug]].name} attivato per #{@club.name}."
|
||||||
|
rescue Billing::AdminCompedSubscription::Error, ActiveRecord::RecordInvalid => e
|
||||||
|
redirect_back_or_club alert: e.message
|
||||||
|
end
|
||||||
|
|
||||||
|
def revoke_comped
|
||||||
|
Billing::AdminCompedSubscription.revoke(club: @club, admin: current_admin_account)
|
||||||
|
redirect_back_or_club notice: "Abbonamento omaggio revocato per #{@club.name}."
|
||||||
|
rescue Billing::AdminCompedSubscription::Error => e
|
||||||
|
redirect_back_or_club alert: e.message
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_club
|
||||||
|
@club = Club.find(params[:id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def redirect_back_or_club(notice: nil, alert: nil)
|
||||||
|
target = params[:return_to].presence || admin_club_path(@club)
|
||||||
|
redirect_to target, notice: notice, alert: alert
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,8 +1,19 @@
|
|||||||
module Admin
|
module Admin
|
||||||
class DashboardController < Admin::BaseController
|
class DashboardController < Admin::BaseController
|
||||||
def index
|
def index
|
||||||
@teams = Team.includes(:matches).order(:name)
|
@stats = DashboardStats.new.call
|
||||||
@active_sessions = StreamSession.where(status: %w[live reconnecting connecting]).includes(:match)
|
@host = HostMetrics.new.sample!
|
||||||
|
@active_sessions = StreamSession
|
||||||
|
.where(status: DashboardStats::ACTIVE_STATUSES)
|
||||||
|
.includes(match: :team)
|
||||||
|
.order(started_at: :desc)
|
||||||
|
@teams = Team.includes(:matches).order(:name).limit(8)
|
||||||
|
end
|
||||||
|
|
||||||
|
def metrics
|
||||||
|
host = HostMetrics.new.sample!
|
||||||
|
stats = DashboardStats.new.call
|
||||||
|
render json: { host: host, stats: stats, at: Time.current.iso8601 }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
30
backend/app/controllers/admin/passwords_controller.rb
Normal file
30
backend/app/controllers/admin/passwords_controller.rb
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
module Admin
|
||||||
|
class PasswordsController < Admin::BaseController
|
||||||
|
def edit
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
unless current_admin_account.authenticate(params[:current_password])
|
||||||
|
flash.now[:alert] = "Password attuale non corretta"
|
||||||
|
return render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
if params[:password].blank? || params[:password].length < 8
|
||||||
|
flash.now[:alert] = "La nuova password deve avere almeno 8 caratteri"
|
||||||
|
return render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
if params[:password] != params[:password_confirmation]
|
||||||
|
flash.now[:alert] = "Le password non coincidono"
|
||||||
|
return render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
if current_admin_account.update(password: params[:password])
|
||||||
|
redirect_to admin_root_path, notice: "Password aggiornata"
|
||||||
|
else
|
||||||
|
flash.now[:alert] = current_admin_account.errors.full_messages.to_sentence
|
||||||
|
render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -8,5 +8,19 @@ module Admin
|
|||||||
@session = StreamSession.find(params[:id])
|
@session = StreamSession.find(params[:id])
|
||||||
@events = @session.stream_events.recent.limit(50)
|
@events = @session.stream_events.recent.limit(50)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def stop
|
||||||
|
@session = StreamSession.find(params[:id])
|
||||||
|
if @session.terminal?
|
||||||
|
redirect_to admin_session_path(@session), alert: "Sessione già terminata (#{@session.status})."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
Sessions::Stop.new(@session).call
|
||||||
|
redirect_to admin_session_path(@session), notice: "Sessione terminata."
|
||||||
|
rescue StandardError => e
|
||||||
|
Rails.logger.error("[admin] stop session #{@session.id}: #{e.class} #{e.message}")
|
||||||
|
redirect_to admin_session_path(@session), alert: "Errore durante la chiusura: #{e.message}"
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
module Admin
|
module Admin
|
||||||
class TeamsController < Admin::BaseController
|
class TeamsController < Admin::BaseController
|
||||||
def index
|
def index
|
||||||
@teams = Team.all.order(:name)
|
redirect_to admin_clubs_path, status: :moved_permanently
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
|
|||||||
13
backend/app/controllers/admin/youtube_controller.rb
Normal file
13
backend/app/controllers/admin/youtube_controller.rb
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
module Admin
|
||||||
|
class YoutubeController < Admin::BaseController
|
||||||
|
def platform
|
||||||
|
if ENV["YOUTUBE_CLIENT_ID"].blank?
|
||||||
|
redirect_to admin_root_path, alert: "Configura YOUTUBE_CLIENT_ID e YOUTUBE_CLIENT_SECRET in .env"
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
state = Youtube::OauthState.for_platform(admin_id: current_admin_account.id)
|
||||||
|
redirect_to Youtube::OauthUrl.build(state: state), allow_other_host: true
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -2,9 +2,17 @@ module Api
|
|||||||
module V1
|
module V1
|
||||||
class BaseController < ApplicationController
|
class BaseController < ApplicationController
|
||||||
rescue_from Teams::EntitlementError, with: :render_entitlement_error
|
rescue_from Teams::EntitlementError, with: :render_entitlement_error
|
||||||
|
rescue_from Youtube::BroadcastService::Error, with: :render_youtube_error
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
def render_youtube_error(error)
|
||||||
|
render json: {
|
||||||
|
error: "YouTube: #{error.message}",
|
||||||
|
error_code: "youtube_api_error"
|
||||||
|
}, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
def render_entitlement_error(error)
|
def render_entitlement_error(error)
|
||||||
render json: {
|
render json: {
|
||||||
error: error.message,
|
error: error.message,
|
||||||
|
|||||||
52
backend/app/controllers/api/v1/invitations_controller.rb
Normal file
52
backend/app/controllers/api/v1/invitations_controller.rb
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
module Api
|
||||||
|
module V1
|
||||||
|
class InvitationsController < BaseController
|
||||||
|
skip_before_action :authenticate_request!, only: :show
|
||||||
|
|
||||||
|
def show
|
||||||
|
invitation = find_pending_invitation
|
||||||
|
unless invitation
|
||||||
|
return render json: { valid: false, error: "Invito non valido o scaduto" }, status: :not_found
|
||||||
|
end
|
||||||
|
|
||||||
|
render json: {
|
||||||
|
valid: true,
|
||||||
|
email: invitation.email,
|
||||||
|
team_id: invitation.team_id,
|
||||||
|
team_name: invitation.team.name,
|
||||||
|
club_name: invitation.team.club.name,
|
||||||
|
staff_kind: invitation.staff_kind,
|
||||||
|
expires_at: invitation.expires_at
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def accept
|
||||||
|
invitation = find_pending_invitation
|
||||||
|
return render json: { error: "Invito non valido o scaduto" }, status: :not_found unless invitation
|
||||||
|
|
||||||
|
if current_user.email.downcase != invitation.email.downcase
|
||||||
|
return render json: {
|
||||||
|
error: "Questo invito è per #{invitation.email}. Accedi con quell'indirizzo email.",
|
||||||
|
invited_email: invitation.email
|
||||||
|
}, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
invitation.accept!(current_user)
|
||||||
|
render json: {
|
||||||
|
team_id: invitation.team_id,
|
||||||
|
team_name: invitation.team.name,
|
||||||
|
message: "Sei entrato in #{invitation.team.name} come responsabile trasmissione."
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def find_pending_invitation
|
||||||
|
token = params[:token].to_s
|
||||||
|
return nil if token.blank?
|
||||||
|
|
||||||
|
TeamInvitation.pending.find_by(token_digest: Digest::SHA256.hexdigest(token))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -7,7 +7,7 @@ module Api
|
|||||||
def index
|
def index
|
||||||
matches = @team.matches
|
matches = @team.matches
|
||||||
.includes(:team, :stream_sessions)
|
.includes(:team, :stream_sessions)
|
||||||
.order(scheduled_at: :desc)
|
.order(Arel.sql("scheduled_at ASC NULLS LAST"), created_at: :desc)
|
||||||
render json: matches.map { |m| match_json(m) }
|
render json: matches.map { |m| match_json(m) }
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -40,11 +40,13 @@ module Api
|
|||||||
private
|
private
|
||||||
|
|
||||||
def set_team
|
def set_team
|
||||||
@team = current_user.teams.find(params[:team_id])
|
@team = current_user.streamable_teams.find { |t| t.id == params[:team_id] }
|
||||||
|
raise ActiveRecord::RecordNotFound unless @team
|
||||||
end
|
end
|
||||||
|
|
||||||
def set_match
|
def set_match
|
||||||
@match = Match.joins(:team).merge(current_user.teams).find(params[:id])
|
team_ids = current_user.streamable_teams.map(&:id)
|
||||||
|
@match = Match.where(team_id: team_ids).find(params[:id])
|
||||||
end
|
end
|
||||||
|
|
||||||
def match_params
|
def match_params
|
||||||
|
|||||||
105
backend/app/controllers/api/v1/recordings_controller.rb
Normal file
105
backend/app/controllers/api/v1/recordings_controller.rb
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
module Api
|
||||||
|
module V1
|
||||||
|
class RecordingsController < BaseController
|
||||||
|
before_action :set_recording
|
||||||
|
|
||||||
|
def update
|
||||||
|
authorize_manage!
|
||||||
|
@recording.update!(recording_update_attrs)
|
||||||
|
render json: recording_json(@recording)
|
||||||
|
end
|
||||||
|
|
||||||
|
def destroy
|
||||||
|
authorize_manage!
|
||||||
|
Recordings::Delete.new(@recording).call
|
||||||
|
head :no_content
|
||||||
|
end
|
||||||
|
|
||||||
|
def download
|
||||||
|
url = Recordings::DownloadUrl.new(@recording, viewer: current_user).call
|
||||||
|
render json: { download_url: url, expires_in_seconds: MatchLiveTv.replay_download_url_ttl_seconds }
|
||||||
|
rescue Recordings::DownloadUrl::NotAllowed
|
||||||
|
render json: { error: "Download non disponibile per il tuo piano", error_code: "download_not_allowed" },
|
||||||
|
status: :forbidden
|
||||||
|
rescue ArgumentError => e
|
||||||
|
render json: { error: e.message }, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def publish_youtube
|
||||||
|
authorize_manage!
|
||||||
|
ent = @recording.team.entitlements
|
||||||
|
unless ent.premium_full? && ent.youtube_enabled?
|
||||||
|
return render json: { error: "Republicazione YouTube con Premium Full" }, status: :forbidden
|
||||||
|
end
|
||||||
|
|
||||||
|
Recordings::PublishToYoutubeJob.perform_async(@recording.id)
|
||||||
|
render json: { queued: true, message: "Pubblicazione su YouTube in corso" }
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_recording
|
||||||
|
team_ids = current_user.manageable_teams.map(&:id)
|
||||||
|
@recording = Recording.not_deleted
|
||||||
|
.includes(stream_session: :match)
|
||||||
|
.where(team_id: team_ids)
|
||||||
|
.find(params[:id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def authorize_manage!
|
||||||
|
team = @recording.team
|
||||||
|
return if team.club.owned_by?(current_user)
|
||||||
|
return if current_user.manageable_teams.exists?(id: team.id)
|
||||||
|
|
||||||
|
render json: { error: "Non autorizzato" }, status: :forbidden
|
||||||
|
end
|
||||||
|
|
||||||
|
def recording_update_attrs
|
||||||
|
p = params.require(:recording).permit(:privacy_status, :title)
|
||||||
|
p = p.to_h
|
||||||
|
p[:privacy_status] = "unlisted" if p[:privacy_status] == "private"
|
||||||
|
if params.dig(:recording, :metadata).present?
|
||||||
|
p[:metadata] = @recording.metadata.merge(
|
||||||
|
params[:recording][:metadata].to_unsafe_h.stringify_keys
|
||||||
|
)
|
||||||
|
end
|
||||||
|
p
|
||||||
|
end
|
||||||
|
|
||||||
|
def recording_json(recording)
|
||||||
|
session = recording.stream_session
|
||||||
|
match = session.match
|
||||||
|
ent = recording.team.entitlements
|
||||||
|
{
|
||||||
|
id: recording.id,
|
||||||
|
session_id: session.id,
|
||||||
|
match_id: match.id,
|
||||||
|
title: recording.title_or_default,
|
||||||
|
opponent_name: match.opponent_name,
|
||||||
|
team_name: match.team.name,
|
||||||
|
team_id: recording.team_id,
|
||||||
|
status: recording.status,
|
||||||
|
status_label: recording.status_label,
|
||||||
|
privacy_status: recording.privacy_status,
|
||||||
|
ended_at: session.ended_at,
|
||||||
|
recorded_at: recording.recorded_at_or_fallback,
|
||||||
|
duration_secs: recording.duration_secs,
|
||||||
|
duration_label: recording.duration_label,
|
||||||
|
byte_size: recording.byte_size,
|
||||||
|
byte_size_label: recording.byte_size_label,
|
||||||
|
view_count: recording.view_count,
|
||||||
|
views_label: recording.views_label,
|
||||||
|
replay_url: recording.replay_url,
|
||||||
|
playback_url: recording.playback_stream_url,
|
||||||
|
thumbnail_url: recording.thumbnail_url,
|
||||||
|
download_enabled: ent.phone_download_enabled?,
|
||||||
|
youtube_video_id: recording.youtube_video_id,
|
||||||
|
youtube_watch_url: recording.youtube_watch_url,
|
||||||
|
youtube_publish_enabled: ent.premium_full? && ent.youtube_enabled?,
|
||||||
|
expires_at: recording.expires_at,
|
||||||
|
metadata: recording.metadata
|
||||||
|
}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -4,7 +4,8 @@ module Api
|
|||||||
before_action :set_session, except: :create
|
before_action :set_session, except: :create
|
||||||
|
|
||||||
def create
|
def create
|
||||||
match = Match.joins(:team).merge(current_user.teams).find(params[:match_id])
|
team_ids = current_user.streamable_teams.map(&:id)
|
||||||
|
match = Match.where(team_id: team_ids).find(params[:match_id])
|
||||||
session = Sessions::Create.new(user: current_user, match: match, params: session_params).call
|
session = Sessions::Create.new(user: current_user, match: match, params: session_params).call
|
||||||
render json: session_json(session), status: :created
|
render json: session_json(session), status: :created
|
||||||
end
|
end
|
||||||
@@ -28,6 +29,16 @@ module Api
|
|||||||
render json: session_json(@session)
|
render json: session_json(@session)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def resume
|
||||||
|
Sessions::Resume.new(@session).call
|
||||||
|
render json: session_json(@session)
|
||||||
|
end
|
||||||
|
|
||||||
|
def score
|
||||||
|
Scoring::SyncState.new(session: @session, payload: score_sync_params).call
|
||||||
|
render json: session_json(@session, detail: true)
|
||||||
|
end
|
||||||
|
|
||||||
def events
|
def events
|
||||||
events = @session.stream_events.recent.limit(100)
|
events = @session.stream_events.recent.limit(100)
|
||||||
render json: events.map { |e| event_json(e) }
|
render json: events.map { |e| event_json(e) }
|
||||||
@@ -45,6 +56,7 @@ module Api
|
|||||||
fps: params[:fps],
|
fps: params[:fps],
|
||||||
last_seen_at: Time.current
|
last_seen_at: Time.current
|
||||||
)
|
)
|
||||||
|
sync_publisher_when_streaming!(params[:fps].to_f)
|
||||||
SessionChannel.broadcast_message(@session, state.as_cable_payload)
|
SessionChannel.broadcast_message(@session, state.as_cable_payload)
|
||||||
head :no_content
|
head :no_content
|
||||||
end
|
end
|
||||||
@@ -66,6 +78,15 @@ module Api
|
|||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def regia_link
|
||||||
|
access = Sessions::RegiaAccess.new(@session)
|
||||||
|
token = access.issue_token!
|
||||||
|
render json: {
|
||||||
|
regia_url: access.url(token),
|
||||||
|
expires_at: @session.regia_token_expires_at
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
def claim_pairing
|
def claim_pairing
|
||||||
token = params.require(:pairing_token)
|
token = params.require(:pairing_token)
|
||||||
digest = Digest::SHA256.hexdigest(token)
|
digest = Digest::SHA256.hexdigest(token)
|
||||||
@@ -101,13 +122,21 @@ module Api
|
|||||||
private
|
private
|
||||||
|
|
||||||
def set_session
|
def set_session
|
||||||
@session = StreamSession.joins(match: :team)
|
team_ids = current_user.streamable_teams.map(&:id)
|
||||||
.merge(current_user.teams)
|
@session = StreamSession.joins(:match)
|
||||||
|
.where(matches: { team_id: team_ids })
|
||||||
.find(params[:id])
|
.find(params[:id])
|
||||||
end
|
end
|
||||||
|
|
||||||
def session_params
|
def session_params
|
||||||
params.permit(:platform, :privacy_status, :quality_preset, :target_bitrate, :target_fps)
|
params.permit(:platform, :privacy_status, :quality_preset, :target_bitrate, :target_fps, :youtube_channel)
|
||||||
|
end
|
||||||
|
|
||||||
|
def score_sync_params
|
||||||
|
params.permit(
|
||||||
|
:home_sets, :away_sets, :home_points, :away_points, :current_set,
|
||||||
|
set_partials: %i[set home away]
|
||||||
|
)
|
||||||
end
|
end
|
||||||
|
|
||||||
def session_json(session, detail: false)
|
def session_json(session, detail: false)
|
||||||
@@ -118,8 +147,11 @@ module Api
|
|||||||
platform: session.platform,
|
platform: session.platform,
|
||||||
rtmp_ingest_url: session.rtmp_ingest_url,
|
rtmp_ingest_url: session.rtmp_ingest_url,
|
||||||
hls_playback_url: session.hls_playback_url,
|
hls_playback_url: session.hls_playback_url,
|
||||||
watch_page_url: session.watch_page_url,
|
watch_page_url: session.matchlivetv_platform? ? session.watch_page_url : nil,
|
||||||
|
share_url: session.share_url,
|
||||||
|
youtube_watch_url: session.youtube_watch_url,
|
||||||
youtube_broadcast_id: session.youtube_broadcast_id,
|
youtube_broadcast_id: session.youtube_broadcast_id,
|
||||||
|
youtube_ready: session.youtube_ready?,
|
||||||
privacy_status: session.privacy_status,
|
privacy_status: session.privacy_status,
|
||||||
quality_preset: session.quality_preset,
|
quality_preset: session.quality_preset,
|
||||||
target_bitrate: session.target_bitrate,
|
target_bitrate: session.target_bitrate,
|
||||||
@@ -141,6 +173,19 @@ module Api
|
|||||||
occurred_at: event.occurred_at
|
occurred_at: event.occurred_at
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# L'app invia fps ogni ~10s; poll status.json per allineare stato sessione e relay YouTube.
|
||||||
|
def sync_publisher_when_streaming!(fps)
|
||||||
|
return if fps < 1
|
||||||
|
return if @session.terminal? || @session.paused?
|
||||||
|
return unless @session.platform == "youtube"
|
||||||
|
return unless @session.status.in?(%w[connecting live reconnecting])
|
||||||
|
|
||||||
|
Mediamtx::PublisherSync.new(@session).call
|
||||||
|
if @session.platform == "youtube" && @session.status.in?(%w[live connecting reconnecting])
|
||||||
|
Mediamtx::PublisherSync.schedule_youtube_pipeline!(@session, force: false)
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -2,30 +2,33 @@ module Api
|
|||||||
module V1
|
module V1
|
||||||
class TeamsController < BaseController
|
class TeamsController < BaseController
|
||||||
def index
|
def index
|
||||||
teams = current_user.teams.includes(:matches)
|
teams = current_user.streamable_teams
|
||||||
render json: teams.map { |t| team_json(t) }
|
render json: teams.map { |t| team_json(t) }
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
team = current_user.teams.find(params[:id])
|
team = current_user.manageable_teams.find(params[:id])
|
||||||
render json: team_json(team, detail: true)
|
render json: team_json(team, detail: true)
|
||||||
end
|
end
|
||||||
|
|
||||||
def create
|
def create
|
||||||
if current_user.user_teams.where(role: "owner").count >= 1
|
if current_user.owned_clubs.exists?
|
||||||
return render json: {
|
return render json: {
|
||||||
error: "Puoi gestire una sola squadra. Usa il sito per inviti o contattaci."
|
error: "Registra o gestisci la società dal sito web per aggiungere squadre."
|
||||||
}, status: :unprocessable_entity
|
}, status: :unprocessable_entity
|
||||||
end
|
end
|
||||||
|
|
||||||
team = Team.create!(team_params)
|
club = Club.create!(name: team_params[:name], sport: team_params[:sport] || "volleyball",
|
||||||
UserTeam.create!(user: current_user, team: team, role: "owner")
|
primary_color: "#e53935", secondary_color: "#ffffff")
|
||||||
Billing::AssignPlan.call(team: team, plan_slug: "free")
|
ClubMembership.create!(user: current_user, club: club, role: "owner")
|
||||||
|
team = club.teams.create!(name: team_params[:name], sport: club.sport)
|
||||||
|
Billing::AssignPlan.call(club: club, plan_slug: "free")
|
||||||
render json: team_json(team), status: :created
|
render json: team_json(team), status: :created
|
||||||
end
|
end
|
||||||
|
|
||||||
def recordings
|
def recordings
|
||||||
team = current_user.teams.find(params[:id])
|
team = current_user.streamable_teams.find { |t| t.id.to_s == params[:id].to_s }
|
||||||
|
raise ActiveRecord::RecordNotFound unless team
|
||||||
unless team.entitlements.can_access_recordings?
|
unless team.entitlements.can_access_recordings?
|
||||||
return render json: {
|
return render json: {
|
||||||
error: "Archivio gare disponibile con Premium Light o Full",
|
error: "Archivio gare disponibile con Premium Light o Full",
|
||||||
@@ -34,18 +37,22 @@ module Api
|
|||||||
}, status: :forbidden
|
}, status: :forbidden
|
||||||
end
|
end
|
||||||
|
|
||||||
recs = team.recordings.ready.includes(stream_session: :match).order(created_at: :desc).limit(50)
|
recs = team.recordings.not_deleted
|
||||||
|
.where(status: %w[ready processing])
|
||||||
|
.includes(stream_session: :match)
|
||||||
|
.order(recorded_at: :desc, created_at: :desc)
|
||||||
|
.limit(50)
|
||||||
render json: recs.map { |r| recording_json(r) }
|
render json: recs.map { |r| recording_json(r) }
|
||||||
end
|
end
|
||||||
|
|
||||||
def update
|
def update
|
||||||
team = current_user.teams.find(params[:id])
|
team = current_user.manageable_teams.find(params[:id])
|
||||||
team.update!(team_params)
|
team.update!(team_params)
|
||||||
render json: team_json(team)
|
render json: team_json(team)
|
||||||
end
|
end
|
||||||
|
|
||||||
def add_member
|
def add_member
|
||||||
team = current_user.teams.find(params[:id])
|
team = current_user.manageable_teams.find(params[:id])
|
||||||
team.entitlements.assert_can_invite!
|
team.entitlements.assert_can_invite!
|
||||||
member = User.find(params[:user_id])
|
member = User.find(params[:user_id])
|
||||||
UserTeam.find_or_create_by!(user: member, team: team) { |ut| ut.role = "member" }
|
UserTeam.find_or_create_by!(user: member, team: team) { |ut| ut.role = "member" }
|
||||||
@@ -53,7 +60,7 @@ module Api
|
|||||||
end
|
end
|
||||||
|
|
||||||
def remove_member
|
def remove_member
|
||||||
team = current_user.teams.find(params[:id])
|
team = current_user.manageable_teams.find(params[:id])
|
||||||
ut = team.user_teams.find_by!(user_id: params[:user_id], role: "member")
|
ut = team.user_teams.find_by!(user_id: params[:user_id], role: "member")
|
||||||
ut.destroy!
|
ut.destroy!
|
||||||
head :no_content
|
head :no_content
|
||||||
@@ -67,12 +74,24 @@ module Api
|
|||||||
|
|
||||||
def team_json(team, detail: false)
|
def team_json(team, detail: false)
|
||||||
ent = team.entitlements
|
ent = team.entitlements
|
||||||
|
yt = Youtube::TeamStatus.new(team)
|
||||||
|
resolver = Youtube::CredentialResolver.new(team)
|
||||||
data = {
|
data = {
|
||||||
id: team.id,
|
id: team.id,
|
||||||
name: team.name,
|
name: team.name,
|
||||||
sport: team.sport,
|
sport: team.sport,
|
||||||
logo_url: team.logo_url,
|
logo_url: team.effective_logo_url,
|
||||||
youtube_connected: team.youtube_credential.present?,
|
primary_color: team.effective_primary_color,
|
||||||
|
secondary_color: team.effective_secondary_color,
|
||||||
|
club_id: team.club_id,
|
||||||
|
club_name: team.club.name,
|
||||||
|
youtube_connected: yt.connected?,
|
||||||
|
youtube_selectable: yt.selectable?,
|
||||||
|
youtube_channel_title: yt.channel_title,
|
||||||
|
youtube_uses_platform_channel: yt.uses_platform_channel?,
|
||||||
|
youtube_platform_available: resolver.platform_available?,
|
||||||
|
youtube_team_channel_available: resolver.team_channel_available?,
|
||||||
|
youtube_team_channel_title: team.club.youtube_credential&.channel_title,
|
||||||
plan_slug: ent.plan.slug,
|
plan_slug: ent.plan.slug,
|
||||||
plan_name: ent.plan.name,
|
plan_name: ent.plan.name,
|
||||||
premium_active: ent.premium_active?,
|
premium_active: ent.premium_active?,
|
||||||
@@ -83,16 +102,17 @@ module Api
|
|||||||
staff_manage_url: ent.staff_manage_url,
|
staff_manage_url: ent.staff_manage_url,
|
||||||
max_staff: ent.max_staff,
|
max_staff: ent.max_staff,
|
||||||
max_staff_transmission: ent.max_staff_transmission,
|
max_staff_transmission: ent.max_staff_transmission,
|
||||||
max_staff_regia: ent.max_staff_regia,
|
|
||||||
staff_used: ent.staff_count,
|
staff_used: ent.staff_count,
|
||||||
staff_transmission_used: ent.staff_count_for("transmission"),
|
staff_transmission_used: ent.staff_count_for("transmission"),
|
||||||
staff_regia_used: ent.staff_count_for("regia"),
|
|
||||||
concurrent_streams_used: ent.concurrent_streams_used,
|
concurrent_streams_used: ent.concurrent_streams_used,
|
||||||
concurrent_streams_limit: ent.concurrent_streams_limit,
|
concurrent_streams_limit: ent.concurrent_streams_limit,
|
||||||
recordings_enabled: ent.can_access_recordings?,
|
recordings_enabled: ent.can_access_recordings?,
|
||||||
phone_download_enabled: ent.phone_download_enabled?,
|
phone_download_enabled: ent.phone_download_enabled?,
|
||||||
youtube_enabled: ent.youtube_enabled?,
|
youtube_enabled: ent.youtube_enabled?,
|
||||||
youtube_mode: ent.plan.youtube_mode
|
youtube_mode: ent.plan.youtube_mode,
|
||||||
|
staff_role: current_user.staff_role_for(team),
|
||||||
|
can_stream: current_user.can_stream_for?(team),
|
||||||
|
can_connect_youtube: team.club.owned_by?(current_user) && ent.premium_full? && ent.youtube_enabled?
|
||||||
}
|
}
|
||||||
if detail
|
if detail
|
||||||
data[:members] = team.user_teams.includes(:user).where.not(role: "owner").map do |ut|
|
data[:members] = team.user_teams.includes(:user).where.not(role: "owner").map do |ut|
|
||||||
@@ -105,16 +125,34 @@ module Api
|
|||||||
def recording_json(recording)
|
def recording_json(recording)
|
||||||
session = recording.stream_session
|
session = recording.stream_session
|
||||||
match = session.match
|
match = session.match
|
||||||
|
ent = recording.team.entitlements
|
||||||
{
|
{
|
||||||
id: recording.id,
|
id: recording.id,
|
||||||
session_id: session.id,
|
session_id: session.id,
|
||||||
match_id: match.id,
|
match_id: match.id,
|
||||||
|
title: recording.title_or_default,
|
||||||
opponent_name: match.opponent_name,
|
opponent_name: match.opponent_name,
|
||||||
team_name: match.team.name,
|
team_name: match.team.name,
|
||||||
|
status: recording.status,
|
||||||
|
status_label: recording.status_label,
|
||||||
|
privacy_status: recording.privacy_status,
|
||||||
ended_at: session.ended_at,
|
ended_at: session.ended_at,
|
||||||
|
recorded_at: recording.recorded_at_or_fallback,
|
||||||
|
duration_secs: recording.duration_secs,
|
||||||
|
duration_label: recording.duration_label,
|
||||||
|
byte_size: recording.byte_size,
|
||||||
|
byte_size_label: recording.byte_size_label,
|
||||||
replay_url: recording.replay_url,
|
replay_url: recording.replay_url,
|
||||||
download_url: recording.replay_url,
|
playback_url: recording.playback_stream_url,
|
||||||
expires_at: recording.expires_at
|
thumbnail_url: recording.thumbnail_url,
|
||||||
|
download_enabled: ent.phone_download_enabled?,
|
||||||
|
view_count: recording.view_count,
|
||||||
|
views_label: recording.views_label,
|
||||||
|
youtube_video_id: recording.youtube_video_id,
|
||||||
|
youtube_watch_url: recording.youtube_watch_url,
|
||||||
|
youtube_publish_enabled: ent.premium_full? && ent.youtube_enabled?,
|
||||||
|
expires_at: recording.expires_at,
|
||||||
|
metadata: recording.metadata
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -2,24 +2,21 @@ module Api
|
|||||||
module V1
|
module V1
|
||||||
class YoutubeController < BaseController
|
class YoutubeController < BaseController
|
||||||
def authorize
|
def authorize
|
||||||
team = current_user.teams.find(params[:team_id])
|
team = current_user.streamable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
|
||||||
team.entitlements.assert_can_connect_youtube!
|
raise ActiveRecord::RecordNotFound unless team
|
||||||
url = Youtube::OauthUrl.build(team_id: team.id, redirect_uri: ENV.fetch("YOUTUBE_REDIRECT_URI"))
|
unless team.club.owned_by?(current_user)
|
||||||
render json: { authorization_url: url }
|
return render json: { error: "Solo il titolare della società può collegare YouTube" }, status: :forbidden
|
||||||
end
|
end
|
||||||
|
|
||||||
def callback
|
team.entitlements.assert_can_connect_youtube!
|
||||||
team = current_user.teams.find(params[:state])
|
return_app = ActiveModel::Type::Boolean.new.cast(params[:return_app])
|
||||||
tokens = Youtube::OauthExchange.call(params[:code])
|
state = Youtube::OauthState.for_team(
|
||||||
cred = team.youtube_credential || team.build_youtube_credential
|
team_id: team.id,
|
||||||
cred.update!(
|
user_id: current_user.id,
|
||||||
access_token: tokens[:access_token],
|
return_app: return_app
|
||||||
refresh_token: tokens[:refresh_token],
|
|
||||||
expires_at: Time.current + tokens[:expires_in].seconds,
|
|
||||||
channel_id: tokens[:channel_id],
|
|
||||||
channel_title: tokens[:channel_title]
|
|
||||||
)
|
)
|
||||||
redirect_to "/admin/teams/#{team.id}?youtube=connected"
|
url = Youtube::OauthUrl.build(state: state, redirect_uri: ENV.fetch("YOUTUBE_REDIRECT_URI"))
|
||||||
|
render json: { authorization_url: url, return_app: return_app }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
16
backend/app/controllers/concerns/branding_attachments.rb
Normal file
16
backend/app/controllers/concerns/branding_attachments.rb
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
module BrandingAttachments
|
||||||
|
extend ActiveSupport::Concern
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def attach_branding_logo(record)
|
||||||
|
file = params.dig(:branding, :logo_file)
|
||||||
|
record.logo_file.attach(file) if file.present?
|
||||||
|
end
|
||||||
|
|
||||||
|
def normalize_hex_color(value, fallback)
|
||||||
|
v = value.to_s.strip
|
||||||
|
v = "##{v}" if v.match?(/\A[0-9A-Fa-f]{6}\z/)
|
||||||
|
v.match?(Brandable::HEX_COLOR) ? v : fallback
|
||||||
|
end
|
||||||
|
end
|
||||||
34
backend/app/controllers/concerns/mediamtx_playback.rb
Normal file
34
backend/app/controllers/concerns/mediamtx_playback.rb
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
module MediamtxPlayback
|
||||||
|
extend ActiveSupport::Concern
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def mediamtx_paths_index
|
||||||
|
@mediamtx_paths_index ||= Mediamtx::Client.new.list_paths.index_by { |i| i["name"] }
|
||||||
|
end
|
||||||
|
|
||||||
|
def mediamtx_path_info(session, path_name: mediamtx_playback_path_name(session))
|
||||||
|
mediamtx_paths_index[path_name]
|
||||||
|
end
|
||||||
|
|
||||||
|
def mediamtx_playback_path_name(session)
|
||||||
|
session.effective_hls_path_name
|
||||||
|
end
|
||||||
|
|
||||||
|
# Player HLS: path grezzo MediaMTX (live/match_{uuid}).
|
||||||
|
def mediamtx_stream_playable?(session)
|
||||||
|
return false if session.terminal?
|
||||||
|
|
||||||
|
mediamtx_path_has_output?(session)
|
||||||
|
end
|
||||||
|
|
||||||
|
def mediamtx_path_has_output?(session)
|
||||||
|
info = mediamtx_path_info(session)
|
||||||
|
info && (info["ready"] || info["available"] || info["online"])
|
||||||
|
end
|
||||||
|
|
||||||
|
def mediamtx_publisher_online?(session)
|
||||||
|
info = mediamtx_paths_index[session.mediamtx_path_name]
|
||||||
|
info && info["online"]
|
||||||
|
end
|
||||||
|
end
|
||||||
93
backend/app/controllers/public/club_billing_controller.rb
Normal file
93
backend/app/controllers/public/club_billing_controller.rb
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
module Public
|
||||||
|
class ClubBillingController < WebBaseController
|
||||||
|
before_action :require_login!
|
||||||
|
before_action :set_club
|
||||||
|
before_action :require_club_owner_for_club!
|
||||||
|
|
||||||
|
def profile
|
||||||
|
end
|
||||||
|
|
||||||
|
def update_profile
|
||||||
|
@club.assign_attributes(billing_profile_params)
|
||||||
|
if @club.save(context: :billing_profile)
|
||||||
|
if premium_checkout_return_params.present? && @club.billing_profile_complete?
|
||||||
|
redirect_to public_club_checkout_path(
|
||||||
|
@club,
|
||||||
|
plan: premium_checkout_return_params[:plan],
|
||||||
|
interval: premium_checkout_return_params[:interval]
|
||||||
|
), notice: "Dati salvati. Procedi con il pagamento."
|
||||||
|
else
|
||||||
|
redirect_to public_club_billing_path(@club), notice: "Dati di fatturazione aggiornati."
|
||||||
|
end
|
||||||
|
else
|
||||||
|
flash.now[:alert] = @club.errors.full_messages.join(", ")
|
||||||
|
render :profile, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def cancel_subscription
|
||||||
|
unless MatchLiveTv.stripe_enabled?
|
||||||
|
redirect_to public_club_billing_path(@club), alert: "Stripe non configurato."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
Billing::Stripe::CancelSubscription.call(club: @club)
|
||||||
|
sub = @club.subscription.reload
|
||||||
|
date = sub.current_period_end ? helpers.l_local(sub.current_period_end.to_date) : "fine periodo"
|
||||||
|
redirect_to public_club_billing_path(@club),
|
||||||
|
notice: "Abbonamento disdetto. Resta attivo fino al #{date}; da quel giorno passerai al piano Free."
|
||||||
|
rescue ArgumentError, RuntimeError => e
|
||||||
|
redirect_to public_club_billing_path(@club), alert: e.message
|
||||||
|
rescue ::Stripe::StripeError => e
|
||||||
|
redirect_to public_club_billing_path(@club), alert: "Errore Stripe: #{e.message}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def download_invoice
|
||||||
|
invoice = @club.billing_invoices.find(params[:invoice_id])
|
||||||
|
unless invoice.pdf.attached?
|
||||||
|
redirect_to public_club_billing_path(@club), alert: "PDF fattura non disponibile."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
redirect_to rails_blob_path(invoice.pdf, disposition: "attachment"), allow_other_host: true
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_club
|
||||||
|
@club = current_user.owned_clubs.find(params[:id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def require_club_owner_for_club!
|
||||||
|
require_club_owner!(@club)
|
||||||
|
end
|
||||||
|
|
||||||
|
def premium_checkout_return_params
|
||||||
|
plan = params[:plan].presence_in(%w[premium_light premium_full])
|
||||||
|
return nil if plan.blank?
|
||||||
|
|
||||||
|
{
|
||||||
|
plan: plan,
|
||||||
|
interval: params[:interval].presence || Billing::Stripe::PriceCatalog::DEFAULT_INTERVAL
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing_profile_params
|
||||||
|
params.require(:club).permit(
|
||||||
|
:billing_entity_type,
|
||||||
|
:billing_legal_name,
|
||||||
|
:billing_vat_number,
|
||||||
|
:billing_fiscal_code,
|
||||||
|
:billing_email,
|
||||||
|
:billing_phone,
|
||||||
|
:billing_address_line,
|
||||||
|
:billing_city,
|
||||||
|
:billing_province,
|
||||||
|
:billing_postal_code,
|
||||||
|
:billing_country,
|
||||||
|
:billing_recipient_code,
|
||||||
|
:billing_pec
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
85
backend/app/controllers/public/club_matches_controller.rb
Normal file
85
backend/app/controllers/public/club_matches_controller.rb
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
module Public
|
||||||
|
class ClubMatchesController < WebBaseController
|
||||||
|
before_action :require_login!
|
||||||
|
before_action :set_club
|
||||||
|
before_action :load_schedulable_teams
|
||||||
|
before_action :require_any_schedulable_team!
|
||||||
|
|
||||||
|
def new
|
||||||
|
@match = default_match_for_form
|
||||||
|
@selected_team = resolve_selected_team
|
||||||
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
@selected_team = @schedulable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
|
||||||
|
unless @selected_team
|
||||||
|
@match = default_match_for_form
|
||||||
|
flash.now[:alert] = "Seleziona una squadra valida."
|
||||||
|
return render :new, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
@match = @selected_team.matches.create!(
|
||||||
|
match_params.merge(sport: @selected_team.sport, sets_to_win: 3)
|
||||||
|
)
|
||||||
|
redirect_to public_live_index_path(club_id: @club.id),
|
||||||
|
notice: "Partita programmata: #{@selected_team.name} vs #{@match.opponent_name}."
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
@match = @selected_team.matches.build(match_params)
|
||||||
|
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||||
|
render :new, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_club
|
||||||
|
@club = Club.find(params[:club_id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def load_schedulable_teams
|
||||||
|
@schedulable_teams = current_user.schedulable_teams_for(@club)
|
||||||
|
@club_admin = @club.owned_by?(current_user)
|
||||||
|
end
|
||||||
|
|
||||||
|
def require_any_schedulable_team!
|
||||||
|
return if @schedulable_teams.any?
|
||||||
|
|
||||||
|
redirect_to public_live_index_path(club_id: @club.id),
|
||||||
|
alert: "Non hai permessi per programmare partite in questa società."
|
||||||
|
end
|
||||||
|
|
||||||
|
def resolve_selected_team
|
||||||
|
if params[:team_id].present?
|
||||||
|
@schedulable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
|
||||||
|
end || @schedulable_teams.first
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_match_for_form
|
||||||
|
team = resolve_selected_team
|
||||||
|
Match.new(
|
||||||
|
sport: team&.sport || @club.sport,
|
||||||
|
sets_to_win: 3,
|
||||||
|
scheduled_at: default_scheduled_at
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def match_params
|
||||||
|
p = params.require(:match).permit(:opponent_name, :location, :scheduled_at)
|
||||||
|
p[:scheduled_at] = parse_scheduled_at(p[:scheduled_at]) if p[:scheduled_at].present?
|
||||||
|
p
|
||||||
|
end
|
||||||
|
|
||||||
|
def parse_scheduled_at(value)
|
||||||
|
raw = value.to_s.strip
|
||||||
|
return nil if raw.blank?
|
||||||
|
|
||||||
|
Time.zone.strptime(raw, "%Y-%m-%dT%H:%M")
|
||||||
|
rescue ArgumentError
|
||||||
|
Time.zone.parse(raw)
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_scheduled_at
|
||||||
|
t = Time.current + 2.hours
|
||||||
|
Time.zone.local(t.year, t.month, t.day, t.hour, 0, 0)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
55
backend/app/controllers/public/club_recordings_controller.rb
Normal file
55
backend/app/controllers/public/club_recordings_controller.rb
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
module Public
|
||||||
|
class ClubRecordingsController < WebBaseController
|
||||||
|
before_action :require_login!
|
||||||
|
before_action :set_club
|
||||||
|
before_action -> { require_club_owner!(@club) }
|
||||||
|
before_action :set_recording, only: %i[update destroy publish_youtube]
|
||||||
|
|
||||||
|
def index
|
||||||
|
@stats = Recordings::ClubStats.new(@club).call
|
||||||
|
@recordings = Recording.for_club(@club)
|
||||||
|
.not_deleted
|
||||||
|
.includes(stream_session: { match: :team })
|
||||||
|
.order(recorded_at: :desc, created_at: :desc)
|
||||||
|
@teams = @club.teams.order(:name)
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
privacy = params.require(:recording).permit(:privacy_status, :title)[:privacy_status]
|
||||||
|
attrs = {}
|
||||||
|
attrs[:privacy_status] = privacy if privacy.in?(Recording::PRIVACY_STATUSES)
|
||||||
|
title = params.dig(:recording, :title)
|
||||||
|
attrs[:title] = title if title.present?
|
||||||
|
@recording.update!(attrs)
|
||||||
|
redirect_to public_club_recordings_path(@club), notice: "Replay aggiornato"
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
redirect_to public_club_recordings_path(@club), alert: e.record.errors.full_messages.join(", ")
|
||||||
|
end
|
||||||
|
|
||||||
|
def destroy
|
||||||
|
Recordings::Delete.new(@recording).call
|
||||||
|
redirect_to public_club_recordings_path(@club), notice: "Replay eliminato"
|
||||||
|
end
|
||||||
|
|
||||||
|
def publish_youtube
|
||||||
|
ent = @recording.team.entitlements
|
||||||
|
unless ent.premium_full? && ent.youtube_enabled?
|
||||||
|
redirect_to public_club_recordings_path(@club), alert: "Republicazione YouTube con Premium Full"
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
Recordings::PublishToYoutubeJob.perform_async(@recording.id)
|
||||||
|
redirect_to public_club_recordings_path(@club), notice: "Pubblicazione su YouTube avviata"
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_club
|
||||||
|
@club = current_user.owned_clubs.find(params[:club_id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_recording
|
||||||
|
@recording = Recording.for_club(@club).not_deleted.find(params[:id])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
245
backend/app/controllers/public/clubs_controller.rb
Normal file
245
backend/app/controllers/public/clubs_controller.rb
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
module Public
|
||||||
|
class ClubsController < WebBaseController
|
||||||
|
include BrandingAttachments
|
||||||
|
|
||||||
|
before_action :require_login!
|
||||||
|
before_action :set_club, only: %i[show edit update billing checkout portal youtube_connect youtube_disconnect]
|
||||||
|
before_action :require_billing_profile_for_premium_checkout!, only: :checkout
|
||||||
|
|
||||||
|
def new
|
||||||
|
redirect_to public_club_path(current_user.primary_club) if current_user.primary_club
|
||||||
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
if current_user.owned_clubs.exists?
|
||||||
|
redirect_to public_club_path(current_user.primary_club), alert: "Hai già registrato una società"
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
club = Club.new(club_params)
|
||||||
|
attach_branding_logo(club)
|
||||||
|
club.save!
|
||||||
|
|
||||||
|
ClubMembership.create!(user: current_user, club: club, role: "owner")
|
||||||
|
|
||||||
|
first_team_name = params.dig(:first_team, :name).presence || "Prima squadra"
|
||||||
|
club.teams.create!(
|
||||||
|
name: first_team_name,
|
||||||
|
sport: club.sport
|
||||||
|
)
|
||||||
|
|
||||||
|
plan = params[:plan].presence_in(%w[free premium_light premium_full]) || "free"
|
||||||
|
Billing::AssignPlan.call(club: club, plan_slug: plan)
|
||||||
|
|
||||||
|
if plan.in?(%w[premium_light premium_full]) && MatchLiveTv.stripe_enabled?
|
||||||
|
unless club.billing_profile_complete?
|
||||||
|
redirect_to public_club_billing_profile_path(club, plan: plan, interval: checkout_interval_param),
|
||||||
|
alert: "Completa i dati di fatturazione prima di attivare un piano premium."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
interval = checkout_interval_param
|
||||||
|
redirect_to public_club_checkout_path(club, plan: plan, interval: interval)
|
||||||
|
else
|
||||||
|
redirect_to public_club_path(club), notice: "Società e prima squadra create."
|
||||||
|
end
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||||
|
render :new, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def show
|
||||||
|
require_club_owner!(@club)
|
||||||
|
apply_checkout_flash!
|
||||||
|
@entitlements_team = @club.teams.first
|
||||||
|
@entitlements = @entitlements_team&.entitlements
|
||||||
|
@teams = @club.teams.order(:name)
|
||||||
|
@replay_stats = Recordings::ClubStats.new(@club).call if @entitlements&.can_access_recordings?
|
||||||
|
end
|
||||||
|
|
||||||
|
def edit
|
||||||
|
require_club_owner!(@club)
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
require_club_owner!(@club)
|
||||||
|
@club.assign_attributes(club_params)
|
||||||
|
attach_branding_logo(@club)
|
||||||
|
@club.save!
|
||||||
|
redirect_to public_club_path(@club), notice: "Società aggiornata."
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||||
|
render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing
|
||||||
|
require_club_owner!(@club)
|
||||||
|
sync_checkout_return!
|
||||||
|
finalize_subscription_if_due!
|
||||||
|
@subscription = @club.subscription&.reload
|
||||||
|
apply_checkout_flash!
|
||||||
|
@team = @club.teams.first!
|
||||||
|
@entitlements = @team.entitlements
|
||||||
|
@plans = Plan.ordered
|
||||||
|
@payments = @club.billing_payments.recent.includes(:invoice).limit(50)
|
||||||
|
end
|
||||||
|
|
||||||
|
def checkout
|
||||||
|
require_club_owner!(@club)
|
||||||
|
if @club.subscription&.admin_comped?
|
||||||
|
redirect_to public_club_billing_path(@club),
|
||||||
|
alert: "Il piano è un abbonamento omaggio gestito da Match Live TV. Per passare a un abbonamento a pagamento contatta il supporto."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
unless MatchLiveTv.stripe_enabled?
|
||||||
|
redirect_to public_club_billing_path(@club), alert: "Pagamenti non ancora configurati sul server"
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
plan_slug = params[:plan].presence_in(%w[premium_light premium_full]) || "premium_light"
|
||||||
|
interval = checkout_interval_param
|
||||||
|
target_plan = Plan[plan_slug]
|
||||||
|
sub = @club.subscription
|
||||||
|
|
||||||
|
if sub&.stripe_subscription_id.present? && sub.active? &&
|
||||||
|
sub.plan.slug == plan_slug && sub.billing_interval == interval && !sub.plan_change_pending?
|
||||||
|
redirect_to public_club_billing_path(@club),
|
||||||
|
notice: "Sei già su #{target_plan.name} (#{Billing::Stripe::PriceCatalog.label(plan_slug: plan_slug, interval: interval)})."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
if sub&.plan_change_pending? && sub.pending_plan&.slug == plan_slug &&
|
||||||
|
sub.pending_billing_interval == interval
|
||||||
|
when_label = sub.current_period_end.present? ? I18n.l(sub.current_period_end, format: :long) : "il prossimo rinnovo"
|
||||||
|
redirect_to public_club_billing_path(@club),
|
||||||
|
notice: "Il passaggio a #{target_plan.name} è già programmato dal #{when_label}."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
if sub&.stripe_subscription_id.present? && sub.active?
|
||||||
|
result = Billing::Stripe::ChangePlan.call(club: @club, plan_slug: plan_slug, interval: interval)
|
||||||
|
redirect_to public_club_billing_path(@club),
|
||||||
|
notice: Billing::Stripe::PlanChangeMessages.flash_notice(
|
||||||
|
result,
|
||||||
|
current_plan: sub.plan
|
||||||
|
)
|
||||||
|
else
|
||||||
|
url = Billing::Stripe::CheckoutSession.new(
|
||||||
|
club: @club, user: current_user, plan_slug: plan_slug, interval: interval
|
||||||
|
).url
|
||||||
|
redirect_to url, allow_other_host: true
|
||||||
|
end
|
||||||
|
rescue ArgumentError => e
|
||||||
|
redirect_to public_club_billing_path(@club), alert: e.message
|
||||||
|
rescue ::Stripe::StripeError => e
|
||||||
|
Rails.logger.warn("[Stripe checkout] #{e.message}")
|
||||||
|
redirect_to public_club_billing_path(@club), alert: "Errore Stripe: #{e.message}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def youtube_connect
|
||||||
|
require_club_owner!(@club)
|
||||||
|
entitlements = @club.teams.first!.entitlements
|
||||||
|
entitlements.assert_can_connect_youtube!
|
||||||
|
|
||||||
|
if ENV["YOUTUBE_CLIENT_ID"].blank?
|
||||||
|
redirect_to public_club_path(@club), alert: "YouTube OAuth non configurato sul server"
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
return_app = params[:return_app] == "1"
|
||||||
|
state = Youtube::OauthState.for_club(
|
||||||
|
club_id: @club.id,
|
||||||
|
user_id: current_user.id,
|
||||||
|
return_app: return_app
|
||||||
|
)
|
||||||
|
redirect_to Youtube::OauthUrl.build(state: state), allow_other_host: true
|
||||||
|
rescue Teams::EntitlementError => e
|
||||||
|
redirect_to public_club_path(@club), alert: e.message
|
||||||
|
end
|
||||||
|
|
||||||
|
def youtube_disconnect
|
||||||
|
require_club_owner!(@club)
|
||||||
|
@club.youtube_credential&.destroy!
|
||||||
|
redirect_to public_club_path(@club), notice: "Canale YouTube della società scollegato"
|
||||||
|
end
|
||||||
|
|
||||||
|
def portal
|
||||||
|
require_club_owner!(@club)
|
||||||
|
unless MatchLiveTv.stripe_enabled?
|
||||||
|
redirect_to public_club_billing_path(@club), alert: "Portale pagamenti non configurato"
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
url = Billing::Stripe::CheckoutSession.new(club: @club, user: current_user).portal_url
|
||||||
|
redirect_to url, allow_other_host: true
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_club
|
||||||
|
@club = current_user.owned_clubs.find(params[:id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def club_params
|
||||||
|
p = params.require(:club).permit(
|
||||||
|
:name, :sport, :logo_url, :primary_color, :secondary_color,
|
||||||
|
:billing_entity_type, :billing_legal_name, :billing_vat_number, :billing_fiscal_code,
|
||||||
|
:billing_email, :billing_phone, :billing_address_line, :billing_city, :billing_province,
|
||||||
|
:billing_postal_code, :billing_country, :billing_recipient_code, :billing_pec
|
||||||
|
)
|
||||||
|
p[:primary_color] = normalize_hex_color(p[:primary_color], "#e53935")
|
||||||
|
p[:secondary_color] = normalize_hex_color(p[:secondary_color], "#ffffff")
|
||||||
|
p
|
||||||
|
end
|
||||||
|
|
||||||
|
def require_billing_profile_for_premium_checkout!
|
||||||
|
require_club_owner!(@club)
|
||||||
|
plan_slug = params[:plan].presence_in(%w[premium_light premium_full])
|
||||||
|
return if plan_slug.blank?
|
||||||
|
return if @club.billing_profile_complete?
|
||||||
|
|
||||||
|
redirect_to public_club_billing_profile_path(
|
||||||
|
@club,
|
||||||
|
plan: plan_slug,
|
||||||
|
interval: params[:interval].presence
|
||||||
|
), alert: "Completa i dati di fatturazione prima di attivare un piano premium."
|
||||||
|
end
|
||||||
|
|
||||||
|
def checkout_interval_param
|
||||||
|
Billing::Stripe::PriceCatalog.normalize_interval(params[:interval])
|
||||||
|
rescue ArgumentError
|
||||||
|
Billing::Stripe::PriceCatalog::DEFAULT_INTERVAL
|
||||||
|
end
|
||||||
|
|
||||||
|
def finalize_subscription_if_due!
|
||||||
|
return unless MatchLiveTv.stripe_enabled?
|
||||||
|
|
||||||
|
Billing::Stripe::FinalizeSubscription.call(club: @club)
|
||||||
|
rescue ::Stripe::StripeError => e
|
||||||
|
Rails.logger.warn("[Stripe finalize subscription] #{e.message}")
|
||||||
|
end
|
||||||
|
|
||||||
|
def sync_checkout_return!
|
||||||
|
return unless params[:checkout] == "success"
|
||||||
|
return unless MatchLiveTv.stripe_enabled?
|
||||||
|
|
||||||
|
Billing::Stripe::CheckoutSync.call(
|
||||||
|
club: @club,
|
||||||
|
session_id: params[:session_id].presence
|
||||||
|
)
|
||||||
|
rescue ::Stripe::StripeError => e
|
||||||
|
Rails.logger.warn("[Stripe checkout sync] #{e.message}")
|
||||||
|
end
|
||||||
|
|
||||||
|
def apply_checkout_flash!
|
||||||
|
case params[:checkout]
|
||||||
|
when "success"
|
||||||
|
plan_name = @subscription&.plan&.name || "premium"
|
||||||
|
flash.now[:notice] = "Pagamento completato! Piano attivo: #{plan_name}."
|
||||||
|
when "canceled"
|
||||||
|
flash.now[:alert] = "Pagamento annullato. Nessun addebito è stato effettuato."
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -18,7 +18,7 @@ module Public
|
|||||||
return
|
return
|
||||||
end
|
end
|
||||||
invitation.accept!(current_user)
|
invitation.accept!(current_user)
|
||||||
redirect_to public_team_dashboard_path(invitation.team), notice: "Sei entrato nella squadra!"
|
redirect_to public_team_details_path(invitation.team), notice: "Sei entrato nella squadra!"
|
||||||
else
|
else
|
||||||
session[:pending_invite_token] = params[:token]
|
session[:pending_invite_token] = params[:token]
|
||||||
redirect_to public_signup_path, notice: "Registrati con #{invitation.email} per accettare l'invito"
|
redirect_to public_signup_path, notice: "Registrati con #{invitation.email} per accettare l'invito"
|
||||||
|
|||||||
@@ -1,47 +1,86 @@
|
|||||||
module Public
|
module Public
|
||||||
class LiveController < SiteBaseController
|
class LiveController < SiteBaseController
|
||||||
|
include MediamtxPlayback
|
||||||
|
|
||||||
layout "marketing_live"
|
layout "marketing_live"
|
||||||
|
|
||||||
ACTIVE_STATUSES = %w[live connecting reconnecting].freeze
|
ACTIVE_STATUSES = %w[live connecting reconnecting].freeze
|
||||||
|
|
||||||
def index
|
def index
|
||||||
@query = params[:q].to_s.strip
|
@query = params[:q].to_s.strip
|
||||||
@sessions = StreamSession
|
@club = Club.find_by(id: params[:club_id]) if params[:club_id].present?
|
||||||
|
team_ids = @club&.teams&.pluck(:id)
|
||||||
|
|
||||||
|
sessions = StreamSession
|
||||||
.broadcasting
|
.broadcasting
|
||||||
.includes(:score_state, match: :team)
|
.publicly_listed
|
||||||
|
.where(platform: "matchlivetv")
|
||||||
|
.includes(:score_state, match: { team: :club })
|
||||||
|
sessions = sessions.joins(:match).where(matches: { team_id: team_ids }) if team_ids.present?
|
||||||
|
|
||||||
|
@sessions = sessions
|
||||||
.search_by_team_or_opponent(@query)
|
.search_by_team_or_opponent(@query)
|
||||||
.order(Arel.sql("started_at DESC NULLS LAST"), created_at: :desc)
|
.order(Arel.sql("started_at DESC NULLS LAST"), created_at: :desc)
|
||||||
|
|
||||||
|
# Solo dirette già in onda: le partite «programmate» restano visibili anche se c’è sessione idle.
|
||||||
|
broadcasting_match_ids = StreamSession.broadcasting.select(:match_id)
|
||||||
|
upcoming = Match.scheduled_for_live.includes(team: :club)
|
||||||
|
upcoming = upcoming.where(team_id: team_ids) if team_ids.present?
|
||||||
|
|
||||||
|
@upcoming_matches = upcoming
|
||||||
|
.search_teams_or_opponents(@query)
|
||||||
|
.where.not(id: broadcasting_match_ids)
|
||||||
|
.order(scheduled_at: :asc)
|
||||||
|
.limit(50)
|
||||||
|
|
||||||
@online_paths = Mediamtx::Client.new.online_path_names
|
@online_paths = Mediamtx::Client.new.online_path_names
|
||||||
|
|
||||||
|
return unless logged_in? && @club
|
||||||
|
|
||||||
|
@schedulable_teams = current_user.schedulable_teams_for(@club)
|
||||||
|
@can_schedule_match = @schedulable_teams.any?
|
||||||
end
|
end
|
||||||
|
|
||||||
def show
|
def show
|
||||||
@session = StreamSession.includes(match: :team).find(params[:id])
|
@session = StreamSession.includes(match: { team: :club }).find(params[:id])
|
||||||
|
@session = Mediamtx::PublisherSync.new(@session).call unless @session.terminal?
|
||||||
@match = @session.match
|
@match = @session.match
|
||||||
@stream_closed = @session.terminal?
|
@stream_closed = @session.terminal?
|
||||||
@on_air = !@stream_closed && mediamtx_online?(@session)
|
@on_air = !@stream_closed && (
|
||||||
|
mediamtx_stream_playable?(@session) ||
|
||||||
|
@session.status.in?(%w[connecting live reconnecting paused])
|
||||||
|
)
|
||||||
|
@publisher_online = !@stream_closed && mediamtx_publisher_online?(@session)
|
||||||
end
|
end
|
||||||
|
|
||||||
def status
|
def status
|
||||||
session = StreamSession.includes(match: :team).find(params[:id])
|
# Mai cache: il tabellone deve restare allineato con l'app (poll ogni ~1,5s).
|
||||||
|
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
|
||||||
|
response.headers["Pragma"] = "no-cache"
|
||||||
|
|
||||||
|
session = StreamSession.includes(match: { team: :club }).find(params[:id])
|
||||||
|
session = Mediamtx::PublisherSync.new(session).call unless session.terminal?
|
||||||
closed = session.terminal?
|
closed = session.terminal?
|
||||||
|
publisher_online = !closed && mediamtx_publisher_online?(session)
|
||||||
|
playable = !closed && mediamtx_stream_playable?(session)
|
||||||
render json: {
|
render json: {
|
||||||
status: session.status,
|
status: session.status,
|
||||||
|
paused: session.paused?,
|
||||||
stream_closed: closed,
|
stream_closed: closed,
|
||||||
live: !closed && (session.live? || mediamtx_online?(session)),
|
live: !closed && (
|
||||||
on_air: !closed && mediamtx_online?(session),
|
session.live? || session.paused? || session.connecting? || session.reconnecting? ||
|
||||||
|
mediamtx_publisher_online?(session)
|
||||||
|
),
|
||||||
|
on_air: playable || (!closed && session.status.in?(%w[connecting live reconnecting paused])),
|
||||||
|
publisher_online: publisher_online,
|
||||||
|
awaiting_signal: !closed && !mediamtx_path_has_output?(session),
|
||||||
|
showing_cover: !closed && mediamtx_path_has_output?(session) &&
|
||||||
|
(session.paused? || !mediamtx_publisher_online?(session)),
|
||||||
ended_at: session.ended_at,
|
ended_at: session.ended_at,
|
||||||
home_name: session.match.team.name,
|
home_name: session.match.team.name,
|
||||||
away_name: session.match.opponent_name,
|
away_name: session.match.opponent_name,
|
||||||
score: session.score_state&.as_cable_payload
|
score: session.score_state&.as_cable_payload
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def mediamtx_online?(session)
|
|
||||||
@online_paths_cache ||= Mediamtx::Client.new.online_path_names
|
|
||||||
@online_paths_cache.include?(session.mediamtx_path_name)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
102
backend/app/controllers/public/matches_controller.rb
Normal file
102
backend/app/controllers/public/matches_controller.rb
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
module Public
|
||||||
|
class MatchesController < WebBaseController
|
||||||
|
before_action :require_login!
|
||||||
|
before_action :set_team
|
||||||
|
before_action :require_can_schedule!
|
||||||
|
before_action :set_match, only: %i[edit update destroy]
|
||||||
|
|
||||||
|
def index
|
||||||
|
@matches = @team.matches
|
||||||
|
.includes(:stream_sessions)
|
||||||
|
.order(Arel.sql("scheduled_at ASC NULLS LAST"), created_at: :desc)
|
||||||
|
@can_manage = @team.club.owned_by?(current_user)
|
||||||
|
end
|
||||||
|
|
||||||
|
def new
|
||||||
|
@match = @team.matches.build(
|
||||||
|
sport: @team.sport,
|
||||||
|
sets_to_win: 3,
|
||||||
|
scheduled_at: default_scheduled_at
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
@match = @team.matches.create!(
|
||||||
|
match_params.merge(sport: @team.sport, sets_to_win: match_params[:sets_to_win].presence || 3)
|
||||||
|
)
|
||||||
|
redirect_to public_team_matches_path(@team),
|
||||||
|
notice: "Partita programmata: #{@match.opponent_name}. Avvia lo streaming dall’app quando sei in palestra."
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
@match = @team.matches.build(match_params)
|
||||||
|
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||||
|
render :new, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def edit
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
@match.update!(match_params)
|
||||||
|
redirect_to public_team_matches_path(@team), notice: "Partita aggiornata."
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||||
|
render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def destroy
|
||||||
|
active = active_session_for(@match)
|
||||||
|
if active&.resumable?
|
||||||
|
redirect_to public_team_matches_path(@team),
|
||||||
|
alert: "Chiudi la diretta prima di eliminare questa partita."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
@match.destroy!
|
||||||
|
redirect_to public_team_matches_path(@team), notice: "Partita eliminata."
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_team
|
||||||
|
@team = current_user.manageable_teams.find(params[:team_id])
|
||||||
|
@club = @team.club
|
||||||
|
end
|
||||||
|
|
||||||
|
def require_can_schedule!
|
||||||
|
return if current_user.can_schedule_for?(@team)
|
||||||
|
|
||||||
|
redirect_to public_team_details_path(@team),
|
||||||
|
alert: "Solo un responsabile trasmissione o il titolare della società possono programmare le partite."
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_match
|
||||||
|
@match = @team.matches.find(params[:id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def match_params
|
||||||
|
p = params.require(:match).permit(:opponent_name, :location, :scheduled_at, :sport, :sets_to_win)
|
||||||
|
p[:scheduled_at] = parse_scheduled_at(p[:scheduled_at]) if p[:scheduled_at].present?
|
||||||
|
p
|
||||||
|
end
|
||||||
|
|
||||||
|
def parse_scheduled_at(value)
|
||||||
|
raw = value.to_s.strip
|
||||||
|
return nil if raw.blank?
|
||||||
|
|
||||||
|
Time.zone.strptime(raw, "%Y-%m-%dT%H:%M")
|
||||||
|
rescue ArgumentError
|
||||||
|
Time.zone.parse(raw)
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_scheduled_at
|
||||||
|
t = Time.current + 2.hours
|
||||||
|
Time.zone.local(t.year, t.month, t.day, t.hour, 0, 0)
|
||||||
|
end
|
||||||
|
|
||||||
|
def active_session_for(match)
|
||||||
|
match.stream_sessions
|
||||||
|
.order(created_at: :desc)
|
||||||
|
.find { |s| !%w[ended error].include?(s.status) }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -8,6 +8,20 @@ module Public
|
|||||||
|
|
||||||
def pricing
|
def pricing
|
||||||
@plans = Plan.ordered
|
@plans = Plan.ordered
|
||||||
|
load_club_billing_context_for_pricing
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def load_club_billing_context_for_pricing
|
||||||
|
return unless logged_in?
|
||||||
|
|
||||||
|
@club = current_user.primary_club
|
||||||
|
return unless @club
|
||||||
|
|
||||||
|
@subscription = @club.subscription
|
||||||
|
@team = @club.teams.order(:name).first
|
||||||
|
@entitlements = @team&.entitlements
|
||||||
end
|
end
|
||||||
|
|
||||||
def privacy
|
def privacy
|
||||||
@@ -15,5 +29,14 @@ module Public
|
|||||||
|
|
||||||
def terms
|
def terms
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def cookies
|
||||||
|
end
|
||||||
|
|
||||||
|
def faq
|
||||||
|
end
|
||||||
|
|
||||||
|
def pallavolo
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
52
backend/app/controllers/public/password_resets_controller.rb
Normal file
52
backend/app/controllers/public/password_resets_controller.rb
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
module Public
|
||||||
|
class PasswordResetsController < WebBaseController
|
||||||
|
def new
|
||||||
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
user = User.find_by(email: params[:email]&.downcase&.strip)
|
||||||
|
if user
|
||||||
|
token = user.generate_password_reset!
|
||||||
|
UserMailer.password_reset(user, token).deliver_now
|
||||||
|
end
|
||||||
|
|
||||||
|
redirect_to public_login_path,
|
||||||
|
notice: "Se l'email è registrata, riceverai a breve un link per reimpostare la password."
|
||||||
|
end
|
||||||
|
|
||||||
|
def edit
|
||||||
|
@user = User.find_by_password_reset_token(params[:token])
|
||||||
|
if @user.nil? || @user.password_reset_expired?
|
||||||
|
redirect_to new_public_password_reset_path,
|
||||||
|
alert: "Link non valido o scaduto. Richiedi un nuovo reset password."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
@token = params[:token]
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
@user = User.find_by_password_reset_token(params[:token])
|
||||||
|
if @user.nil? || @user.password_reset_expired?
|
||||||
|
redirect_to new_public_password_reset_path,
|
||||||
|
alert: "Link non valido o scaduto. Richiedi un nuovo reset password."
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
if params[:password].blank? || params[:password].length < 8
|
||||||
|
flash.now[:alert] = "La password deve avere almeno 8 caratteri"
|
||||||
|
@token = params[:token]
|
||||||
|
return render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
if params[:password] != params[:password_confirmation]
|
||||||
|
flash.now[:alert] = "Le password non coincidono"
|
||||||
|
@token = params[:token]
|
||||||
|
return render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
@user.update!(password: params[:password])
|
||||||
|
@user.clear_password_reset!
|
||||||
|
redirect_to public_login_path, notice: "Password aggiornata. Ora puoi accedere."
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
81
backend/app/controllers/public/regia_controller.rb
Normal file
81
backend/app/controllers/public/regia_controller.rb
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
module Public
|
||||||
|
class RegiaController < SiteBaseController
|
||||||
|
include Public::LiveHelper
|
||||||
|
include MediamtxPlayback
|
||||||
|
|
||||||
|
layout "regia"
|
||||||
|
|
||||||
|
protect_from_forgery with: :null_session
|
||||||
|
skip_before_action :verify_authenticity_token, only: %i[score pause stop]
|
||||||
|
|
||||||
|
before_action :set_session_from_token
|
||||||
|
|
||||||
|
def show
|
||||||
|
@match = @session.match
|
||||||
|
@team = @match.team
|
||||||
|
@score = @session.score_state || @session.create_score_state!(
|
||||||
|
home_sets: 0, away_sets: 0, home_points: 0, away_points: 0, current_set: 1, set_partials: []
|
||||||
|
)
|
||||||
|
@rules = Scoring::Rules.from_match(@match)
|
||||||
|
@stream_closed = @session.terminal?
|
||||||
|
@on_air = !@stream_closed && mediamtx_stream_playable?(@session)
|
||||||
|
@share_url = request.original_url
|
||||||
|
@share_title = "Regia — #{@team.name} vs #{@match.opponent_name}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def status
|
||||||
|
render json: status_payload
|
||||||
|
end
|
||||||
|
|
||||||
|
def score
|
||||||
|
cmd = params[:cmd].presence || params[:score_action].presence
|
||||||
|
result = Scoring::ApplyAction.new(session: @session, action: cmd).call
|
||||||
|
render json: status_payload.merge(
|
||||||
|
set_won: result.set_won,
|
||||||
|
match_won: result.match_won,
|
||||||
|
winner: result.winner&.to_s
|
||||||
|
)
|
||||||
|
rescue ArgumentError => e
|
||||||
|
render json: { error: e.message }, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def pause
|
||||||
|
Sessions::Pause.new(@session).call
|
||||||
|
render json: status_payload
|
||||||
|
end
|
||||||
|
|
||||||
|
def stop
|
||||||
|
Sessions::Stop.new(@session).call
|
||||||
|
render json: status_payload
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_session_from_token
|
||||||
|
@session = Sessions::RegiaAccess.find_session_by_token(params[:token])
|
||||||
|
return if @session
|
||||||
|
|
||||||
|
render file: Rails.root.join("public/404.html"), status: :not_found, layout: false
|
||||||
|
throw :abort
|
||||||
|
end
|
||||||
|
|
||||||
|
def status_payload
|
||||||
|
score = @session.score_state
|
||||||
|
closed = @session.terminal?
|
||||||
|
playable = !closed && mediamtx_stream_playable?(@session)
|
||||||
|
{
|
||||||
|
status: @session.status,
|
||||||
|
paused: @session.paused?,
|
||||||
|
stream_closed: closed,
|
||||||
|
live: !closed && (@session.live? || @session.paused? || mediamtx_publisher_online?(@session)),
|
||||||
|
on_air: playable,
|
||||||
|
publisher_online: !closed && mediamtx_publisher_online?(@session),
|
||||||
|
ended_at: @session.ended_at,
|
||||||
|
home_name: @session.match.team.name,
|
||||||
|
away_name: @session.match.opponent_name,
|
||||||
|
points_target: Scoring::Rules.from_match(@session.match).points_target(score&.current_set || 1),
|
||||||
|
score: score&.as_cable_payload
|
||||||
|
}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,11 +1,17 @@
|
|||||||
module Public
|
module Public
|
||||||
class RegistrationsController < WebBaseController
|
class RegistrationsController < WebBaseController
|
||||||
def new
|
def new
|
||||||
redirect_to public_team_dashboard_path(current_user.teams.first) if logged_in? && current_user.teams.any?
|
redirect_to public_club_path(current_user.primary_club) if logged_in? && current_user.primary_club
|
||||||
@user = User.new
|
@user = User.new
|
||||||
end
|
end
|
||||||
|
|
||||||
def create
|
def create
|
||||||
|
unless params[:accept_terms] == "1"
|
||||||
|
@user = User.new(user_params.merge(role: "coach"))
|
||||||
|
flash.now[:alert] = "Devi accettare l’informativa privacy e i termini di servizio per registrarti."
|
||||||
|
return render :new, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
@user = User.new(user_params.merge(role: "coach"))
|
@user = User.new(user_params.merge(role: "coach"))
|
||||||
if @user.save
|
if @user.save
|
||||||
session[:user_id] = @user.id
|
session[:user_id] = @user.id
|
||||||
@@ -14,10 +20,10 @@ module Public
|
|||||||
invitation = TeamInvitation.pending.find_by(token_digest: Digest::SHA256.hexdigest(token))
|
invitation = TeamInvitation.pending.find_by(token_digest: Digest::SHA256.hexdigest(token))
|
||||||
if invitation && invitation.email.downcase == @user.email.downcase
|
if invitation && invitation.email.downcase == @user.email.downcase
|
||||||
invitation.accept!(@user)
|
invitation.accept!(@user)
|
||||||
return redirect_to public_team_dashboard_path(invitation.team), notice: "Benvenuto nella squadra!"
|
return redirect_to public_team_details_path(invitation.team), notice: "Benvenuto nella squadra!"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
redirect_to new_public_team_path, notice: "Account creato. Ora crea la tua squadra."
|
redirect_to public_new_club_path, notice: "Account creato. Ora registra la tua società."
|
||||||
else
|
else
|
||||||
flash.now[:alert] = @user.errors.full_messages.join(", ")
|
flash.now[:alert] = @user.errors.full_messages.join(", ")
|
||||||
render :new, status: :unprocessable_entity
|
render :new, status: :unprocessable_entity
|
||||||
|
|||||||
@@ -2,14 +2,102 @@ module Public
|
|||||||
class ReplayController < SiteBaseController
|
class ReplayController < SiteBaseController
|
||||||
layout "marketing_live"
|
layout "marketing_live"
|
||||||
|
|
||||||
def show
|
before_action :set_session_and_recording, only: %i[show stream thumbnail download]
|
||||||
@session = StreamSession.includes(match: :team).find(params[:id])
|
before_action :authorize_replay_access!, only: %i[show stream thumbnail download]
|
||||||
@recording = Recording.ready.find_by(stream_session: @session)
|
|
||||||
@match = @session.match
|
def index
|
||||||
|
@query = params[:q].to_s.strip
|
||||||
|
@recordings = Recording.ready.publicly_listed
|
||||||
|
.includes(stream_session: { match: { team: :club } })
|
||||||
|
.search_replays(@query)
|
||||||
|
.order(recorded_at: :desc, created_at: :desc)
|
||||||
|
.limit(100)
|
||||||
|
if params[:club_id].present?
|
||||||
|
@recordings = @recordings.joins(:team).where(teams: { club_id: params[:club_id] })
|
||||||
|
end
|
||||||
|
if params[:team_id].present?
|
||||||
|
@recordings = @recordings.where(team_id: params[:team_id])
|
||||||
|
end
|
||||||
|
@clubs = Club.joins(teams: :recordings)
|
||||||
|
.merge(Recording.ready.publicly_listed)
|
||||||
|
.distinct
|
||||||
|
.order(:name)
|
||||||
|
@filter_club = @clubs.find { |c| c.id.to_s == params[:club_id].to_s } if params[:club_id].present?
|
||||||
|
end
|
||||||
|
|
||||||
|
def show
|
||||||
|
@match = @session.match
|
||||||
|
end
|
||||||
|
|
||||||
|
def stream
|
||||||
|
Recordings::IncrementViews.new(@recording).call
|
||||||
|
serve_video(disposition: "inline")
|
||||||
|
end
|
||||||
|
|
||||||
|
def thumbnail
|
||||||
|
serve_thumbnail
|
||||||
|
end
|
||||||
|
|
||||||
|
def download
|
||||||
|
unless download_allowed?
|
||||||
|
redirect_to public_replay_path(@session), alert: "Download non disponibile"
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
serve_video(disposition: "attachment")
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def serve_video(disposition:)
|
||||||
|
Recordings::ServeFromStorage.new(
|
||||||
|
key: @recording.storage_key,
|
||||||
|
content_type: "video/mp4",
|
||||||
|
disposition: disposition,
|
||||||
|
filename: disposition == "attachment" ? download_filename : nil
|
||||||
|
).call(self)
|
||||||
|
rescue ArgumentError
|
||||||
|
head :not_found
|
||||||
|
end
|
||||||
|
|
||||||
|
def serve_thumbnail
|
||||||
|
key = @recording.thumbnail_storage_key
|
||||||
|
return head :not_found if key.blank?
|
||||||
|
|
||||||
|
Recordings::ServeFromStorage.new(
|
||||||
|
key: key,
|
||||||
|
content_type: "image/jpeg",
|
||||||
|
disposition: "inline"
|
||||||
|
).call(self)
|
||||||
|
rescue ArgumentError
|
||||||
|
head :not_found
|
||||||
|
end
|
||||||
|
|
||||||
|
def download_allowed?
|
||||||
|
ent = @recording.team.entitlements
|
||||||
|
return false unless ent.phone_download_enabled?
|
||||||
|
|
||||||
|
Recordings::AccessPolicy.new(@recording, viewer: current_user).allowed? ||
|
||||||
|
Recordings::AccessPolicy.new(@recording, viewer: current_user).manage_allowed?
|
||||||
|
end
|
||||||
|
|
||||||
|
def download_filename
|
||||||
|
slug = @recording.title_or_default.parameterize.presence || "replay"
|
||||||
|
"#{slug}.mp4"
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_session_and_recording
|
||||||
|
@session = StreamSession.includes(match: { team: :club }).find(params[:id])
|
||||||
|
@recording = Recording.not_deleted.find_by(stream_session: @session)
|
||||||
|
return if @recording
|
||||||
|
|
||||||
unless @recording
|
|
||||||
redirect_to public_live_path(@session), alert: "Replay non disponibile"
|
redirect_to public_live_path(@session), alert: "Replay non disponibile"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def authorize_replay_access!
|
||||||
|
return if Recordings::AccessPolicy.new(@recording, viewer: current_user).allowed?
|
||||||
|
|
||||||
|
redirect_to public_live_index_path, alert: "Replay non disponibile"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,14 +1,22 @@
|
|||||||
module Public
|
module Public
|
||||||
class SessionsController < WebBaseController
|
class SessionsController < WebBaseController
|
||||||
def new
|
def new
|
||||||
redirect_to public_team_dashboard_path(current_user.teams.first) if logged_in? && current_user.teams.any?
|
if logged_in? && current_user.primary_club
|
||||||
|
redirect_to public_club_path(current_user.primary_club)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def create
|
def create
|
||||||
user = User.find_by(email: params[:email]&.downcase)
|
user = User.find_by(email: params[:email]&.downcase)
|
||||||
if user&.authenticate(params[:password])
|
if user&.authenticate(params[:password])
|
||||||
session[:user_id] = user.id
|
session[:user_id] = user.id
|
||||||
dest = user.teams.first ? public_team_dashboard_path(user.teams.first) : new_public_team_path
|
dest = if user.primary_club
|
||||||
|
public_club_path(user.primary_club)
|
||||||
|
elsif user.manageable_teams.first
|
||||||
|
public_team_details_path(user.manageable_teams.first)
|
||||||
|
else
|
||||||
|
public_new_club_path
|
||||||
|
end
|
||||||
redirect_to dest, notice: "Bentornato!"
|
redirect_to dest, notice: "Bentornato!"
|
||||||
else
|
else
|
||||||
flash.now[:alert] = "Email o password non validi"
|
flash.now[:alert] = "Email o password non validi"
|
||||||
|
|||||||
@@ -2,10 +2,19 @@ module Public
|
|||||||
class SiteBaseController < ActionController::Base
|
class SiteBaseController < ActionController::Base
|
||||||
layout "marketing"
|
layout "marketing"
|
||||||
|
|
||||||
|
include ::SeoHelper
|
||||||
|
include ::LegalHelper
|
||||||
|
helper ApplicationHelper
|
||||||
helper_method :current_user, :logged_in?
|
helper_method :current_user, :logged_in?
|
||||||
|
|
||||||
|
before_action :set_site_locale
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
def set_site_locale
|
||||||
|
I18n.locale = :it
|
||||||
|
end
|
||||||
|
|
||||||
def current_user
|
def current_user
|
||||||
return @current_user if defined?(@current_user)
|
return @current_user if defined?(@current_user)
|
||||||
|
|
||||||
|
|||||||
22
backend/app/controllers/public/sitemap_controller.rb
Normal file
22
backend/app/controllers/public/sitemap_controller.rb
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
module Public
|
||||||
|
class SitemapController < ActionController::Base
|
||||||
|
def show
|
||||||
|
base = MatchLiveTv.app_public_url.chomp("/")
|
||||||
|
@entries = [
|
||||||
|
{ loc: "#{base}/", changefreq: "weekly", priority: "1.0" },
|
||||||
|
{ loc: "#{base}/funzionalita", changefreq: "monthly", priority: "0.9" },
|
||||||
|
{ loc: "#{base}/prezzi", changefreq: "monthly", priority: "0.9" },
|
||||||
|
{ loc: "#{base}/pallavolo-giovanile", changefreq: "monthly", priority: "0.85" },
|
||||||
|
{ loc: "#{base}/faq", changefreq: "monthly", priority: "0.8" },
|
||||||
|
{ loc: "#{base}/live", changefreq: "hourly", priority: "0.85" },
|
||||||
|
{ loc: "#{base}/privacy", changefreq: "yearly", priority: "0.3" },
|
||||||
|
{ loc: "#{base}/cookie", changefreq: "yearly", priority: "0.3" },
|
||||||
|
{ loc: "#{base}/termini", changefreq: "yearly", priority: "0.3" }
|
||||||
|
]
|
||||||
|
|
||||||
|
respond_to do |format|
|
||||||
|
format.xml { render layout: false }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
module Public
|
||||||
|
class TeamRosterMembersController < WebBaseController
|
||||||
|
before_action :require_login!
|
||||||
|
before_action :set_team
|
||||||
|
before_action :require_team_owner!
|
||||||
|
before_action :set_member, only: %i[edit update destroy]
|
||||||
|
|
||||||
|
def create
|
||||||
|
member = @team.roster_members.build(member_params)
|
||||||
|
attach_photo(member)
|
||||||
|
member.save!
|
||||||
|
redirect_to public_team_details_path(@team), notice: "#{member.full_name} aggiunto all'organico."
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
redirect_to public_team_details_path(@team), alert: e.record.errors.full_messages.join(", ")
|
||||||
|
end
|
||||||
|
|
||||||
|
def edit
|
||||||
|
@club = @team.club
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
@member.assign_attributes(member_params)
|
||||||
|
attach_photo(@member)
|
||||||
|
@member.save!
|
||||||
|
redirect_to public_team_details_path(@team), notice: "Scheda aggiornata."
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
@club = @team.club
|
||||||
|
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||||
|
render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def destroy
|
||||||
|
name = @member.full_name
|
||||||
|
@member.destroy!
|
||||||
|
redirect_to public_team_details_path(@team), notice: "#{name} rimosso dall'organico."
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_team
|
||||||
|
@team = current_user.manageable_teams.find(params[:team_id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def require_team_owner!
|
||||||
|
require_club_owner_for_team!(@team)
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_member
|
||||||
|
@member = @team.roster_members.find(params[:id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def member_params
|
||||||
|
params.require(:team_roster_member).permit(
|
||||||
|
:category, :full_name, :role_label, :jersey_number, :bio, :position
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def attach_photo(member)
|
||||||
|
file = params.dig(:team_roster_member, :photo_file)
|
||||||
|
member.photo_file.attach(file) if file.present?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,82 +1,91 @@
|
|||||||
module Public
|
module Public
|
||||||
class TeamsController < WebBaseController
|
class TeamsController < WebBaseController
|
||||||
|
include BrandingAttachments
|
||||||
|
|
||||||
before_action :require_login!
|
before_action :require_login!
|
||||||
|
before_action :set_club, only: %i[new create]
|
||||||
before_action :set_team, only: %i[
|
before_action :set_team, only: %i[
|
||||||
dashboard billing checkout portal invite create_invitation
|
details dashboard roster edit update invite create_invitation
|
||||||
remove_member destroy_invitation
|
assign_self_staff clear_self_staff remove_member destroy_invitation
|
||||||
|
youtube_connect youtube_disconnect
|
||||||
]
|
]
|
||||||
|
|
||||||
def new
|
def new
|
||||||
redirect_to public_team_dashboard_path(current_user.teams.first) if current_user.teams.any?
|
redirect_to public_new_club_path if current_user.owned_clubs.none?
|
||||||
|
require_club_owner!(@club)
|
||||||
end
|
end
|
||||||
|
|
||||||
def create
|
def create
|
||||||
if current_user.user_teams.where(role: "owner").exists?
|
require_club_owner!(@club)
|
||||||
redirect_to public_team_dashboard_path(current_user.teams.first), alert: "Hai già una squadra"
|
team = @club.teams.create!(team_params)
|
||||||
return
|
attach_branding_logo(team)
|
||||||
|
redirect_to public_club_path(@club), notice: "Squadra «#{team.name}» aggiunta."
|
||||||
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
|
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||||
|
render :new, status: :unprocessable_entity
|
||||||
end
|
end
|
||||||
|
|
||||||
team = Team.create!(team_params)
|
def details
|
||||||
UserTeam.create!(user: current_user, team: team, role: "owner")
|
load_team_details!
|
||||||
plan = params[:plan].presence_in(%w[free premium_light premium_full]) || "free"
|
render :details
|
||||||
Billing::AssignPlan.call(team: team, plan_slug: plan)
|
|
||||||
|
|
||||||
if plan.in?(%w[premium_light premium_full]) && MatchLiveTv.stripe_enabled?
|
|
||||||
redirect_to public_team_checkout_path(team, plan: plan)
|
|
||||||
else
|
|
||||||
redirect_to public_team_dashboard_path(team), notice: "Squadra creata con piano Free"
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def dashboard
|
def dashboard
|
||||||
require_team_owner!(@team)
|
redirect_to public_team_details_path(params[:id])
|
||||||
@entitlements = @team.entitlements
|
|
||||||
@recordings = @team.recordings.ready.includes(stream_session: :match).order(created_at: :desc).limit(10)
|
|
||||||
@members = @team.user_teams.includes(:user).where.not(role: "owner")
|
|
||||||
@pending_invitations = @team.team_invitations.pending.order(created_at: :desc)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def billing
|
def roster
|
||||||
require_team_owner!(@team)
|
redirect_to public_team_details_path(params[:id])
|
||||||
@entitlements = @team.entitlements
|
|
||||||
@plans = Plan.ordered
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def checkout
|
def edit
|
||||||
require_team_owner!(@team)
|
require_club_owner_for_team!(@team)
|
||||||
unless MatchLiveTv.stripe_enabled?
|
@club = @team.club
|
||||||
redirect_to public_team_billing_path(@team), alert: "Pagamenti non ancora configurati sul server"
|
|
||||||
return
|
|
||||||
end
|
end
|
||||||
|
|
||||||
plan_slug = params[:plan].presence_in(%w[premium_light premium_full]) || "premium_light"
|
def update
|
||||||
url = Billing::Stripe::CheckoutSession.new(team: @team, user: current_user, plan_slug: plan_slug).url
|
require_club_owner_for_team!(@team)
|
||||||
redirect_to url, allow_other_host: true
|
@team.assign_attributes(team_params)
|
||||||
end
|
attach_branding_logo(@team)
|
||||||
|
attach_team_photo(@team)
|
||||||
def portal
|
@team.save!
|
||||||
require_team_owner!(@team)
|
redirect_to public_team_details_path(@team), notice: "Squadra aggiornata."
|
||||||
unless MatchLiveTv.stripe_enabled?
|
rescue ActiveRecord::RecordInvalid => e
|
||||||
redirect_to public_team_billing_path(@team), alert: "Portale pagamenti non configurato"
|
@club = @team.club
|
||||||
return
|
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||||
end
|
render :edit, status: :unprocessable_entity
|
||||||
|
|
||||||
url = Billing::Stripe::CheckoutSession.new(team: @team, user: current_user).portal_url
|
|
||||||
redirect_to url, allow_other_host: true
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def invite
|
def invite
|
||||||
require_team_owner!(@team)
|
require_club_owner_for_team!(@team)
|
||||||
@entitlements = @team.entitlements
|
@entitlements = @team.entitlements
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def assign_self_staff
|
||||||
|
require_club_owner_for_team!(@team)
|
||||||
|
membership = current_user.user_teams.find_or_initialize_by(team: @team)
|
||||||
|
membership.role = "member" if membership.new_record?
|
||||||
|
Teams::StaffAssignment.call(team: @team, user: current_user, membership: membership)
|
||||||
|
redirect_to public_team_details_path(@team), notice: "Il tuo account è ora responsabile trasmissione."
|
||||||
|
rescue Teams::StaffAssignmentError, Teams::EntitlementError => e
|
||||||
|
redirect_to public_team_details_path(@team), alert: e.message
|
||||||
|
end
|
||||||
|
|
||||||
|
def clear_self_staff
|
||||||
|
require_club_owner_for_team!(@team)
|
||||||
|
membership = current_user.user_teams.find_by(team: @team)
|
||||||
|
membership&.update!(staff_kind: nil)
|
||||||
|
redirect_to public_team_details_path(@team), notice: "Ruolo staff rimosso dal tuo account."
|
||||||
|
end
|
||||||
|
|
||||||
def create_invitation
|
def create_invitation
|
||||||
require_team_owner!(@team)
|
require_club_owner_for_team!(@team)
|
||||||
@entitlements = @team.entitlements
|
@entitlements = @team.entitlements
|
||||||
staff_kind = params[:staff_kind].presence_in(TeamInvitation::STAFF_KINDS) || "transmission"
|
staff_kind = "transmission"
|
||||||
@entitlements.assert_can_invite!(staff_kind: staff_kind)
|
@entitlements.assert_can_invite!(staff_kind: staff_kind)
|
||||||
|
|
||||||
email = params[:email]&.downcase&.strip
|
email = params[:email]&.downcase&.strip
|
||||||
|
Teams::StaffEmailValidator.assert_available!(team: @team, email: email, staff_kind: staff_kind)
|
||||||
token = TeamInvitation.generate_token
|
token = TeamInvitation.generate_token
|
||||||
@team.team_invitations.create!(
|
@team.team_invitations.create!(
|
||||||
email: email,
|
email: email,
|
||||||
@@ -88,32 +97,84 @@ module Public
|
|||||||
@invite_url = join_public_invitation_url(token: token)
|
@invite_url = join_public_invitation_url(token: token)
|
||||||
flash.now[:notice] = "Link invito generato (valido 7 giorni)"
|
flash.now[:notice] = "Link invito generato (valido 7 giorni)"
|
||||||
render :invite
|
render :invite
|
||||||
rescue Teams::EntitlementError => e
|
rescue Teams::EntitlementError, Teams::StaffAssignmentError => e
|
||||||
redirect_to public_team_invite_path(@team), alert: e.message
|
redirect_to public_team_invite_path(@team), alert: e.message
|
||||||
end
|
end
|
||||||
|
|
||||||
def remove_member
|
def remove_member
|
||||||
require_team_owner!(@team)
|
require_club_owner_for_team!(@team)
|
||||||
ut = @team.user_teams.find_by!(user_id: params[:user_id], role: "member")
|
ut = @team.user_teams.find_by!(user_id: params[:user_id], role: "member")
|
||||||
ut.destroy!
|
ut.destroy!
|
||||||
redirect_to public_team_dashboard_path(@team), notice: "Accesso revocato"
|
redirect_to public_team_details_path(@team), notice: "Accesso revocato"
|
||||||
end
|
end
|
||||||
|
|
||||||
def destroy_invitation
|
def destroy_invitation
|
||||||
require_team_owner!(@team)
|
require_club_owner_for_team!(@team)
|
||||||
inv = @team.team_invitations.pending.find(params[:invitation_id])
|
inv = @team.team_invitations.pending.find(params[:invitation_id])
|
||||||
inv.destroy!
|
inv.destroy!
|
||||||
redirect_to public_team_dashboard_path(@team), notice: "Invito annullato"
|
redirect_to public_team_details_path(@team), notice: "Invito annullato"
|
||||||
|
end
|
||||||
|
|
||||||
|
def youtube_connect
|
||||||
|
redirect_to public_club_youtube_connect_path(
|
||||||
|
@team.club_id,
|
||||||
|
return_app: params[:return_app]
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def youtube_disconnect
|
||||||
|
require_club_owner_for_team!(@team)
|
||||||
|
@team.club.youtube_credential&.destroy!
|
||||||
|
redirect_to public_club_path(@team.club), notice: "Canale YouTube della società scollegato"
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
def load_team_details!
|
||||||
|
@club = @team.club
|
||||||
|
@can_manage = @club.owned_by?(current_user)
|
||||||
|
@entitlements = @team.entitlements
|
||||||
|
@roster_by_category = @team.roster_by_category
|
||||||
|
if @can_manage
|
||||||
|
@roster_member = @team.roster_members.build(
|
||||||
|
category: params[:category].presence_in(TeamRosterMember::CATEGORIES) || "player"
|
||||||
|
)
|
||||||
|
end
|
||||||
|
@recordings = @team.recordings.not_deleted
|
||||||
|
.where(status: %w[ready processing])
|
||||||
|
.includes(stream_session: :match)
|
||||||
|
.order(recorded_at: :desc, created_at: :desc)
|
||||||
|
.limit(10)
|
||||||
|
@owner_membership = current_user.user_teams.find_by(team: @team)
|
||||||
|
@staff_memberships = @team.user_teams.includes(:user)
|
||||||
|
.where("user_teams.role = 'member' OR (user_teams.staff_kind IS NOT NULL)")
|
||||||
|
@pending_invitations = @team.team_invitations.pending.order(created_at: :desc)
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_club
|
||||||
|
@club = current_user.owned_clubs.find(params[:club_id])
|
||||||
|
end
|
||||||
|
|
||||||
def set_team
|
def set_team
|
||||||
@team = current_user.teams.find(params[:id])
|
@team = current_user.manageable_teams.find(params[:id])
|
||||||
|
end
|
||||||
|
|
||||||
|
def attach_team_photo(team)
|
||||||
|
file = params.dig(:team, :photo_file)
|
||||||
|
team.photo_file.attach(file) if file.present?
|
||||||
end
|
end
|
||||||
|
|
||||||
def team_params
|
def team_params
|
||||||
params.require(:team).permit(:name, :sport, :logo_url)
|
p = params.require(:team).permit(:name, :sport, :description, :logo_url, :primary_color, :secondary_color)
|
||||||
|
p[:primary_color] = p[:primary_color].presence
|
||||||
|
p[:secondary_color] = p[:secondary_color].presence
|
||||||
|
if p[:primary_color].present?
|
||||||
|
p[:primary_color] = normalize_hex_color(p[:primary_color], p[:primary_color])
|
||||||
|
end
|
||||||
|
if p[:secondary_color].present?
|
||||||
|
p[:secondary_color] = normalize_hex_color(p[:secondary_color], p[:secondary_color])
|
||||||
|
end
|
||||||
|
p
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -10,9 +10,12 @@ module Public
|
|||||||
redirect_to public_login_path, alert: "Accedi per continuare"
|
redirect_to public_login_path, alert: "Accedi per continuare"
|
||||||
end
|
end
|
||||||
|
|
||||||
def require_team_owner!(team)
|
def require_club_owner!(club)
|
||||||
membership = current_user.user_teams.find_by(team: team)
|
redirect_to public_prezzi_path, alert: "Accesso non consentito" unless club.owned_by?(current_user)
|
||||||
redirect_to public_prezzi_path, alert: "Accesso non consentito" unless membership&.role == "owner"
|
end
|
||||||
|
|
||||||
|
def require_club_owner_for_team!(team)
|
||||||
|
redirect_to public_prezzi_path, alert: "Accesso non consentito" unless team.club&.owned_by?(current_user)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
49
backend/app/controllers/youtube_oauth_callback_controller.rb
Normal file
49
backend/app/controllers/youtube_oauth_callback_controller.rb
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
# Callback OAuth YouTube (HTML). Non usare Api::V1 — ActionController::API non renderizza le view.
|
||||||
|
class YoutubeOauthCallbackController < ActionController::Base
|
||||||
|
def show
|
||||||
|
return redirect_to_oauth_error("Codice OAuth mancante") if params[:code].blank?
|
||||||
|
|
||||||
|
ctx = Youtube::OauthState.verify!(params[:state])
|
||||||
|
tokens = Youtube::OauthExchange.call(params[:code])
|
||||||
|
|
||||||
|
if ctx[:kind] == :platform
|
||||||
|
@refresh_token = tokens[:refresh_token]
|
||||||
|
@channel_title = tokens[:channel_title]
|
||||||
|
return render "admin/youtube/platform_token", layout: false
|
||||||
|
end
|
||||||
|
|
||||||
|
user = User.find(ctx[:user_id])
|
||||||
|
club = Club.find(ctx[:club_id])
|
||||||
|
unless club.owned_by?(user)
|
||||||
|
return redirect_to_oauth_error("Solo il titolare della società può collegare il canale YouTube")
|
||||||
|
end
|
||||||
|
|
||||||
|
cred = club.youtube_credential || club.build_youtube_credential
|
||||||
|
cred.update!(
|
||||||
|
access_token: tokens[:access_token],
|
||||||
|
refresh_token: tokens[:refresh_token] || cred.refresh_token,
|
||||||
|
expires_at: Time.current + tokens[:expires_in].seconds,
|
||||||
|
channel_id: tokens[:channel_id],
|
||||||
|
channel_title: tokens[:channel_title]
|
||||||
|
)
|
||||||
|
|
||||||
|
if ctx[:return_app]
|
||||||
|
redirect_to "matchlivetv://youtube-connected?club_id=#{club.id}", allow_other_host: true
|
||||||
|
else
|
||||||
|
redirect_to "#{public_base_url}/clubs/#{club.id}?youtube=connected", allow_other_host: true
|
||||||
|
end
|
||||||
|
rescue ArgumentError, Youtube::BroadcastService::Error => e
|
||||||
|
redirect_to_oauth_error(e.message)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def public_base_url
|
||||||
|
MatchLiveTv.app_public_url.chomp("/")
|
||||||
|
end
|
||||||
|
|
||||||
|
def redirect_to_oauth_error(message)
|
||||||
|
redirect_to "#{public_base_url}/prezzi?youtube_error=#{ERB::Util.url_encode(message)}",
|
||||||
|
allow_other_host: true
|
||||||
|
end
|
||||||
|
end
|
||||||
22
backend/app/helpers/admin_helper.rb
Normal file
22
backend/app/helpers/admin_helper.rb
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
module AdminHelper
|
||||||
|
def format_bytes(bytes)
|
||||||
|
return "—" if bytes.nil?
|
||||||
|
|
||||||
|
units = %w[B KB MB GB TB]
|
||||||
|
size = bytes.to_f
|
||||||
|
unit = units.shift
|
||||||
|
while size >= 1024 && units.any?
|
||||||
|
size /= 1024
|
||||||
|
unit = units.shift
|
||||||
|
end
|
||||||
|
"#{size.round(size >= 10 ? 0 : 1)} #{unit}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def format_duration_minutes(minutes)
|
||||||
|
return "0 min" if minutes.to_i <= 0
|
||||||
|
|
||||||
|
hours = minutes / 60
|
||||||
|
mins = minutes % 60
|
||||||
|
hours.positive? ? "#{hours}h #{mins}m" : "#{mins} min"
|
||||||
|
end
|
||||||
|
end
|
||||||
19
backend/app/helpers/application_helper.rb
Normal file
19
backend/app/helpers/application_helper.rb
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
module ApplicationHelper
|
||||||
|
PLAN_ICONS = {
|
||||||
|
"free" => "fa-solid fa-seedling",
|
||||||
|
"premium_light" => "fa-solid fa-rocket",
|
||||||
|
"premium_full" => "fa-solid fa-crown"
|
||||||
|
}.freeze
|
||||||
|
|
||||||
|
def plan_icon_class(plan)
|
||||||
|
PLAN_ICONS[plan.slug] || "fa-solid fa-circle"
|
||||||
|
end
|
||||||
|
|
||||||
|
# Data/ora nel fuso dell'app (Europe/Rome) e nella lingua del sito.
|
||||||
|
def l_local(date_or_time, format: :long)
|
||||||
|
return nil if date_or_time.blank?
|
||||||
|
|
||||||
|
value = date_or_time.respond_to?(:in_time_zone) ? date_or_time.in_time_zone : date_or_time
|
||||||
|
I18n.with_locale(:it) { I18n.l(value, format: format) }
|
||||||
|
end
|
||||||
|
end
|
||||||
9
backend/app/helpers/legal_helper.rb
Normal file
9
backend/app/helpers/legal_helper.rb
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
module LegalHelper
|
||||||
|
def legal_last_updated
|
||||||
|
"3 giugno 2026"
|
||||||
|
end
|
||||||
|
|
||||||
|
def cookie_policy_last_updated
|
||||||
|
"3 giugno 2026"
|
||||||
|
end
|
||||||
|
end
|
||||||
96
backend/app/helpers/public/billing_helper.rb
Normal file
96
backend/app/helpers/public/billing_helper.rb
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
module Public
|
||||||
|
module BillingHelper
|
||||||
|
def plan_billing_action(current_slug:, target_plan:, stripe_subscription_active:, current_interval: nil, subscription: nil)
|
||||||
|
if target_plan.slug == "free"
|
||||||
|
return { kind: :current, label: "Piano attuale" } if current_slug == "free"
|
||||||
|
return { kind: :none } if stripe_subscription_active
|
||||||
|
|
||||||
|
return { kind: :contact, label: "Per passare al piano Free, contatta il supporto." }
|
||||||
|
end
|
||||||
|
|
||||||
|
unless MatchLiveTv.stripe_enabled?
|
||||||
|
return { kind: :disabled, label: "Stripe non configurato" }
|
||||||
|
end
|
||||||
|
|
||||||
|
intervals = Billing::Stripe::PriceCatalog.available_intervals(plan_slug: target_plan.slug)
|
||||||
|
return { kind: :disabled, label: "Prezzi Stripe non configurati" } if intervals.empty?
|
||||||
|
|
||||||
|
active_interval = current_interval.presence || Billing::Stripe::PriceCatalog::DEFAULT_INTERVAL
|
||||||
|
|
||||||
|
if current_slug == target_plan.slug && stripe_subscription_active && !subscription&.plan_change_pending?
|
||||||
|
other_intervals = intervals - [active_interval]
|
||||||
|
if other_intervals.empty?
|
||||||
|
label = "Piano attuale — #{Billing::Stripe::PriceCatalog.label(plan_slug: target_plan.slug, interval: active_interval)}"
|
||||||
|
return { kind: :current, label: label }
|
||||||
|
end
|
||||||
|
|
||||||
|
return {
|
||||||
|
kind: :interval_switch,
|
||||||
|
plan: target_plan,
|
||||||
|
intervals: other_intervals,
|
||||||
|
current_interval: active_interval,
|
||||||
|
current_slug: current_slug,
|
||||||
|
subscription: subscription
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
if current_slug == "free" || !stripe_subscription_active
|
||||||
|
{ kind: :checkout_options, plan: target_plan, intervals: intervals, subscription: subscription }
|
||||||
|
else
|
||||||
|
{
|
||||||
|
kind: :change_options,
|
||||||
|
plan: target_plan,
|
||||||
|
intervals: intervals,
|
||||||
|
current_slug: current_slug,
|
||||||
|
current_interval: active_interval,
|
||||||
|
subscription: subscription
|
||||||
|
}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def plan_interval_checkout_path(club, plan, interval)
|
||||||
|
public_club_checkout_path(club, plan: plan.slug, interval: interval)
|
||||||
|
end
|
||||||
|
|
||||||
|
def plan_interval_button_label(plan, interval, kind: :checkout, **)
|
||||||
|
btn_kind = kind == :checkout_options ? :checkout : :change
|
||||||
|
Billing::Stripe::PlanChangeMessages.button_label(plan: plan, interval: interval, kind: btn_kind)
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing_plan_change_info_lines(subscription: nil)
|
||||||
|
Billing::Stripe::PlanChangeMessages.billing_info_lines(subscription: subscription)
|
||||||
|
end
|
||||||
|
|
||||||
|
def stripe_subscription_active?(subscription)
|
||||||
|
subscription&.stripe_subscription_id.present? && subscription.active?
|
||||||
|
end
|
||||||
|
|
||||||
|
def stripe_interval_available?(plan_slug, interval)
|
||||||
|
Billing::Stripe::PriceCatalog.configured?(plan_slug: plan_slug, interval: interval)
|
||||||
|
end
|
||||||
|
|
||||||
|
def plan_interval_button_class(interval, **)
|
||||||
|
if interval.to_s == "yearly"
|
||||||
|
"btn btn-primary plan-interval-btn plan-interval-btn--yearly"
|
||||||
|
else
|
||||||
|
"btn btn-outline plan-interval-btn plan-interval-btn--monthly"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def plan_intervals_for_display(intervals)
|
||||||
|
Array(intervals).sort_by { |i| i.to_s == "yearly" ? 0 : 1 }
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing_profile_blocks_premium?(club)
|
||||||
|
club.present? && !club.billing_profile_complete?
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing_profile_incomplete_message(club)
|
||||||
|
missing = club.billing_profile_errors
|
||||||
|
return "Completa i dati di fatturazione prima di attivare un piano premium." if missing.empty?
|
||||||
|
|
||||||
|
"Mancano: #{missing.join(", ")}."
|
||||||
|
end
|
||||||
|
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -15,14 +15,73 @@ module Public
|
|||||||
partials.map { |p| format_set_partial_entry(p) }.join(" · ")
|
partials.map { |p| format_set_partial_entry(p) }.join(" · ")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def live_scheduled_label(datetime)
|
||||||
|
return nil unless datetime
|
||||||
|
|
||||||
|
datetime.in_time_zone.strftime("%d/%m/%Y alle %H:%M")
|
||||||
|
end
|
||||||
|
|
||||||
|
def live_scheduled_relative(datetime)
|
||||||
|
return nil unless datetime
|
||||||
|
|
||||||
|
if datetime.to_date == Time.zone.today
|
||||||
|
"Oggi alle #{datetime.strftime('%H:%M')}"
|
||||||
|
elsif datetime.to_date == Time.zone.tomorrow
|
||||||
|
"Domani alle #{datetime.strftime('%H:%M')}"
|
||||||
|
else
|
||||||
|
live_scheduled_label(datetime)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def live_match_card_heading(match)
|
||||||
|
team = match.team
|
||||||
|
club_name = team.club&.name.presence || "Società"
|
||||||
|
content_tag(:h3, class: "live-card__title") do
|
||||||
|
safe_join([
|
||||||
|
content_tag(:span, club_name, class: "live-card__club"),
|
||||||
|
content_tag(:span, "#{team.name} vs #{match.opponent_name}", class: "live-card__matchup")
|
||||||
|
])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def live_match_page_heading(match)
|
||||||
|
team = match.team
|
||||||
|
club_name = team.club&.name.presence || "Società"
|
||||||
|
content_tag(:div, class: "live-page-heading") do
|
||||||
|
safe_join([
|
||||||
|
content_tag(:p, club_name, class: "live-page-heading__club"),
|
||||||
|
content_tag(:h1, "#{team.name} vs #{match.opponent_name}", class: "live-page-heading__matchup")
|
||||||
|
])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def live_score_points_label(match, score_state)
|
def live_score_points_label(match, score_state)
|
||||||
return "—" unless score_state
|
return "—" unless score_state
|
||||||
|
|
||||||
"#{match.team.name} #{score_state.home_points} - #{score_state.away_points} #{match.opponent_name}"
|
"#{match.team.name} #{score_state.home_points} - #{score_state.away_points} #{match.opponent_name}"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Colore ospite sul tabellone: secondario società se leggibile su bianco, altrimenti blu visitatore.
|
||||||
|
def live_scorebug_away_color(team)
|
||||||
|
club = team.club
|
||||||
|
candidate = club&.effective_secondary_color.presence || "#1565c0"
|
||||||
|
return candidate unless light_hex_color?(candidate)
|
||||||
|
|
||||||
|
"#1565c0"
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
def light_hex_color?(hex)
|
||||||
|
h = hex.to_s.delete_prefix("#")
|
||||||
|
return false unless h.match?(/\A\h{6}\z/i)
|
||||||
|
|
||||||
|
r = h[0..1].to_i(16)
|
||||||
|
g = h[2..3].to_i(16)
|
||||||
|
b = h[4..5].to_i(16)
|
||||||
|
(0.299 * r + 0.587 * g + 0.114 * b) > 200
|
||||||
|
end
|
||||||
|
|
||||||
def format_set_partial_entry(partial)
|
def format_set_partial_entry(partial)
|
||||||
data = partial.respond_to?(:with_indifferent_access) ? partial.with_indifferent_access : partial
|
data = partial.respond_to?(:with_indifferent_access) ? partial.with_indifferent_access : partial
|
||||||
set_no = data[:set] || data["set"]
|
set_no = data[:set] || data["set"]
|
||||||
|
|||||||
32
backend/app/helpers/roster_helper.rb
Normal file
32
backend/app/helpers/roster_helper.rb
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
module RosterHelper
|
||||||
|
def roster_person_avatar(person, team, size: 96)
|
||||||
|
primary = team.effective_primary_color
|
||||||
|
secondary = team.effective_secondary_color
|
||||||
|
style = "--avatar-primary:#{primary};--avatar-secondary:#{secondary};width:#{size}px;height:#{size}px"
|
||||||
|
|
||||||
|
if person.photo_url.present?
|
||||||
|
image_tag person.photo_url, alt: person.full_name, class: "roster-avatar roster-avatar--photo",
|
||||||
|
style: style, width: size, height: size
|
||||||
|
else
|
||||||
|
tag.div(
|
||||||
|
person.initials,
|
||||||
|
class: "roster-avatar roster-avatar--placeholder",
|
||||||
|
style: "#{style};font-size:#{(size * 0.34).round}px",
|
||||||
|
aria: { label: person.full_name }
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def roster_category_options
|
||||||
|
TeamRosterMember::DISPLAY_ORDER.map do |cat|
|
||||||
|
[TeamRosterMember::CATEGORY_LABELS[cat], cat]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def roster_player_role_options(selected = nil)
|
||||||
|
options_for_select(
|
||||||
|
[["— Seleziona ruolo —", ""]] + TeamRosterMember::VOLLEYBALL_PLAYER_ROLES.map { |r| [r, r] },
|
||||||
|
selected
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
33
backend/app/helpers/seo_helper.rb
Normal file
33
backend/app/helpers/seo_helper.rb
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
module SeoHelper
|
||||||
|
DEFAULT_OG_IMAGE_PATH = "/og-share.png"
|
||||||
|
|
||||||
|
def seo_site_url
|
||||||
|
MatchLiveTv.app_public_url.chomp("/")
|
||||||
|
end
|
||||||
|
|
||||||
|
def seo_absolute_url(path)
|
||||||
|
path = "/#{path}" unless path.start_with?("/")
|
||||||
|
"#{seo_site_url}#{path}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def seo_canonical_url
|
||||||
|
if content_for?(:canonical_url)
|
||||||
|
content_for(:canonical_url)
|
||||||
|
else
|
||||||
|
request.original_url.split("?").first
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def seo_og_image_url
|
||||||
|
if content_for?(:og_image)
|
||||||
|
img = content_for(:og_image)
|
||||||
|
img.start_with?("http") ? img : seo_absolute_url(img)
|
||||||
|
else
|
||||||
|
seo_absolute_url(DEFAULT_OG_IMAGE_PATH)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def seo_robots_content
|
||||||
|
content_for?(:robots) ? content_for(:robots) : "index, follow"
|
||||||
|
end
|
||||||
|
end
|
||||||
9
backend/app/helpers/staff_helper.rb
Normal file
9
backend/app/helpers/staff_helper.rb
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
module StaffHelper
|
||||||
|
def staff_role_label(membership, team)
|
||||||
|
Teams::StaffCoverage.new(team).role_label_for(membership)
|
||||||
|
end
|
||||||
|
|
||||||
|
def staff_coverage_for(team)
|
||||||
|
Teams::StaffCoverage.new(team)
|
||||||
|
end
|
||||||
|
end
|
||||||
17
backend/app/jobs/expire_ended_subscriptions_job.rb
Normal file
17
backend/app/jobs/expire_ended_subscriptions_job.rb
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Passa a Free le società con disdetta programmata e periodo scaduto (anche senza visita pagina billing).
|
||||||
|
class ExpireEndedSubscriptionsJob
|
||||||
|
include Sidekiq::Job
|
||||||
|
|
||||||
|
def perform
|
||||||
|
free_plan = Plan["free"]
|
||||||
|
|
||||||
|
Subscription.where(cancel_at_period_end: true)
|
||||||
|
.where("current_period_end <= ?", Time.current)
|
||||||
|
.where.not(plan_id: free_plan.id)
|
||||||
|
.find_each do |sub|
|
||||||
|
Billing::Stripe::FinalizeSubscription.call(club: sub.club)
|
||||||
|
rescue StandardError => e
|
||||||
|
Rails.logger.warn("[ExpireEndedSubscriptions] club=#{sub.club_id} #{e.message}")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
18
backend/app/jobs/recordings/expiry_warning_job.rb
Normal file
18
backend/app/jobs/recordings/expiry_warning_job.rb
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
module Recordings
|
||||||
|
class ExpiryWarningJob
|
||||||
|
include Sidekiq::Job
|
||||||
|
sidekiq_options retry: 1, queue: "default"
|
||||||
|
|
||||||
|
def perform
|
||||||
|
Recording.ready
|
||||||
|
.where(expiry_warning_sent_at: nil)
|
||||||
|
.where.not(expires_at: nil)
|
||||||
|
.where(expires_at: ..7.days.from_now)
|
||||||
|
.find_each do |recording|
|
||||||
|
Recordings::NotifyExpiring.new(recording).call
|
||||||
|
rescue StandardError => e
|
||||||
|
Rails.logger.warn("[Recordings::ExpiryWarningJob] #{recording.id}: #{e.message}")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
18
backend/app/jobs/recordings/post_process_job.rb
Normal file
18
backend/app/jobs/recordings/post_process_job.rb
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
module Recordings
|
||||||
|
class PostProcessJob
|
||||||
|
include Sidekiq::Job
|
||||||
|
sidekiq_options retry: 2, queue: "default"
|
||||||
|
|
||||||
|
def perform(recording_id)
|
||||||
|
recording = Recording.find_by(id: recording_id)
|
||||||
|
return unless recording&.ready?
|
||||||
|
|
||||||
|
Recordings::NotifyReady.new(recording).call
|
||||||
|
|
||||||
|
return unless recording.auto_publish_youtube?
|
||||||
|
return if recording.youtube_video_id.present?
|
||||||
|
|
||||||
|
Recordings::PublishToYoutubeJob.perform_async(recording.id)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
17
backend/app/jobs/recordings/publish_to_youtube_job.rb
Normal file
17
backend/app/jobs/recordings/publish_to_youtube_job.rb
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
module Recordings
|
||||||
|
class PublishToYoutubeJob
|
||||||
|
include Sidekiq::Job
|
||||||
|
sidekiq_options retry: 2, queue: "default"
|
||||||
|
|
||||||
|
def perform(recording_id)
|
||||||
|
recording = Recording.find_by(id: recording_id)
|
||||||
|
return unless recording&.ready?
|
||||||
|
|
||||||
|
Recordings::PublishToYoutube.new(recording).call
|
||||||
|
rescue Recordings::PublishToYoutube::Error => e
|
||||||
|
meta = recording.metadata.merge("youtube_publish_error" => e.message, "youtube_publish_failed_at" => Time.current.iso8601)
|
||||||
|
recording.update!(metadata: meta)
|
||||||
|
Rails.logger.warn("[Recordings::PublishToYoutubeJob] #{recording_id}: #{e.message}")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
14
backend/app/jobs/recordings/purge_expired_job.rb
Normal file
14
backend/app/jobs/recordings/purge_expired_job.rb
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
module Recordings
|
||||||
|
class PurgeExpiredJob
|
||||||
|
include Sidekiq::Job
|
||||||
|
sidekiq_options retry: 1, queue: "default"
|
||||||
|
|
||||||
|
def perform
|
||||||
|
Recording.expired_pending_purge.find_each do |recording|
|
||||||
|
Recordings::Delete.new(recording, reason: :expired).call
|
||||||
|
rescue StandardError => e
|
||||||
|
Rails.logger.warn("[Recordings::PurgeExpiredJob] #{recording.id}: #{e.message}")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
14
backend/app/jobs/recordings/upload_job.rb
Normal file
14
backend/app/jobs/recordings/upload_job.rb
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
module Recordings
|
||||||
|
class UploadJob
|
||||||
|
include Sidekiq::Job
|
||||||
|
sidekiq_options retry: 3, queue: "default"
|
||||||
|
|
||||||
|
def perform(session_id)
|
||||||
|
session = StreamSession.find_by(id: session_id)
|
||||||
|
return unless session
|
||||||
|
|
||||||
|
Recordings::UploadFromSession.new(session).call
|
||||||
|
Recordings::PurgeExpiredJob.perform_async
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
37
backend/app/jobs/stream_publisher_sync_job.rb
Normal file
37
backend/app/jobs/stream_publisher_sync_job.rb
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# Poll MediaMTX + pipeline YouTube automatica (webhook MediaMTX non disponibile in prod).
|
||||||
|
class StreamPublisherSyncJob < ApplicationJob
|
||||||
|
queue_as :default
|
||||||
|
|
||||||
|
INTERVAL = 5.seconds
|
||||||
|
ACTIVE_STATUSES = %w[connecting live reconnecting paused].freeze
|
||||||
|
REDIS_CHAIN_KEY = "stream_publisher_sync:chain"
|
||||||
|
RUN_LOCK_KEY = "stream_publisher_sync:run_lock"
|
||||||
|
|
||||||
|
def self.ensure_chain
|
||||||
|
return if redis.get(REDIS_CHAIN_KEY)
|
||||||
|
|
||||||
|
redis.set(REDIS_CHAIN_KEY, "1", ex: INTERVAL.to_i * 4)
|
||||||
|
set(wait: INTERVAL).perform_later
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.redis
|
||||||
|
@redis ||= Redis.new(url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0"))
|
||||||
|
end
|
||||||
|
|
||||||
|
def perform
|
||||||
|
return unless self.class.redis.set(RUN_LOCK_KEY, "1", nx: true, ex: INTERVAL.to_i)
|
||||||
|
|
||||||
|
begin
|
||||||
|
self.class.redis.set(REDIS_CHAIN_KEY, "1", ex: INTERVAL.to_i * 4)
|
||||||
|
|
||||||
|
StreamSession
|
||||||
|
.where(status: ACTIVE_STATUSES)
|
||||||
|
.find_each do |session|
|
||||||
|
Mediamtx::PublisherSync.new(session).call
|
||||||
|
end
|
||||||
|
ensure
|
||||||
|
self.class.set(wait: INTERVAL).perform_later
|
||||||
|
self.class.redis.del(RUN_LOCK_KEY)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
54
backend/app/jobs/youtube_broadcast_activate_job.rb
Normal file
54
backend/app/jobs/youtube_broadcast_activate_job.rb
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
class YoutubeBroadcastActivateJob < ApplicationJob
|
||||||
|
queue_as :default
|
||||||
|
|
||||||
|
MAX_ATTEMPTS = 30
|
||||||
|
RETRY_WAIT = 15.seconds
|
||||||
|
RATE_LIMIT_WAIT = 90.seconds
|
||||||
|
LIVE_STATUSES = %w[live connecting reconnecting paused].freeze
|
||||||
|
|
||||||
|
def perform(session_id, attempt = 1)
|
||||||
|
session = StreamSession.find_by(id: session_id)
|
||||||
|
return unless session&.platform == "youtube"
|
||||||
|
return if session.terminal?
|
||||||
|
return if session.youtube_broadcast_id.blank?
|
||||||
|
return unless LIVE_STATUSES.include?(session.status)
|
||||||
|
return unless Youtube::LivePipeline.broadcast_ready?(session)
|
||||||
|
|
||||||
|
unless Streams::YoutubeRelay.running?(session.id)
|
||||||
|
Streams::YoutubeRelay.ensure_publishing!(session)
|
||||||
|
return reschedule(session_id, attempt + 1) if attempt < MAX_ATTEMPTS
|
||||||
|
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
result = Youtube::BroadcastService.new(session.match.team).activate_broadcast!(session.youtube_broadcast_id)
|
||||||
|
Rails.logger.info("[YoutubeBroadcastActivate] session=#{session.id} attempt=#{attempt} result=#{result}")
|
||||||
|
|
||||||
|
return if result == :live || result == :transitioned
|
||||||
|
|
||||||
|
if result == :rate_limited
|
||||||
|
reschedule(session_id, attempt, wait: RATE_LIMIT_WAIT)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
if result == :broadcast_ended
|
||||||
|
Youtube::SetupBroadcast.recreate!(session.reload)
|
||||||
|
Youtube::LivePipeline.schedule!(session.reload, force: true)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
if result == :waiting_ingest && (attempt % 4).zero?
|
||||||
|
Streams::YoutubeRelay.ensure_publishing!(session)
|
||||||
|
end
|
||||||
|
|
||||||
|
return if attempt >= MAX_ATTEMPTS
|
||||||
|
|
||||||
|
reschedule(session_id, attempt + 1)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def reschedule(session_id, attempt, wait: RETRY_WAIT)
|
||||||
|
self.class.set(wait: wait).perform_later(session_id, attempt)
|
||||||
|
end
|
||||||
|
end
|
||||||
61
backend/app/jobs/youtube_broadcast_setup_job.rb
Normal file
61
backend/app/jobs/youtube_broadcast_setup_job.rb
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
class YoutubeBroadcastSetupJob < ApplicationJob
|
||||||
|
queue_as :default
|
||||||
|
|
||||||
|
RUN_LOCK_KEY = "youtube_setup:running:%s"
|
||||||
|
MAX_RATE_LIMIT_ATTEMPTS = 15
|
||||||
|
RATE_LIMIT_WAITS = [30, 45, 60, 90, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120].freeze
|
||||||
|
|
||||||
|
def perform(session_id, youtube_channel = nil, attempt = 1)
|
||||||
|
session = StreamSession.find_by(id: session_id)
|
||||||
|
return unless session&.platform == "youtube"
|
||||||
|
return if session.terminal?
|
||||||
|
return if session.youtube_broadcast_id.present? && session.stream_key.present?
|
||||||
|
return unless acquire_run_lock!(session_id, attempt)
|
||||||
|
|
||||||
|
Youtube::SetupBroadcast.call(session, youtube_channel: youtube_channel.presence)
|
||||||
|
release_run_lock!(session_id)
|
||||||
|
rescue Youtube::SetupBroadcast::Error => e
|
||||||
|
if rate_limit?(e) && attempt < MAX_RATE_LIMIT_ATTEMPTS
|
||||||
|
Youtube::ApiThrottle.mark_rate_limited!
|
||||||
|
wait = RATE_LIMIT_WAITS[attempt - 1] || 120
|
||||||
|
extend_run_lock!(session_id, wait + 90)
|
||||||
|
Rails.logger.warn(
|
||||||
|
"[YoutubeBroadcastSetupJob] rate limit session=#{session_id} attempt=#{attempt} retry_in=#{wait}s"
|
||||||
|
)
|
||||||
|
self.class.set(wait: wait.seconds).perform_later(session_id, youtube_channel, attempt + 1)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
release_run_lock!(session_id)
|
||||||
|
raise
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def rate_limit?(error)
|
||||||
|
msg = error.message.to_s
|
||||||
|
msg.include?("rate limit") ||
|
||||||
|
msg.include?("userRequestsExceedRateLimit") ||
|
||||||
|
msg.include?("temporaneamente occupato")
|
||||||
|
end
|
||||||
|
|
||||||
|
def acquire_run_lock!(session_id, attempt)
|
||||||
|
key = format(RUN_LOCK_KEY, session_id)
|
||||||
|
if attempt > 1
|
||||||
|
return redis.exists?(key).positive?
|
||||||
|
end
|
||||||
|
|
||||||
|
redis.set(key, "1", nx: true, ex: 90)
|
||||||
|
end
|
||||||
|
|
||||||
|
def extend_run_lock!(session_id, seconds)
|
||||||
|
redis.expire(format(RUN_LOCK_KEY, session_id), seconds)
|
||||||
|
end
|
||||||
|
|
||||||
|
def release_run_lock!(session_id)
|
||||||
|
redis.del(format(RUN_LOCK_KEY, session_id))
|
||||||
|
end
|
||||||
|
|
||||||
|
def redis
|
||||||
|
@redis ||= Redis.new(url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0"))
|
||||||
|
end
|
||||||
|
end
|
||||||
57
backend/app/jobs/youtube_ingest_watchdog_job.rb
Normal file
57
backend/app/jobs/youtube_ingest_watchdog_job.rb
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
# Controlli ripetuti finché YouTube non ha ingest active (poi attiva la broadcast).
|
||||||
|
class YoutubeIngestWatchdogJob < ApplicationJob
|
||||||
|
queue_as :default
|
||||||
|
|
||||||
|
FIRST_WAIT = 20.seconds
|
||||||
|
NEXT_WAITS = [35.seconds, 45.seconds, 60.seconds].freeze
|
||||||
|
|
||||||
|
def perform(session_id, phase = 0)
|
||||||
|
session = StreamSession.find_by(id: session_id)
|
||||||
|
return unless Youtube::LivePipeline.broadcast_ready?(session)
|
||||||
|
return if Youtube::ApiThrottle.rate_limited?
|
||||||
|
|
||||||
|
ingest = youtube_ingest_status(session)
|
||||||
|
if ingest == "active"
|
||||||
|
Youtube::LivePipeline.schedule_activate!(session, force: true, wait: 3.seconds)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
if Streams::YoutubeRelay.running?(session.id)
|
||||||
|
Rails.logger.info("[YoutubeIngestWatchdog] relay ok ingest=#{ingest} phase=#{phase} session=#{session.id}")
|
||||||
|
else
|
||||||
|
Rails.logger.warn("[YoutubeIngestWatchdog] avvio relay ingest=#{ingest} session=#{session.id}")
|
||||||
|
Streams::YoutubeRelay.ensure_publishing!(session)
|
||||||
|
end
|
||||||
|
|
||||||
|
schedule_next(session_id, phase)
|
||||||
|
rescue StandardError => e
|
||||||
|
Rails.logger.warn("[YoutubeIngestWatchdog] session=#{session_id}: #{e.message}")
|
||||||
|
schedule_next(session_id, phase)
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.schedule_chain(session_id)
|
||||||
|
set(wait: FIRST_WAIT).perform_later(session_id, 0)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def schedule_next(session_id, phase)
|
||||||
|
wait = NEXT_WAITS[phase]
|
||||||
|
return unless wait
|
||||||
|
|
||||||
|
self.class.set(wait: wait).perform_later(session_id, phase + 1)
|
||||||
|
end
|
||||||
|
|
||||||
|
def youtube_ingest_status(session)
|
||||||
|
return nil if session.youtube_broadcast_id.blank?
|
||||||
|
|
||||||
|
client = Youtube::BroadcastService.new(session.match.team).send(:authorized_client)
|
||||||
|
b = client.list_live_broadcasts("status,contentDetails", id: session.youtube_broadcast_id).items&.first
|
||||||
|
return nil unless b
|
||||||
|
|
||||||
|
sid = b.content_details.bound_stream_id
|
||||||
|
client.list_live_streams("status", id: sid).items.first&.status&.stream_status
|
||||||
|
rescue StandardError
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
end
|
||||||
11
backend/app/jobs/youtube_relay_ensure_job.rb
Normal file
11
backend/app/jobs/youtube_relay_ensure_job.rb
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# Avvia/riavvia il relay YouTube solo nel container sidekiq (YOUTUBE_RELAY_WORKER=1).
|
||||||
|
class YoutubeRelayEnsureJob < ApplicationJob
|
||||||
|
queue_as :default
|
||||||
|
|
||||||
|
def perform(session_id)
|
||||||
|
session = StreamSession.find_by(id: session_id)
|
||||||
|
return unless session
|
||||||
|
|
||||||
|
Streams::YoutubeRelay.ensure_on_worker!(session)
|
||||||
|
end
|
||||||
|
end
|
||||||
10
backend/app/jobs/youtube_relay_stop_job.rb
Normal file
10
backend/app/jobs/youtube_relay_stop_job.rb
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
class YoutubeRelayStopJob < ApplicationJob
|
||||||
|
queue_as :default
|
||||||
|
|
||||||
|
def perform(session_id)
|
||||||
|
session = StreamSession.find_by(id: session_id)
|
||||||
|
return unless session
|
||||||
|
|
||||||
|
Streams::YoutubeRelay.stop_on_worker!(session) if Streams::YoutubeRelay.worker?
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
class ApplicationMailer < ActionMailer::Base
|
class ApplicationMailer < ActionMailer::Base
|
||||||
default from: "from@example.com"
|
default from: -> { MatchLiveTv.mail_from }
|
||||||
layout "mailer"
|
layout "mailer"
|
||||||
end
|
end
|
||||||
|
|||||||
18
backend/app/mailers/billing/invoice_mailer.rb
Normal file
18
backend/app/mailers/billing/invoice_mailer.rb
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
module Billing
|
||||||
|
class InvoiceMailer < ApplicationMailer
|
||||||
|
def invoice_pdf
|
||||||
|
@invoice = params[:invoice]
|
||||||
|
@club = @invoice.club
|
||||||
|
|
||||||
|
attachments["fattura-#{@invoice.number.parameterize}.pdf"] = {
|
||||||
|
mime_type: "application/pdf",
|
||||||
|
content: @invoice.pdf.download
|
||||||
|
}
|
||||||
|
|
||||||
|
mail(
|
||||||
|
to: @club.billing_email,
|
||||||
|
subject: "Fattura #{@invoice.display_number} — Match Live TV"
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
34
backend/app/mailers/recordings/replay_mailer.rb
Normal file
34
backend/app/mailers/recordings/replay_mailer.rb
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
module Recordings
|
||||||
|
class ReplayMailer < ApplicationMailer
|
||||||
|
default from: -> { MatchLiveTv.mail_from }
|
||||||
|
|
||||||
|
def replay_ready(recording:, recipient:)
|
||||||
|
@recording = recording
|
||||||
|
@team = recording.team
|
||||||
|
@club = @team.club
|
||||||
|
@recipient = recipient
|
||||||
|
@replay_url = recording.replay_url
|
||||||
|
@expires_at = recording.expires_at
|
||||||
|
|
||||||
|
mail(
|
||||||
|
to: recipient.email,
|
||||||
|
subject: "Replay pronto — #{recording.title_or_default}"
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def replay_expiring_soon(recording:, recipient:)
|
||||||
|
@recording = recording
|
||||||
|
@team = recording.team
|
||||||
|
@club = @team.club
|
||||||
|
@recipient = recipient
|
||||||
|
@replay_url = recording.replay_url
|
||||||
|
@expires_at = recording.expires_at
|
||||||
|
@days_left = ((recording.expires_at - Time.current) / 1.day).ceil
|
||||||
|
|
||||||
|
mail(
|
||||||
|
to: recipient.email,
|
||||||
|
subject: "Replay in scadenza tra #{@days_left} giorni — #{recording.title_or_default}"
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
11
backend/app/mailers/user_mailer.rb
Normal file
11
backend/app/mailers/user_mailer.rb
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
class UserMailer < ApplicationMailer
|
||||||
|
default from: -> { MatchLiveTv.mail_from }
|
||||||
|
|
||||||
|
def password_reset(user, token)
|
||||||
|
@user = user
|
||||||
|
@reset_url = public_password_reset_url(token: token)
|
||||||
|
@expiry_hours = MatchLiveTv.password_reset_expiry_hours
|
||||||
|
|
||||||
|
mail to: user.email, subject: "Reimposta la password — Match Live TV"
|
||||||
|
end
|
||||||
|
end
|
||||||
5
backend/app/models/admin_account.rb
Normal file
5
backend/app/models/admin_account.rb
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
class AdminAccount < ApplicationRecord
|
||||||
|
has_secure_password
|
||||||
|
|
||||||
|
validates :username, presence: true, uniqueness: true
|
||||||
|
end
|
||||||
63
backend/app/models/billing/invoice.rb
Normal file
63
backend/app/models/billing/invoice.rb
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
module Billing
|
||||||
|
class Invoice < ApplicationRecord
|
||||||
|
self.table_name = "billing_invoices"
|
||||||
|
|
||||||
|
STATUSES = %w[draft issued sent cancelled].freeze
|
||||||
|
SOURCES = %w[manual aruba].freeze
|
||||||
|
|
||||||
|
belongs_to :club
|
||||||
|
belongs_to :billing_payment, class_name: "Billing::Payment", optional: true
|
||||||
|
has_one_attached :pdf
|
||||||
|
|
||||||
|
validates :number, presence: true, uniqueness: { scope: :club_id }
|
||||||
|
validates :issued_on, presence: true
|
||||||
|
validates :amount_cents, numericality: { greater_than: 0 }
|
||||||
|
validates :currency, presence: true
|
||||||
|
validates :status, inclusion: { in: STATUSES }
|
||||||
|
validates :source, inclusion: { in: SOURCES }
|
||||||
|
validates :billing_payment_id, uniqueness: true, allow_nil: true
|
||||||
|
validate :pdf_present_when_issued, on: :issue
|
||||||
|
|
||||||
|
scope :recent, -> { order(issued_on: :desc, created_at: :desc) }
|
||||||
|
|
||||||
|
def amount_euros
|
||||||
|
amount_cents / 100.0
|
||||||
|
end
|
||||||
|
|
||||||
|
def formatted_amount
|
||||||
|
format("%.2f €", amount_euros)
|
||||||
|
end
|
||||||
|
|
||||||
|
def downloadable?
|
||||||
|
pdf.attached? && status.in?(%w[issued sent])
|
||||||
|
end
|
||||||
|
|
||||||
|
def draft?
|
||||||
|
status == "draft"
|
||||||
|
end
|
||||||
|
|
||||||
|
def display_number
|
||||||
|
n = number.to_s.strip
|
||||||
|
cleaned = n.gsub(/\baruba[-_\s]*/i, "").strip
|
||||||
|
cleaned.presence || n
|
||||||
|
end
|
||||||
|
|
||||||
|
def display_status
|
||||||
|
{
|
||||||
|
"draft" => "In preparazione",
|
||||||
|
"issued" => "Emessa",
|
||||||
|
"sent" => "Inviata",
|
||||||
|
"cancelled" => "Annullata"
|
||||||
|
}[status] || status
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def pdf_present_when_issued
|
||||||
|
return unless validation_context == :issue
|
||||||
|
return if pdf.attached?
|
||||||
|
|
||||||
|
errors.add(:pdf, "è obbligatorio per emettere la fattura")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
72
backend/app/models/billing/payment.rb
Normal file
72
backend/app/models/billing/payment.rb
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
module Billing
|
||||||
|
class Payment < ApplicationRecord
|
||||||
|
self.table_name = "billing_payments"
|
||||||
|
|
||||||
|
STATUSES = %w[paid failed refunded].freeze
|
||||||
|
|
||||||
|
belongs_to :club
|
||||||
|
has_one :invoice, class_name: "Billing::Invoice", foreign_key: :billing_payment_id, dependent: :nullify
|
||||||
|
|
||||||
|
validates :amount_cents, numericality: { greater_than: 0 }
|
||||||
|
validates :currency, presence: true
|
||||||
|
validates :status, inclusion: { in: STATUSES }
|
||||||
|
validates :stripe_invoice_id, uniqueness: true, allow_nil: true
|
||||||
|
|
||||||
|
scope :recent, -> { order(paid_at: :desc, created_at: :desc) }
|
||||||
|
|
||||||
|
# Pagamenti pagati senza PDF fattura caricato (da gestire in admin).
|
||||||
|
scope :awaiting_invoice_pdf, lambda {
|
||||||
|
where(status: "paid").where(
|
||||||
|
<<~SQL.squish,
|
||||||
|
NOT EXISTS (
|
||||||
|
SELECT 1 FROM billing_invoices bi
|
||||||
|
INNER JOIN active_storage_attachments asa
|
||||||
|
ON asa.record_type = 'Billing::Invoice'
|
||||||
|
AND asa.record_id = bi.id
|
||||||
|
AND asa.name = 'pdf'
|
||||||
|
WHERE bi.billing_payment_id = billing_payments.id
|
||||||
|
)
|
||||||
|
SQL
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
scope :with_invoice_pdf, lambda {
|
||||||
|
where(status: "paid").where(
|
||||||
|
<<~SQL.squish,
|
||||||
|
EXISTS (
|
||||||
|
SELECT 1 FROM billing_invoices bi
|
||||||
|
INNER JOIN active_storage_attachments asa
|
||||||
|
ON asa.record_type = 'Billing::Invoice'
|
||||||
|
AND asa.record_id = bi.id
|
||||||
|
AND asa.name = 'pdf'
|
||||||
|
WHERE bi.billing_payment_id = billing_payments.id
|
||||||
|
)
|
||||||
|
SQL
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
def awaiting_invoice_pdf?
|
||||||
|
status == "paid" && !invoice&.pdf&.attached?
|
||||||
|
end
|
||||||
|
|
||||||
|
def amount_euros
|
||||||
|
amount_cents / 100.0
|
||||||
|
end
|
||||||
|
|
||||||
|
def formatted_amount
|
||||||
|
format("%.2f €", amount_euros)
|
||||||
|
end
|
||||||
|
|
||||||
|
def display_description
|
||||||
|
PaymentDescription.for_payment(self)
|
||||||
|
end
|
||||||
|
|
||||||
|
def display_status
|
||||||
|
{ "paid" => "Pagato", "failed" => "Non riuscito", "refunded" => "Rimborsato" }[status] || status
|
||||||
|
end
|
||||||
|
|
||||||
|
def invoice_for_display
|
||||||
|
invoice
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
31
backend/app/models/club.rb
Normal file
31
backend/app/models/club.rb
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
class Club < ApplicationRecord
|
||||||
|
include Brandable
|
||||||
|
include ClubBillingProfile
|
||||||
|
|
||||||
|
has_many :club_memberships, dependent: :destroy
|
||||||
|
has_many :users, through: :club_memberships
|
||||||
|
has_many :teams, dependent: :destroy
|
||||||
|
has_one :youtube_credential, dependent: :destroy
|
||||||
|
has_one :subscription, dependent: :destroy
|
||||||
|
has_many :billing_payments, class_name: "Billing::Payment", dependent: :destroy
|
||||||
|
has_many :billing_invoices, class_name: "Billing::Invoice", dependent: :destroy
|
||||||
|
|
||||||
|
validates :name, presence: true
|
||||||
|
validates :sport, presence: true
|
||||||
|
validates :primary_color, presence: true
|
||||||
|
validates :secondary_color, presence: true
|
||||||
|
|
||||||
|
def owner
|
||||||
|
club_memberships.find_by(role: "owner")&.user
|
||||||
|
end
|
||||||
|
|
||||||
|
def owned_by?(user)
|
||||||
|
club_memberships.exists?(user: user, role: "owner")
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def branding_parent
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
end
|
||||||
9
backend/app/models/club_membership.rb
Normal file
9
backend/app/models/club_membership.rb
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
class ClubMembership < ApplicationRecord
|
||||||
|
ROLES = %w[owner].freeze
|
||||||
|
|
||||||
|
belongs_to :user
|
||||||
|
belongs_to :club
|
||||||
|
|
||||||
|
validates :role, inclusion: { in: ROLES }
|
||||||
|
validates :user_id, uniqueness: { scope: :club_id }
|
||||||
|
end
|
||||||
43
backend/app/models/concerns/brandable.rb
Normal file
43
backend/app/models/concerns/brandable.rb
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
module Brandable
|
||||||
|
extend ActiveSupport::Concern
|
||||||
|
|
||||||
|
HEX_COLOR = /\A#[0-9A-Fa-f]{6}\z/
|
||||||
|
|
||||||
|
included do
|
||||||
|
has_one_attached :logo_file
|
||||||
|
validates :primary_color, format: { with: HEX_COLOR }, allow_blank: true
|
||||||
|
validates :secondary_color, format: { with: HEX_COLOR }, allow_blank: true
|
||||||
|
end
|
||||||
|
|
||||||
|
def effective_primary_color
|
||||||
|
primary_color.presence || default_primary_color
|
||||||
|
end
|
||||||
|
|
||||||
|
def effective_secondary_color
|
||||||
|
secondary_color.presence || default_secondary_color
|
||||||
|
end
|
||||||
|
|
||||||
|
def effective_logo_url
|
||||||
|
if logo_file.attached?
|
||||||
|
Rails.application.routes.url_helpers.rails_blob_path(logo_file, only_path: true)
|
||||||
|
elsif logo_url.present?
|
||||||
|
logo_url
|
||||||
|
else
|
||||||
|
branding_parent&.effective_logo_url
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def default_primary_color
|
||||||
|
"#e53935"
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_secondary_color
|
||||||
|
"#ffffff"
|
||||||
|
end
|
||||||
|
|
||||||
|
def branding_parent
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
end
|
||||||
79
backend/app/models/concerns/club_billing_profile.rb
Normal file
79
backend/app/models/concerns/club_billing_profile.rb
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
module ClubBillingProfile
|
||||||
|
extend ActiveSupport::Concern
|
||||||
|
|
||||||
|
BILLING_ENTITY_TYPES = {
|
||||||
|
"company" => "Società / ASD con P.IVA",
|
||||||
|
"individual" => "Persona fisica",
|
||||||
|
"nonprofit" => "Associazione senza scopo di lucro"
|
||||||
|
}.freeze
|
||||||
|
|
||||||
|
included do
|
||||||
|
validates :billing_entity_type, inclusion: { in: BILLING_ENTITY_TYPES.keys }, allow_nil: true
|
||||||
|
validates :billing_email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_blank: true
|
||||||
|
validates :billing_recipient_code, length: { is: 7 }, allow_blank: true
|
||||||
|
validates :billing_province, length: { is: 2 }, allow_blank: true
|
||||||
|
validates :billing_country, length: { is: 2 }, allow_blank: true
|
||||||
|
validate :billing_profile_for_invoicing, on: :billing_profile
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing_profile_complete?
|
||||||
|
billing_profile_errors.empty?
|
||||||
|
end
|
||||||
|
|
||||||
|
# Campi minimi per intestazione fattura e invio (email PDF + SDI/PEC).
|
||||||
|
def billing_profile_errors
|
||||||
|
errors = []
|
||||||
|
errors << "Tipo intestatario" if billing_entity_type.blank?
|
||||||
|
errors << "Ragione sociale o nome intestatario" if billing_legal_name.blank?
|
||||||
|
errors << "Email di fatturazione" if billing_email.blank?
|
||||||
|
errors << "Indirizzo" if billing_address_line.blank?
|
||||||
|
errors << "Città" if billing_city.blank?
|
||||||
|
errors << "Provincia (sigla 2 lettere)" if billing_province.blank? || billing_province.to_s.length != 2
|
||||||
|
errors << "CAP" if billing_postal_code.blank?
|
||||||
|
errors << "Paese (ISO)" if billing_country.blank? || billing_country.to_s.length != 2
|
||||||
|
errors.concat(billing_tax_id_errors)
|
||||||
|
errors << "Codice destinatario SDI (7 caratteri) o PEC" if billing_recipient_code.blank? && billing_pec.blank?
|
||||||
|
errors << "Codice destinatario SDI (7 caratteri)" if billing_recipient_code.present? && billing_recipient_code.length != 7
|
||||||
|
errors
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing_tax_id_errors
|
||||||
|
case billing_entity_type
|
||||||
|
when "company"
|
||||||
|
billing_vat_number.blank? ? ["Partita IVA"] : []
|
||||||
|
when "individual"
|
||||||
|
billing_fiscal_code.blank? ? ["Codice Fiscale"] : []
|
||||||
|
else
|
||||||
|
billing_vat_number.blank? && billing_fiscal_code.blank? ? ["P.IVA o Codice Fiscale"] : []
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def billing_profile_summary
|
||||||
|
parts = [billing_legal_name.presence, billing_vat_number.presence && "P.IVA #{billing_vat_number}"]
|
||||||
|
parts.compact.join(" · ")
|
||||||
|
end
|
||||||
|
|
||||||
|
# Righe per intestazione fattura in admin (etichetta, valore).
|
||||||
|
def billing_profile_invoice_lines
|
||||||
|
lines = []
|
||||||
|
lines << ["Tipo", BILLING_ENTITY_TYPES[billing_entity_type]] if billing_entity_type.present?
|
||||||
|
lines << ["Intestatario", billing_legal_name]
|
||||||
|
lines << ["P.IVA", billing_vat_number] if billing_vat_number.present?
|
||||||
|
lines << ["Codice fiscale", billing_fiscal_code] if billing_fiscal_code.present?
|
||||||
|
lines << ["Email fatturazione", billing_email]
|
||||||
|
lines << ["Telefono", billing_phone] if billing_phone.present?
|
||||||
|
addr = [billing_address_line, billing_postal_code, billing_city, billing_province, billing_country].compact.join(", ")
|
||||||
|
lines << ["Indirizzo", addr] if addr.present?
|
||||||
|
lines << ["SDI", billing_recipient_code] if billing_recipient_code.present?
|
||||||
|
lines << ["PEC", billing_pec] if billing_pec.present?
|
||||||
|
lines
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def billing_profile_for_invoicing
|
||||||
|
billing_profile_errors.each do |message|
|
||||||
|
errors.add(:base, message)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -2,6 +2,57 @@ class Match < ApplicationRecord
|
|||||||
belongs_to :team
|
belongs_to :team
|
||||||
has_many :stream_sessions, dependent: :destroy
|
has_many :stream_sessions, dependent: :destroy
|
||||||
|
|
||||||
|
ACTIVE_SESSION_STATUSES = %w[live connecting reconnecting paused].freeze
|
||||||
|
|
||||||
validates :opponent_name, presence: true
|
validates :opponent_name, presence: true
|
||||||
validates :sets_to_win, numericality: { greater_than: 0, less_than: 6 }
|
validates :sets_to_win, numericality: { greater_than: 0, less_than: 6 }
|
||||||
|
|
||||||
|
# Partite ancora da giocare in diretta (orario nel futuro).
|
||||||
|
scope :scheduled_for_live, -> {
|
||||||
|
where.not(scheduled_at: nil).where("scheduled_at >= ?", Time.zone.now)
|
||||||
|
}
|
||||||
|
|
||||||
|
scope :scheduled_upcoming, -> { scheduled_for_live }
|
||||||
|
|
||||||
|
def scheduled_upcoming?
|
||||||
|
scheduled_at.present? && scheduled_at >= Time.zone.now
|
||||||
|
end
|
||||||
|
|
||||||
|
def scheduled_on_calendar?
|
||||||
|
scheduled_at.present? && scheduled_at >= Time.zone.now.beginning_of_day
|
||||||
|
end
|
||||||
|
|
||||||
|
def active_stream_session
|
||||||
|
stream_sessions.sort_by { |s| s.created_at }.reverse
|
||||||
|
.find { |s| !%w[ended error].include?(s.status) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def deletable?
|
||||||
|
session = active_stream_session
|
||||||
|
session.nil? || !session.resumable?
|
||||||
|
end
|
||||||
|
|
||||||
|
def public_status_label
|
||||||
|
active = active_stream_session
|
||||||
|
return "In corso / da riprendere" if active
|
||||||
|
return "Programmata" if scheduled_upcoming?
|
||||||
|
return "Pronta" if scheduled_at.present?
|
||||||
|
|
||||||
|
"Senza orario"
|
||||||
|
end
|
||||||
|
|
||||||
|
scope :search_teams_or_opponents, lambda { |query|
|
||||||
|
q = query.to_s.strip
|
||||||
|
return all if q.blank?
|
||||||
|
|
||||||
|
term = "%#{sanitize_sql_like(q)}%"
|
||||||
|
joins(team: :club).where(
|
||||||
|
"teams.name ILIKE :term OR matches.opponent_name ILIKE :term OR clubs.name ILIKE :term OR matches.location ILIKE :term",
|
||||||
|
term: term
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
def broadcast_active?
|
||||||
|
stream_sessions.where(status: ACTIVE_SESSION_STATUSES).exists?
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -16,10 +16,20 @@ class Plan < ApplicationRecord
|
|||||||
find_by!(slug: slug.to_s)
|
find_by!(slug: slug.to_s)
|
||||||
end
|
end
|
||||||
|
|
||||||
def allows_platform?(platform)
|
def self.tier(slug)
|
||||||
return false if platform.to_s == "youtube" && !youtube_enabled?
|
SLUGS.index(slug.to_s) || 0
|
||||||
|
end
|
||||||
|
|
||||||
Array(features["platforms"]).map(&:to_s).include?(platform.to_s)
|
def tier
|
||||||
|
self.class.tier(slug)
|
||||||
|
end
|
||||||
|
|
||||||
|
def allows_platform?(platform)
|
||||||
|
platform = platform.to_s
|
||||||
|
return false if platform == "youtube" && !youtube_enabled?
|
||||||
|
return true if platform == "youtube" && youtube_mode == "matchlivetv_light"
|
||||||
|
|
||||||
|
Array(features["platforms"]).map(&:to_s).include?(platform)
|
||||||
end
|
end
|
||||||
|
|
||||||
def feature(key)
|
def feature(key)
|
||||||
|
|||||||
@@ -1,21 +1,160 @@
|
|||||||
class Recording < ApplicationRecord
|
class Recording < ApplicationRecord
|
||||||
STATUSES = %w[processing ready expired].freeze
|
STATUSES = %w[processing ready expired failed].freeze
|
||||||
|
PRIVACY_STATUSES = %w[public unlisted].freeze
|
||||||
|
STORAGE_BACKENDS = %w[local s3].freeze
|
||||||
|
|
||||||
belongs_to :stream_session
|
belongs_to :stream_session
|
||||||
belongs_to :team
|
belongs_to :team
|
||||||
|
|
||||||
validates :status, inclusion: { in: STATUSES }
|
validates :status, inclusion: { in: STATUSES }
|
||||||
|
validates :privacy_status, inclusion: { in: PRIVACY_STATUSES }
|
||||||
|
validates :storage_backend, inclusion: { in: STORAGE_BACKENDS }
|
||||||
|
|
||||||
scope :ready, -> { where(status: "ready").where("expires_at IS NULL OR expires_at > ?", Time.current) }
|
scope :not_deleted, -> { where(deleted_at: nil) }
|
||||||
|
scope :ready, lambda {
|
||||||
|
not_deleted.where(status: "ready").where("expires_at IS NULL OR expires_at > ?", Time.current)
|
||||||
|
}
|
||||||
|
scope :publicly_listed, -> { where(privacy_status: "public") }
|
||||||
scope :for_team, ->(team) { where(team: team) }
|
scope :for_team, ->(team) { where(team: team) }
|
||||||
|
scope :for_club, lambda { |club|
|
||||||
|
joins(:team).where(teams: { club_id: club.id })
|
||||||
|
}
|
||||||
|
scope :expiring_within, lambda { |days|
|
||||||
|
ready.where(expires_at: ..days.days.from_now)
|
||||||
|
}
|
||||||
|
scope :expired_pending_purge, lambda {
|
||||||
|
not_deleted.where(status: %w[ready failed]).where("expires_at IS NOT NULL AND expires_at <= ?", Time.current)
|
||||||
|
}
|
||||||
|
scope :search_replays, lambda { |query|
|
||||||
|
q = query.to_s.strip
|
||||||
|
return all if q.blank?
|
||||||
|
|
||||||
|
term = "%#{sanitize_sql_like(q)}%"
|
||||||
|
joins(stream_session: { match: { team: :club } }).where(
|
||||||
|
"recordings.title ILIKE :term OR teams.name ILIKE :term OR matches.opponent_name ILIKE :term OR clubs.name ILIKE :term OR matches.location ILIKE :term",
|
||||||
|
term: term
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
before_validation :normalize_privacy_status
|
||||||
|
|
||||||
def replay_url
|
def replay_url
|
||||||
return nil unless ready? && stream_session_id.present?
|
return nil unless stream_session_id.present?
|
||||||
|
return nil unless ready? || status == "processing"
|
||||||
|
|
||||||
"#{MatchLiveTv.app_public_url.chomp('/')}/replay/#{stream_session_id}"
|
"#{MatchLiveTv.app_public_url.chomp('/')}/replay/#{stream_session_id}"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def playback_stream_url
|
||||||
|
return nil unless ready? && stream_session_id.present?
|
||||||
|
|
||||||
|
"#{MatchLiveTv.app_public_url.chomp('/')}/replay/#{stream_session_id}/stream"
|
||||||
|
end
|
||||||
|
|
||||||
|
def thumbnail_url
|
||||||
|
return nil unless thumbnail_storage_key.present? && stream_session_id.present?
|
||||||
|
|
||||||
|
"#{MatchLiveTv.app_public_url.chomp('/')}/replay/#{stream_session_id}/thumbnail"
|
||||||
|
end
|
||||||
|
|
||||||
|
def download_api_path
|
||||||
|
return nil unless ready?
|
||||||
|
|
||||||
|
"/api/v1/recordings/#{id}/download"
|
||||||
|
end
|
||||||
|
|
||||||
|
def youtube_watch_url
|
||||||
|
return nil if youtube_video_id.blank?
|
||||||
|
return nil if youtube_video_id.to_s.start_with?("mock_")
|
||||||
|
|
||||||
|
"https://www.youtube.com/watch?v=#{youtube_video_id}"
|
||||||
|
end
|
||||||
|
|
||||||
def ready?
|
def ready?
|
||||||
status == "ready" && (expires_at.nil? || expires_at.future?)
|
status == "ready" && !deleted? && (expires_at.nil? || expires_at.future?)
|
||||||
|
end
|
||||||
|
|
||||||
|
def deleted?
|
||||||
|
deleted_at.present?
|
||||||
|
end
|
||||||
|
|
||||||
|
def publicly_listed?
|
||||||
|
privacy_status == "public"
|
||||||
|
end
|
||||||
|
|
||||||
|
def unlisted?
|
||||||
|
privacy_status == "unlisted"
|
||||||
|
end
|
||||||
|
|
||||||
|
def auto_publish_youtube?
|
||||||
|
metadata.is_a?(Hash) && metadata["auto_publish_youtube"] == true
|
||||||
|
end
|
||||||
|
|
||||||
|
def ai_metadata
|
||||||
|
metadata.fetch("ai", {})
|
||||||
|
end
|
||||||
|
|
||||||
|
def merge_metadata!(attrs)
|
||||||
|
update!(metadata: metadata.merge(attrs.stringify_keys))
|
||||||
|
end
|
||||||
|
|
||||||
|
def title_or_default
|
||||||
|
title.presence || default_title
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_title
|
||||||
|
match = stream_session&.match
|
||||||
|
return "Replay" unless match
|
||||||
|
|
||||||
|
"#{match.team.name} vs #{match.opponent_name}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def recorded_at_or_fallback
|
||||||
|
recorded_at || stream_session&.ended_at || stream_session&.started_at || created_at
|
||||||
|
end
|
||||||
|
|
||||||
|
def duration_label
|
||||||
|
return "—" if duration_secs.to_i <= 0
|
||||||
|
|
||||||
|
mins = duration_secs / 60
|
||||||
|
secs = duration_secs % 60
|
||||||
|
format("%d:%02d", mins, secs)
|
||||||
|
end
|
||||||
|
|
||||||
|
def byte_size_label
|
||||||
|
bytes = byte_size.to_i
|
||||||
|
return "—" if bytes <= 0
|
||||||
|
|
||||||
|
if bytes >= 1.gigabyte
|
||||||
|
format("%.1f GB", bytes / 1.gigabyte.to_f)
|
||||||
|
elsif bytes >= 1.megabyte
|
||||||
|
format("%.1f MB", bytes / 1.megabyte.to_f)
|
||||||
|
else
|
||||||
|
format("%.0f KB", bytes / 1.kilobyte.to_f)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def views_label
|
||||||
|
count = view_count.to_i
|
||||||
|
return "0 visualizzazioni" if count.zero?
|
||||||
|
|
||||||
|
count == 1 ? "1 visualizzazione" : "#{count} visualizzazioni"
|
||||||
|
end
|
||||||
|
|
||||||
|
def status_label
|
||||||
|
return "Eliminato" if deleted?
|
||||||
|
return "Scaduto" if status == "expired"
|
||||||
|
return "Errore" if status == "failed"
|
||||||
|
return "In elaborazione" if status == "processing"
|
||||||
|
return "Scade presto" if expires_at.present? && expires_at <= 7.days.from_now
|
||||||
|
|
||||||
|
"Disponibile"
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def normalize_privacy_status
|
||||||
|
self.privacy_status = "public" if privacy_status == "private"
|
||||||
|
self.privacy_status = "unlisted" if privacy_status.blank?
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
class StreamEvent < ApplicationRecord
|
class StreamEvent < ApplicationRecord
|
||||||
EVENT_TYPES = %w[
|
EVENT_TYPES = %w[
|
||||||
connected disconnected reconnected quality_changed error paused resumed
|
connected disconnected reconnected quality_changed error paused resumed
|
||||||
started ended network_test pairing
|
started ended network_test pairing youtube_ready
|
||||||
].freeze
|
].freeze
|
||||||
|
|
||||||
belongs_to :stream_session
|
belongs_to :stream_session
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ class StreamSession < ApplicationRecord
|
|||||||
|
|
||||||
PLATFORMS = %w[matchlivetv youtube facebook twitch].freeze
|
PLATFORMS = %w[matchlivetv youtube facebook twitch].freeze
|
||||||
STATUSES = %w[idle connecting live reconnecting paused ended error].freeze
|
STATUSES = %w[idle connecting live reconnecting paused ended error].freeze
|
||||||
|
PRIVACY_STATUSES = %w[public unlisted private].freeze
|
||||||
|
|
||||||
belongs_to :match
|
belongs_to :match
|
||||||
belongs_to :user
|
belongs_to :user
|
||||||
@@ -12,17 +13,20 @@ class StreamSession < ApplicationRecord
|
|||||||
|
|
||||||
validates :platform, inclusion: { in: PLATFORMS }
|
validates :platform, inclusion: { in: PLATFORMS }
|
||||||
validates :status, inclusion: { in: STATUSES }
|
validates :status, inclusion: { in: STATUSES }
|
||||||
|
validates :privacy_status, inclusion: { in: PRIVACY_STATUSES }
|
||||||
|
|
||||||
|
before_validation :normalize_privacy_status
|
||||||
before_validation :ensure_publish_token, on: :create
|
before_validation :ensure_publish_token, on: :create
|
||||||
|
|
||||||
scope :broadcasting, -> { where(status: %w[live connecting reconnecting]) }
|
scope :broadcasting, -> { where(status: %w[live connecting reconnecting paused]) }
|
||||||
|
scope :publicly_listed, -> { where(privacy_status: "public") }
|
||||||
scope :search_by_team_or_opponent, lambda { |query|
|
scope :search_by_team_or_opponent, lambda { |query|
|
||||||
q = query.to_s.strip
|
q = query.to_s.strip
|
||||||
return all if q.blank?
|
return all if q.blank?
|
||||||
|
|
||||||
term = "%#{sanitize_sql_like(q)}%"
|
term = "%#{sanitize_sql_like(q)}%"
|
||||||
joins(match: :team).where(
|
joins(match: { team: :club }).where(
|
||||||
"teams.name ILIKE :term OR matches.opponent_name ILIKE :term",
|
"teams.name ILIKE :term OR matches.opponent_name ILIKE :term OR clubs.name ILIKE :term OR matches.location ILIKE :term",
|
||||||
term: term
|
term: term
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -50,11 +54,11 @@ class StreamSession < ApplicationRecord
|
|||||||
end
|
end
|
||||||
|
|
||||||
event :pause do
|
event :pause do
|
||||||
transitions from: :live, to: :paused
|
transitions from: %i[live reconnecting connecting], to: :paused
|
||||||
end
|
end
|
||||||
|
|
||||||
event :resume do
|
event :resume do
|
||||||
transitions from: :paused, to: :live
|
transitions from: :paused, to: :connecting
|
||||||
end
|
end
|
||||||
|
|
||||||
event :finish do
|
event :finish do
|
||||||
@@ -77,19 +81,52 @@ class StreamSession < ApplicationRecord
|
|||||||
"live/match_#{id}"
|
"live/match_#{id}"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def mediamtx_overlay_path_name
|
||||||
|
"#{mediamtx_path_name}_air"
|
||||||
|
end
|
||||||
|
|
||||||
def matchlivetv_platform?
|
def matchlivetv_platform?
|
||||||
platform == "matchlivetv"
|
platform == "matchlivetv"
|
||||||
end
|
end
|
||||||
|
|
||||||
def hls_playback_url
|
def hls_playback_url
|
||||||
base = MatchLiveTv.hls_public_url.chomp("/")
|
base = MatchLiveTv.hls_public_url.chomp("/")
|
||||||
"#{base}/#{mediamtx_path_name}/index.m3u8"
|
"#{base}/#{effective_hls_path_name}/index.m3u8"
|
||||||
|
end
|
||||||
|
|
||||||
|
def effective_hls_path_name
|
||||||
|
mediamtx_path_name
|
||||||
end
|
end
|
||||||
|
|
||||||
def watch_page_url
|
def watch_page_url
|
||||||
"#{MatchLiveTv.app_public_url.chomp('/')}/live/#{id}"
|
"#{MatchLiveTv.app_public_url.chomp('/')}/live/#{id}"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def youtube_watch_url
|
||||||
|
return nil if youtube_broadcast_id.blank?
|
||||||
|
return nil if youtube_broadcast_id.to_s.start_with?("mock_")
|
||||||
|
|
||||||
|
"https://www.youtube.com/watch?v=#{youtube_broadcast_id}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def share_url
|
||||||
|
return youtube_watch_url if platform == "youtube"
|
||||||
|
|
||||||
|
watch_page_url
|
||||||
|
end
|
||||||
|
|
||||||
|
def youtube_ready?
|
||||||
|
platform == "youtube" && youtube_watch_url.present?
|
||||||
|
end
|
||||||
|
|
||||||
|
def link_only?
|
||||||
|
privacy_status.in?(%w[unlisted private])
|
||||||
|
end
|
||||||
|
|
||||||
|
def publicly_listed?
|
||||||
|
privacy_status == "public"
|
||||||
|
end
|
||||||
|
|
||||||
def terminal?
|
def terminal?
|
||||||
status.in?(%w[ended error])
|
status.in?(%w[ended error])
|
||||||
end
|
end
|
||||||
@@ -136,6 +173,11 @@ class StreamSession < ApplicationRecord
|
|||||||
self.publish_token ||= SecureRandom.urlsafe_base64(32)
|
self.publish_token ||= SecureRandom.urlsafe_base64(32)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def normalize_privacy_status
|
||||||
|
self.privacy_status = "public" if privacy_status.blank?
|
||||||
|
self.privacy_status = "unlisted" if privacy_status == "private"
|
||||||
|
end
|
||||||
|
|
||||||
def record_ended_timestamps!
|
def record_ended_timestamps!
|
||||||
now = Time.current
|
now = Time.current
|
||||||
update!(ended_at: now) if ended_at.nil?
|
update!(ended_at: now) if ended_at.nil?
|
||||||
|
|||||||
@@ -2,11 +2,13 @@ class Subscription < ApplicationRecord
|
|||||||
STATUSES = %w[active trialing past_due canceled incomplete].freeze
|
STATUSES = %w[active trialing past_due canceled incomplete].freeze
|
||||||
ACTIVE_STATUSES = %w[active trialing].freeze
|
ACTIVE_STATUSES = %w[active trialing].freeze
|
||||||
|
|
||||||
belongs_to :team
|
belongs_to :club
|
||||||
belongs_to :plan
|
belongs_to :plan
|
||||||
|
belongs_to :pending_plan, class_name: "Plan", optional: true
|
||||||
|
belongs_to :admin_comped_by, class_name: "AdminAccount", optional: true
|
||||||
|
|
||||||
validates :status, inclusion: { in: STATUSES }
|
validates :status, inclusion: { in: STATUSES }
|
||||||
validates :team_id, uniqueness: true
|
validates :club_id, uniqueness: true
|
||||||
|
|
||||||
scope :active, -> { where(status: ACTIVE_STATUSES) }
|
scope :active, -> { where(status: ACTIVE_STATUSES) }
|
||||||
|
|
||||||
@@ -25,4 +27,12 @@ class Subscription < ApplicationRecord
|
|||||||
def free?
|
def free?
|
||||||
plan.slug == "free"
|
plan.slug == "free"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def plan_change_pending?
|
||||||
|
pending_plan_id.present?
|
||||||
|
end
|
||||||
|
|
||||||
|
def admin_comped?
|
||||||
|
admin_comped
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,19 +1,65 @@
|
|||||||
class Team < ApplicationRecord
|
class Team < ApplicationRecord
|
||||||
|
include Brandable
|
||||||
|
|
||||||
|
belongs_to :club
|
||||||
has_many :user_teams, dependent: :destroy
|
has_many :user_teams, dependent: :destroy
|
||||||
has_many :users, through: :user_teams
|
has_many :users, through: :user_teams
|
||||||
has_many :matches, dependent: :destroy
|
has_many :matches, dependent: :destroy
|
||||||
has_one :youtube_credential, dependent: :destroy
|
|
||||||
has_one :subscription, dependent: :destroy
|
|
||||||
has_many :recordings, dependent: :destroy
|
has_many :recordings, dependent: :destroy
|
||||||
has_many :team_invitations, dependent: :destroy
|
has_many :team_invitations, dependent: :destroy
|
||||||
|
has_many :roster_members, class_name: "TeamRosterMember", dependent: :destroy
|
||||||
|
|
||||||
|
has_one_attached :photo_file
|
||||||
|
|
||||||
validates :name, presence: true
|
validates :name, presence: true
|
||||||
|
validate :photo_file_type, if: -> { photo_file.attached? }
|
||||||
|
|
||||||
|
def subscription
|
||||||
|
club.subscription
|
||||||
|
end
|
||||||
|
|
||||||
def entitlements
|
def entitlements
|
||||||
@entitlements ||= Teams::Entitlements.new(self)
|
Teams::Entitlements.new(self)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Canale YouTube OAuth è unico per tutta la società (Premium Full).
|
||||||
|
def youtube_credential
|
||||||
|
club&.youtube_credential
|
||||||
end
|
end
|
||||||
|
|
||||||
def owner
|
def owner
|
||||||
user_teams.find_by(role: "owner")&.user
|
club&.owner
|
||||||
|
end
|
||||||
|
|
||||||
|
def team_photo_url
|
||||||
|
if photo_file.attached?
|
||||||
|
Rails.application.routes.url_helpers.rails_blob_path(photo_file, only_path: true)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def roster_by_category
|
||||||
|
TeamRosterMember::DISPLAY_ORDER.index_with do |cat|
|
||||||
|
roster_members.by_category(cat).to_a
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def photo_file_type
|
||||||
|
return if photo_file.content_type.in?(%w[image/png image/jpeg image/webp])
|
||||||
|
|
||||||
|
errors.add(:photo_file, "deve essere PNG, JPEG o WebP")
|
||||||
|
end
|
||||||
|
|
||||||
|
def branding_parent
|
||||||
|
club
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_primary_color
|
||||||
|
club&.primary_color.presence || super
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_secondary_color
|
||||||
|
club&.secondary_color.presence || super
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
class TeamInvitation < ApplicationRecord
|
class TeamInvitation < ApplicationRecord
|
||||||
STAFF_KINDS = %w[transmission regia].freeze
|
STAFF_KINDS = %w[transmission].freeze
|
||||||
|
|
||||||
belongs_to :team
|
belongs_to :team
|
||||||
|
|
||||||
|
|||||||
87
backend/app/models/team_roster_member.rb
Normal file
87
backend/app/models/team_roster_member.rb
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
class TeamRosterMember < ApplicationRecord
|
||||||
|
CATEGORIES = %w[staff coach manager player].freeze
|
||||||
|
# Ordine di visualizzazione in pagina organico
|
||||||
|
DISPLAY_ORDER = %w[coach manager player staff].freeze
|
||||||
|
CATEGORY_LABELS = {
|
||||||
|
"staff" => "Staff",
|
||||||
|
"coach" => "Allenatori",
|
||||||
|
"manager" => "Dirigenti",
|
||||||
|
"player" => "Giocatori"
|
||||||
|
}.freeze
|
||||||
|
|
||||||
|
VOLLEYBALL_PLAYER_ROLES = %w[
|
||||||
|
Schiacciatore
|
||||||
|
Opposto
|
||||||
|
Centrale
|
||||||
|
Palleggiatore
|
||||||
|
Libero
|
||||||
|
Universale
|
||||||
|
].freeze
|
||||||
|
|
||||||
|
belongs_to :team
|
||||||
|
|
||||||
|
has_one_attached :photo_file
|
||||||
|
|
||||||
|
validates :full_name, presence: true
|
||||||
|
validates :category, inclusion: { in: CATEGORIES }
|
||||||
|
validates :jersey_number, numericality: { only_integer: true, greater_than: 0, less_than: 100 }, allow_nil: true
|
||||||
|
validate :photo_file_type, if: -> { photo_file.attached? }
|
||||||
|
validate :player_role_label_valid, if: -> { category == "player" && role_label.present? }
|
||||||
|
|
||||||
|
before_validation :assign_position, on: :create
|
||||||
|
|
||||||
|
scope :ordered, -> { order(:position, :created_at) }
|
||||||
|
scope :by_category, ->(cat) { where(category: cat).ordered }
|
||||||
|
|
||||||
|
def category_label
|
||||||
|
CATEGORY_LABELS[category] || category
|
||||||
|
end
|
||||||
|
|
||||||
|
def initials
|
||||||
|
parts = full_name.to_s.split(/\s+/).reject(&:blank?)
|
||||||
|
return "?" if parts.empty?
|
||||||
|
|
||||||
|
parts.first(2).map { |p| p[0] }.join.upcase
|
||||||
|
end
|
||||||
|
|
||||||
|
def photo_url
|
||||||
|
return unless photo_file.attached?
|
||||||
|
|
||||||
|
Rails.application.routes.url_helpers.rails_blob_path(photo_file, only_path: true)
|
||||||
|
end
|
||||||
|
|
||||||
|
def display_role
|
||||||
|
role_label.presence || default_role_label
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def assign_position
|
||||||
|
return if position.positive? || team.blank?
|
||||||
|
|
||||||
|
max_pos = team.roster_members.where(category: category).maximum(:position) || -1
|
||||||
|
self.position = max_pos + 1
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_role_label
|
||||||
|
case category
|
||||||
|
when "coach" then "Allenatore"
|
||||||
|
when "manager" then "Dirigente"
|
||||||
|
when "staff" then "Staff"
|
||||||
|
when "player" then jersey_number.present? ? "Giocatore ##{jersey_number}" : "Giocatore"
|
||||||
|
else category
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def player_role_label_valid
|
||||||
|
return if role_label.in?(VOLLEYBALL_PLAYER_ROLES)
|
||||||
|
|
||||||
|
errors.add(:role_label, "non è un ruolo pallavolo valido")
|
||||||
|
end
|
||||||
|
|
||||||
|
def photo_file_type
|
||||||
|
return if photo_file.content_type.in?(%w[image/png image/jpeg image/webp])
|
||||||
|
|
||||||
|
errors.add(:photo_file, "deve essere PNG, JPEG o WebP")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -5,8 +5,66 @@ class User < ApplicationRecord
|
|||||||
|
|
||||||
has_many :user_teams, dependent: :destroy
|
has_many :user_teams, dependent: :destroy
|
||||||
has_many :teams, through: :user_teams
|
has_many :teams, through: :user_teams
|
||||||
|
has_many :club_memberships, dependent: :destroy
|
||||||
|
has_many :clubs, through: :club_memberships
|
||||||
|
has_many :owned_clubs, -> { where(club_memberships: { role: "owner" }) }, through: :club_memberships, source: :club
|
||||||
has_many :stream_sessions, dependent: :nullify
|
has_many :stream_sessions, dependent: :nullify
|
||||||
|
|
||||||
|
def manageable_teams
|
||||||
|
staff_ids = teams.select(:id)
|
||||||
|
owner_ids = Team.where(club_id: owned_clubs.select(:id)).select(:id)
|
||||||
|
Team.where(id: staff_ids).or(Team.where(id: owner_ids))
|
||||||
|
end
|
||||||
|
|
||||||
|
# Squadre da cui l'utente può programmare partite e avviare lo streaming (app).
|
||||||
|
def streamable_teams
|
||||||
|
manageable_teams.includes(:club).select { |team| can_stream_for?(team) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def club_admin?(club)
|
||||||
|
club&.owned_by?(self)
|
||||||
|
end
|
||||||
|
|
||||||
|
def can_schedule_for?(team)
|
||||||
|
return true if team.club&.owned_by?(self)
|
||||||
|
|
||||||
|
membership = user_teams.find_by(team: team)
|
||||||
|
return false if membership&.staff_kind.blank?
|
||||||
|
|
||||||
|
membership.staff_kind == "transmission"
|
||||||
|
end
|
||||||
|
|
||||||
|
def schedulable_teams_for(club)
|
||||||
|
teams = club.teams.order(:name).to_a
|
||||||
|
return teams if club.owned_by?(self)
|
||||||
|
|
||||||
|
teams.select { |team| can_schedule_for?(team) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def can_stream_for?(team)
|
||||||
|
return true if team.club&.owned_by?(self)
|
||||||
|
|
||||||
|
membership = user_teams.find_by(team: team)
|
||||||
|
return false if membership&.staff_kind.blank?
|
||||||
|
|
||||||
|
return true if membership.staff_kind == "transmission"
|
||||||
|
|
||||||
|
Teams::StaffCoverage.new(team).covers_both_roles?(membership)
|
||||||
|
end
|
||||||
|
|
||||||
|
def staff_role_for(team)
|
||||||
|
return "owner" if team.club&.owned_by?(self)
|
||||||
|
|
||||||
|
membership = user_teams.find_by(team: team)
|
||||||
|
return nil unless membership&.staff_kind.present?
|
||||||
|
|
||||||
|
"transmission"
|
||||||
|
end
|
||||||
|
|
||||||
|
def primary_club
|
||||||
|
owned_clubs.order(:created_at).first
|
||||||
|
end
|
||||||
|
|
||||||
validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
|
validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
|
||||||
validates :name, presence: true
|
validates :name, presence: true
|
||||||
validates :role, inclusion: { in: ROLES }
|
validates :role, inclusion: { in: ROLES }
|
||||||
@@ -14,4 +72,32 @@ class User < ApplicationRecord
|
|||||||
def admin?
|
def admin?
|
||||||
role == "admin"
|
role == "admin"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def generate_password_reset!
|
||||||
|
raw = SecureRandom.urlsafe_base64(32)
|
||||||
|
update!(
|
||||||
|
password_reset_digest: User.digest_token(raw),
|
||||||
|
password_reset_sent_at: Time.current
|
||||||
|
)
|
||||||
|
raw
|
||||||
|
end
|
||||||
|
|
||||||
|
def password_reset_expired?
|
||||||
|
password_reset_sent_at.blank? ||
|
||||||
|
password_reset_sent_at < MatchLiveTv.password_reset_expiry_hours.hours.ago
|
||||||
|
end
|
||||||
|
|
||||||
|
def clear_password_reset!
|
||||||
|
update!(password_reset_digest: nil, password_reset_sent_at: nil)
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.find_by_password_reset_token(token)
|
||||||
|
return if token.blank?
|
||||||
|
|
||||||
|
find_by(password_reset_digest: User.digest_token(token))
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.digest_token(token)
|
||||||
|
Digest::SHA256.hexdigest(token.to_s)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
23
backend/app/models/youtube/platform_credential.rb
Normal file
23
backend/app/models/youtube/platform_credential.rb
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
module Youtube
|
||||||
|
# Credenziali del canale YouTube Match Live TV (Premium Light), da ENV.
|
||||||
|
class PlatformCredential
|
||||||
|
attr_accessor :access_token, :expires_at
|
||||||
|
|
||||||
|
def refresh_token
|
||||||
|
ENV["YOUTUBE_PLATFORM_REFRESH_TOKEN"].presence
|
||||||
|
end
|
||||||
|
|
||||||
|
def expired?
|
||||||
|
expires_at.present? && expires_at < Time.current
|
||||||
|
end
|
||||||
|
|
||||||
|
def update!(attrs)
|
||||||
|
self.access_token = attrs[:access_token] if attrs.key?(:access_token)
|
||||||
|
self.expires_at = attrs[:expires_at] if attrs.key?(:expires_at)
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.configured?
|
||||||
|
ENV["YOUTUBE_PLATFORM_REFRESH_TOKEN"].present?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
class YoutubeCredential < ApplicationRecord
|
class YoutubeCredential < ApplicationRecord
|
||||||
belongs_to :team
|
belongs_to :club
|
||||||
|
|
||||||
attr_encrypted :access_token,
|
attr_encrypted :access_token,
|
||||||
key: :encryption_key,
|
key: :encryption_key,
|
||||||
|
|||||||
29
backend/app/services/admin/dashboard_stats.rb
Normal file
29
backend/app/services/admin/dashboard_stats.rb
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
module Admin
|
||||||
|
class DashboardStats
|
||||||
|
ACTIVE_STATUSES = %w[live reconnecting connecting paused].freeze
|
||||||
|
|
||||||
|
def call
|
||||||
|
now = Time.current
|
||||||
|
day_start = now.beginning_of_day
|
||||||
|
month_start = now.beginning_of_month
|
||||||
|
|
||||||
|
ended_today = StreamSession.where(status: "ended").where("ended_at >= ?", day_start)
|
||||||
|
ended_month = StreamSession.where(status: "ended").where("ended_at >= ?", month_start)
|
||||||
|
|
||||||
|
{
|
||||||
|
active_sessions: StreamSession.where(status: ACTIVE_STATUSES).count,
|
||||||
|
sessions_today: ended_today.count,
|
||||||
|
sessions_month: ended_month.count,
|
||||||
|
stream_minutes_today: (ended_today.sum(:total_duration_secs).to_i / 60.0).round,
|
||||||
|
stream_minutes_month: (ended_month.sum(:total_duration_secs).to_i / 60.0).round,
|
||||||
|
teams_count: Team.count,
|
||||||
|
users_count: User.count,
|
||||||
|
matches_count: Match.count,
|
||||||
|
recordings_count: Recording.not_deleted.count,
|
||||||
|
recordings_ready: Recording.ready.count,
|
||||||
|
recordings_bytes: Recording.ready.sum(:byte_size).to_i,
|
||||||
|
recordings_expiring_soon: Recording.ready.expiring_within(7).count,
|
||||||
|
}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
153
backend/app/services/admin/host_metrics.rb
Normal file
153
backend/app/services/admin/host_metrics.rb
Normal file
@@ -0,0 +1,153 @@
|
|||||||
|
module Admin
|
||||||
|
class HostMetrics
|
||||||
|
RECORDINGS_PATH = ENV.fetch("RECORDINGS_PATH", "/recordings")
|
||||||
|
ROOT_PATH = ENV.fetch("ADMIN_DISK_ROOT_PATH", "/")
|
||||||
|
|
||||||
|
def sample!
|
||||||
|
cpu = read_cpu_percent
|
||||||
|
memory = read_memory
|
||||||
|
disk = read_disk
|
||||||
|
network = read_network
|
||||||
|
|
||||||
|
sample = {
|
||||||
|
at: Time.current.iso8601,
|
||||||
|
cpu: cpu,
|
||||||
|
mem: memory[:used_percent]
|
||||||
|
}
|
||||||
|
MetricsStore.push_sample(sample)
|
||||||
|
|
||||||
|
{
|
||||||
|
cpu: cpu,
|
||||||
|
memory: memory,
|
||||||
|
disk: disk,
|
||||||
|
network: network,
|
||||||
|
history: MetricsStore.history,
|
||||||
|
load_avg: read_load_avg
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def read_cpu_percent
|
||||||
|
a = cpu_jiffies
|
||||||
|
sleep 0.08
|
||||||
|
b = cpu_jiffies
|
||||||
|
return 0.0 unless a && b
|
||||||
|
|
||||||
|
idle_delta = b[:idle] - a[:idle]
|
||||||
|
total_delta = b[:total] - a[:total]
|
||||||
|
return 0.0 if total_delta <= 0
|
||||||
|
|
||||||
|
((1.0 - (idle_delta.to_f / total_delta)) * 100).round(1)
|
||||||
|
rescue StandardError
|
||||||
|
0.0
|
||||||
|
end
|
||||||
|
|
||||||
|
def cpu_jiffies
|
||||||
|
line = File.read("/proc/stat").each_line.find { |l| l.start_with?("cpu ") }
|
||||||
|
return nil unless line
|
||||||
|
|
||||||
|
parts = line.split[1..-1].map(&:to_i)
|
||||||
|
idle = parts[3] + (parts[4] || 0)
|
||||||
|
total = parts.sum
|
||||||
|
{ idle: idle, total: total }
|
||||||
|
rescue StandardError
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
|
||||||
|
def read_memory
|
||||||
|
info = {}
|
||||||
|
File.read("/proc/meminfo").each_line do |line|
|
||||||
|
key, value = line.split(":", 2)
|
||||||
|
info[key.strip] = value.to_i
|
||||||
|
end
|
||||||
|
total = info["MemTotal"] * 1024
|
||||||
|
available = (info["MemAvailable"] || info["MemFree"]) * 1024
|
||||||
|
used = [total - available, 0].max
|
||||||
|
{
|
||||||
|
total_bytes: total,
|
||||||
|
used_bytes: used,
|
||||||
|
available_bytes: available,
|
||||||
|
used_percent: total.positive? ? ((used.to_f / total) * 100).round(1) : 0.0
|
||||||
|
}
|
||||||
|
rescue StandardError
|
||||||
|
{ total_bytes: 0, used_bytes: 0, available_bytes: 0, used_percent: 0.0 }
|
||||||
|
end
|
||||||
|
|
||||||
|
def read_disk
|
||||||
|
{
|
||||||
|
root: disk_usage_for(ROOT_PATH),
|
||||||
|
recordings: disk_usage_for(RECORDINGS_PATH)
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def disk_usage_for(path)
|
||||||
|
return unavailable_disk unless path.present? && (Dir.exist?(path) || File.exist?(path))
|
||||||
|
|
||||||
|
stat = File.statvfs(path)
|
||||||
|
total = stat.blocks * stat.frsize
|
||||||
|
free = stat.bavail * stat.frsize
|
||||||
|
used = total - free
|
||||||
|
{
|
||||||
|
path: path,
|
||||||
|
total_bytes: total,
|
||||||
|
used_bytes: used,
|
||||||
|
free_bytes: free,
|
||||||
|
used_percent: total.positive? ? ((used.to_f / total) * 100).round(1) : 0.0,
|
||||||
|
dir_size_bytes: recordings_dir_size(path)
|
||||||
|
}
|
||||||
|
rescue StandardError
|
||||||
|
unavailable_disk
|
||||||
|
end
|
||||||
|
|
||||||
|
def recordings_dir_size(path)
|
||||||
|
return nil unless path == RECORDINGS_PATH && Dir.exist?(path)
|
||||||
|
|
||||||
|
`du -sb #{Shellwords.escape(path)} 2>/dev/null`.split.first.to_i
|
||||||
|
rescue StandardError
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
|
||||||
|
def unavailable_disk
|
||||||
|
{ path: nil, total_bytes: nil, used_bytes: nil, free_bytes: nil, used_percent: nil, dir_size_bytes: nil }
|
||||||
|
end
|
||||||
|
|
||||||
|
def read_network
|
||||||
|
rx, tx = parse_net_bytes
|
||||||
|
prev = MetricsStore.net_totals
|
||||||
|
MetricsStore.save_net_totals(rx: rx, tx: tx)
|
||||||
|
|
||||||
|
delta_rx = prev[:rx] ? [rx - prev[:rx], 0].max : 0
|
||||||
|
delta_tx = prev[:tx] ? [tx - prev[:tx], 0].max : 0
|
||||||
|
|
||||||
|
{
|
||||||
|
rx_bytes_total: rx,
|
||||||
|
tx_bytes_total: tx,
|
||||||
|
total_bytes: rx + tx
|
||||||
|
}
|
||||||
|
rescue StandardError
|
||||||
|
{ rx_bytes_total: 0, tx_bytes_total: 0, total_bytes: 0 }
|
||||||
|
end
|
||||||
|
|
||||||
|
def parse_net_bytes
|
||||||
|
rx = 0
|
||||||
|
tx = 0
|
||||||
|
File.read("/proc/net/dev").each_line.drop(2).each do |line|
|
||||||
|
iface = line.split(":").first.strip
|
||||||
|
next if iface == "lo"
|
||||||
|
|
||||||
|
cols = line.split(":").last.split.map(&:to_i)
|
||||||
|
rx += cols[0]
|
||||||
|
tx += cols[8]
|
||||||
|
end
|
||||||
|
[rx, tx]
|
||||||
|
end
|
||||||
|
|
||||||
|
def read_load_avg
|
||||||
|
loads = File.read("/proc/loadavg").split[0..2].map(&:to_f)
|
||||||
|
{ "1m" => loads[0], "5m" => loads[1], "15m" => loads[2] }
|
||||||
|
rescue StandardError
|
||||||
|
{ "1m" => 0.0, "5m" => 0.0, "15m" => 0.0 }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
42
backend/app/services/admin/metrics_store.rb
Normal file
42
backend/app/services/admin/metrics_store.rb
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
module Admin
|
||||||
|
class MetricsStore
|
||||||
|
HISTORY_KEY = "admin:metrics:history"
|
||||||
|
NET_RX_KEY = "admin:metrics:net_rx"
|
||||||
|
NET_TX_KEY = "admin:metrics:net_tx"
|
||||||
|
HISTORY_LIMIT = 90
|
||||||
|
|
||||||
|
class << self
|
||||||
|
def redis
|
||||||
|
@redis ||= Redis.new(url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0"))
|
||||||
|
rescue Redis::CannotConnectError
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
|
||||||
|
def push_sample(sample)
|
||||||
|
return unless redis
|
||||||
|
|
||||||
|
redis.lpush(HISTORY_KEY, sample.to_json)
|
||||||
|
redis.ltrim(HISTORY_KEY, 0, HISTORY_LIMIT - 1)
|
||||||
|
end
|
||||||
|
|
||||||
|
def history
|
||||||
|
return [] unless redis
|
||||||
|
|
||||||
|
redis.lrange(HISTORY_KEY, 0, HISTORY_LIMIT - 1).map { |row| JSON.parse(row) }.reverse
|
||||||
|
end
|
||||||
|
|
||||||
|
def net_totals
|
||||||
|
return { rx: nil, tx: nil } unless redis
|
||||||
|
|
||||||
|
{ rx: redis.get(NET_RX_KEY)&.to_i, tx: redis.get(NET_TX_KEY)&.to_i }
|
||||||
|
end
|
||||||
|
|
||||||
|
def save_net_totals(rx:, tx:)
|
||||||
|
return unless redis
|
||||||
|
|
||||||
|
redis.set(NET_RX_KEY, rx)
|
||||||
|
redis.set(NET_TX_KEY, tx)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
101
backend/app/services/billing/admin_comped_subscription.rb
Normal file
101
backend/app/services/billing/admin_comped_subscription.rb
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
module Billing
|
||||||
|
class AdminCompedSubscription
|
||||||
|
class Error < StandardError; end
|
||||||
|
|
||||||
|
VALID_PLANS = %w[premium_light premium_full].freeze
|
||||||
|
|
||||||
|
def self.grant(club:, plan_slug:, reason:, admin:)
|
||||||
|
new(club: club, plan_slug: plan_slug, reason: reason, admin: admin).grant
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.revoke(club:, admin:)
|
||||||
|
new(club: club, admin: admin).revoke
|
||||||
|
end
|
||||||
|
|
||||||
|
def initialize(club:, plan_slug: nil, reason: nil, admin: nil)
|
||||||
|
@club = club
|
||||||
|
@plan_slug = plan_slug.to_s.presence
|
||||||
|
@reason = reason.to_s.strip.presence
|
||||||
|
@admin = admin
|
||||||
|
end
|
||||||
|
|
||||||
|
def grant
|
||||||
|
raise Error, "Piano non valido" unless @plan_slug.in?(VALID_PLANS)
|
||||||
|
|
||||||
|
release_stripe_schedule!
|
||||||
|
|
||||||
|
AssignPlan.call(
|
||||||
|
club: @club,
|
||||||
|
plan_slug: @plan_slug,
|
||||||
|
status: "active",
|
||||||
|
stripe_attrs: comped_attrs.merge(
|
||||||
|
pending_plan_id: nil,
|
||||||
|
pending_billing_interval: nil,
|
||||||
|
stripe_schedule_id: nil,
|
||||||
|
cancel_at_period_end: false
|
||||||
|
)
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def revoke
|
||||||
|
sub = @club.subscription
|
||||||
|
raise Error, "Nessun abbonamento omaggio attivo" unless sub&.admin_comped?
|
||||||
|
|
||||||
|
if sub.stripe_subscription_id.present? && MatchLiveTv.stripe_enabled?
|
||||||
|
stripe_sub = ::Stripe::Subscription.retrieve(sub.stripe_subscription_id)
|
||||||
|
if stripe_sub.status.in?(%w[active trialing past_due])
|
||||||
|
Billing::Stripe::CheckoutSync.from_subscription(stripe_sub, club: @club)
|
||||||
|
clear_comped_flags!(sub.reload)
|
||||||
|
return sub
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
AssignPlan.call(
|
||||||
|
club: @club,
|
||||||
|
plan_slug: "free",
|
||||||
|
status: "active",
|
||||||
|
stripe_attrs: {
|
||||||
|
admin_comped: false,
|
||||||
|
admin_comped_reason: nil,
|
||||||
|
admin_comped_at: nil,
|
||||||
|
admin_comped_by_id: nil,
|
||||||
|
pending_plan_id: nil,
|
||||||
|
pending_billing_interval: nil,
|
||||||
|
stripe_schedule_id: nil
|
||||||
|
}
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def comped_attrs
|
||||||
|
{
|
||||||
|
admin_comped: true,
|
||||||
|
admin_comped_reason: @reason,
|
||||||
|
admin_comped_at: Time.current,
|
||||||
|
admin_comped_by_id: @admin&.id
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def clear_comped_flags!(sub)
|
||||||
|
sub.update!(
|
||||||
|
admin_comped: false,
|
||||||
|
admin_comped_reason: nil,
|
||||||
|
admin_comped_at: nil,
|
||||||
|
admin_comped_by_id: nil
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def release_stripe_schedule!
|
||||||
|
sub = @club.subscription
|
||||||
|
return if sub.blank? || sub.stripe_schedule_id.blank?
|
||||||
|
return unless MatchLiveTv.stripe_enabled?
|
||||||
|
|
||||||
|
::Stripe::SubscriptionSchedule.release(sub.stripe_schedule_id)
|
||||||
|
rescue ::Stripe::InvalidRequestError
|
||||||
|
nil
|
||||||
|
ensure
|
||||||
|
sub&.update!(stripe_schedule_id: nil, pending_plan_id: nil, pending_billing_interval: nil)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
module Billing
|
module Billing
|
||||||
class AssignPlan
|
class AssignPlan
|
||||||
def self.call(team:, plan_slug:, status: "active", stripe_attrs: {})
|
def self.call(club:, plan_slug:, status: "active", stripe_attrs: {})
|
||||||
plan = Plan[plan_slug]
|
plan = Plan[plan_slug]
|
||||||
sub = team.subscription || team.build_subscription
|
sub = club.subscription || club.build_subscription
|
||||||
attrs = { plan: plan, status: status }.merge(stripe_attrs.symbolize_keys)
|
attrs = { plan: plan, status: status }.merge(stripe_attrs.symbolize_keys)
|
||||||
sub.assign_attributes(attrs)
|
sub.assign_attributes(attrs)
|
||||||
sub.save!
|
sub.save!
|
||||||
|
|||||||
37
backend/app/services/billing/attach_payment_invoice.rb
Normal file
37
backend/app/services/billing/attach_payment_invoice.rb
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
module Billing
|
||||||
|
class AttachPaymentInvoice
|
||||||
|
class Error < StandardError; end
|
||||||
|
|
||||||
|
def self.call(payment:, pdf:)
|
||||||
|
new(payment: payment, pdf: pdf).call
|
||||||
|
end
|
||||||
|
|
||||||
|
def initialize(payment:, pdf:)
|
||||||
|
@payment = payment
|
||||||
|
@pdf = pdf
|
||||||
|
end
|
||||||
|
|
||||||
|
def call
|
||||||
|
raise Error, "Seleziona un file PDF" if @pdf.blank?
|
||||||
|
raise Error, "Pagamento non valido" unless @payment.status == "paid"
|
||||||
|
|
||||||
|
club = @payment.club
|
||||||
|
invoice = @payment.invoice || build_invoice!(club)
|
||||||
|
IssueInvoice.call(invoice: invoice, pdf: @pdf)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def build_invoice!(club)
|
||||||
|
club.billing_invoices.create!(
|
||||||
|
number: InvoiceNumber.next_for(club),
|
||||||
|
issued_on: @payment.paid_at&.to_date || Date.current,
|
||||||
|
amount_cents: @payment.amount_cents,
|
||||||
|
currency: @payment.currency.presence || "eur",
|
||||||
|
status: "draft",
|
||||||
|
source: "manual",
|
||||||
|
billing_payment: @payment
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
9
backend/app/services/billing/invoice_number.rb
Normal file
9
backend/app/services/billing/invoice_number.rb
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
module Billing
|
||||||
|
class InvoiceNumber
|
||||||
|
def self.next_for(club)
|
||||||
|
year = Date.current.year
|
||||||
|
count = club.billing_invoices.where("number LIKE ?", "%#{year}%").count + 1
|
||||||
|
"#{year}/#{count}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
47
backend/app/services/billing/issue_invoice.rb
Normal file
47
backend/app/services/billing/issue_invoice.rb
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
module Billing
|
||||||
|
class IssueInvoice
|
||||||
|
class Error < StandardError; end
|
||||||
|
|
||||||
|
def self.call(invoice:, pdf: nil)
|
||||||
|
new(invoice: invoice, pdf: pdf).call
|
||||||
|
end
|
||||||
|
|
||||||
|
def initialize(invoice:, pdf: nil)
|
||||||
|
@invoice = invoice
|
||||||
|
@pdf = pdf
|
||||||
|
end
|
||||||
|
|
||||||
|
def call
|
||||||
|
raise Error, "Carica il file PDF della fattura" if @pdf.blank? && !@invoice.pdf.attached?
|
||||||
|
|
||||||
|
attach_pdf!(@pdf) if @pdf.present?
|
||||||
|
raise Error, "PDF mancante" unless @invoice.pdf.attached?
|
||||||
|
|
||||||
|
recipient = @invoice.club.billing_email.presence
|
||||||
|
raise Error, "Email di fatturazione non configurata per la società" if recipient.blank?
|
||||||
|
|
||||||
|
@invoice.update!(status: "issued")
|
||||||
|
|
||||||
|
Billing::InvoiceMailer.with(invoice: @invoice).invoice_pdf.deliver_now
|
||||||
|
@invoice.update!(status: "sent", emailed_at: Time.current)
|
||||||
|
|
||||||
|
@invoice
|
||||||
|
end
|
||||||
|
|
||||||
|
def attach_pdf!(upload)
|
||||||
|
if upload.respond_to?(:tempfile)
|
||||||
|
@invoice.pdf.attach(
|
||||||
|
io: upload.tempfile,
|
||||||
|
filename: upload.original_filename,
|
||||||
|
content_type: upload.content_type.presence || "application/pdf"
|
||||||
|
)
|
||||||
|
elsif upload.is_a?(Hash)
|
||||||
|
@invoice.pdf.attach(**upload)
|
||||||
|
elsif upload.is_a?(StringIO)
|
||||||
|
@invoice.pdf.attach(io: upload, filename: "fattura.pdf", content_type: "application/pdf")
|
||||||
|
else
|
||||||
|
@invoice.pdf.attach(upload)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
129
backend/app/services/billing/payment_description.rb
Normal file
129
backend/app/services/billing/payment_description.rb
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
module Billing
|
||||||
|
# Etichette leggibili per lo storico pagamenti (mai testo grezzo Stripe / webhook).
|
||||||
|
class PaymentDescription
|
||||||
|
UGLY = /\A(webhook\s*test|test|x|—|-)\z/i
|
||||||
|
|
||||||
|
AMOUNT_HINTS = {
|
||||||
|
500 => %w[premium_light monthly],
|
||||||
|
4000 => %w[premium_light yearly],
|
||||||
|
2000 => %w[premium_full monthly],
|
||||||
|
20_000 => %w[premium_full yearly]
|
||||||
|
}.freeze
|
||||||
|
|
||||||
|
class << self
|
||||||
|
def for_stripe_invoice(invoice)
|
||||||
|
plan_slug, interval = extract_plan_and_interval(invoice)
|
||||||
|
build(plan_slug: plan_slug, interval: interval, amount_cents: invoice.amount_paid)
|
||||||
|
end
|
||||||
|
|
||||||
|
def for_payment(payment)
|
||||||
|
stored = payment.description.to_s.strip
|
||||||
|
return stored if stored.present? && !ugly?(stored)
|
||||||
|
|
||||||
|
build(
|
||||||
|
plan_slug: payment.plan_slug,
|
||||||
|
interval: nil,
|
||||||
|
amount_cents: payment.amount_cents
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def build(plan_slug:, interval:, amount_cents:)
|
||||||
|
plan_slug, interval = resolve_plan_interval(plan_slug, interval, amount_cents)
|
||||||
|
return plan_label(plan_slug, interval) if plan_slug.present?
|
||||||
|
|
||||||
|
if amount_cents.present? && amount_cents.to_i.positive?
|
||||||
|
euros = format("%.2f", amount_cents.to_i / 100.0)
|
||||||
|
return "Pagamento Match Live TV — #{euros} €"
|
||||||
|
end
|
||||||
|
|
||||||
|
"Abbonamento Match Live TV"
|
||||||
|
end
|
||||||
|
|
||||||
|
def resolve_plan_interval(plan_slug, interval, amount_cents)
|
||||||
|
plan_slug = plan_slug.presence
|
||||||
|
interval = interval.presence
|
||||||
|
|
||||||
|
if plan_slug.blank? && amount_cents.present?
|
||||||
|
hint = AMOUNT_HINTS[amount_cents.to_i]
|
||||||
|
plan_slug, interval = hint if hint
|
||||||
|
end
|
||||||
|
|
||||||
|
if plan_slug.present? && interval.blank? && amount_cents.present?
|
||||||
|
hint = AMOUNT_HINTS[amount_cents.to_i]
|
||||||
|
interval = hint&.last if hint&.first == plan_slug
|
||||||
|
end
|
||||||
|
|
||||||
|
interval ||= Billing::Stripe::PriceCatalog::DEFAULT_INTERVAL if plan_slug.present?
|
||||||
|
[plan_slug, interval]
|
||||||
|
end
|
||||||
|
|
||||||
|
def plan_label(plan_slug, interval)
|
||||||
|
plan = Plan[plan_slug]
|
||||||
|
price = Billing::Stripe::PriceCatalog.label(plan_slug: plan_slug, interval: interval)
|
||||||
|
"#{plan.name} — #{price}"
|
||||||
|
rescue KeyError
|
||||||
|
plan_slug.to_s.humanize
|
||||||
|
end
|
||||||
|
|
||||||
|
def extract_plan_and_interval(invoice)
|
||||||
|
meta = merged_metadata(invoice)
|
||||||
|
plan_slug = meta["plan_slug"].presence
|
||||||
|
interval = normalize_interval(meta["billing_interval"])
|
||||||
|
|
||||||
|
line = invoice.lines&.data&.first
|
||||||
|
if line
|
||||||
|
line_meta = line_metadata(line)
|
||||||
|
plan_slug ||= line_meta["plan_slug"]
|
||||||
|
interval ||= normalize_interval(line_meta["billing_interval"])
|
||||||
|
|
||||||
|
price_id = line_price_id(line)
|
||||||
|
from_price = Billing::Stripe::PriceCatalog.infer_from_price_id(price_id)
|
||||||
|
plan_slug ||= from_price&.first
|
||||||
|
interval ||= from_price&.last
|
||||||
|
end
|
||||||
|
|
||||||
|
plan_slug = normalize_plan_slug(plan_slug)
|
||||||
|
[plan_slug, interval]
|
||||||
|
end
|
||||||
|
|
||||||
|
def merged_metadata(invoice)
|
||||||
|
Billing::Stripe::InvoiceMetadata.merged(invoice)
|
||||||
|
end
|
||||||
|
|
||||||
|
def line_metadata(line)
|
||||||
|
meta = Billing::Stripe::InvoicePaymentRefs.safe_get(line, :metadata)
|
||||||
|
meta.to_h.stringify_keys
|
||||||
|
rescue NoMethodError
|
||||||
|
{}
|
||||||
|
end
|
||||||
|
|
||||||
|
def line_price_id(line)
|
||||||
|
pricing = Billing::Stripe::InvoicePaymentRefs.safe_get(line, :pricing)
|
||||||
|
details = Billing::Stripe::InvoicePaymentRefs.safe_get(pricing, :price_details)
|
||||||
|
Billing::Stripe::InvoicePaymentRefs.safe_get(details, :price)
|
||||||
|
end
|
||||||
|
|
||||||
|
def normalize_interval(value)
|
||||||
|
return nil if value.blank?
|
||||||
|
|
||||||
|
Billing::Stripe::PriceCatalog.normalize_interval(value)
|
||||||
|
rescue ArgumentError
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
|
||||||
|
def normalize_plan_slug(slug)
|
||||||
|
return nil if slug.blank?
|
||||||
|
|
||||||
|
slug = slug.to_s
|
||||||
|
slug = "premium_full" if slug == "premium"
|
||||||
|
slug.presence_in(%w[premium_light premium_full])
|
||||||
|
end
|
||||||
|
|
||||||
|
def ugly?(text)
|
||||||
|
UGLY.match?(text.to_s.strip)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
76
backend/app/services/billing/stripe/apply_pending_plan.rb
Normal file
76
backend/app/services/billing/stripe/apply_pending_plan.rb
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
module Billing
|
||||||
|
module Stripe
|
||||||
|
# Allinea piano locale quando scatta un downgrade programmato (o dopo sync Stripe).
|
||||||
|
class ApplyPendingPlan
|
||||||
|
def self.call(club:)
|
||||||
|
new(club: club).call
|
||||||
|
end
|
||||||
|
|
||||||
|
def initialize(club:)
|
||||||
|
@club = club
|
||||||
|
@sub = club.subscription
|
||||||
|
end
|
||||||
|
|
||||||
|
def call
|
||||||
|
return false unless @sub&.pending_plan_id.present?
|
||||||
|
|
||||||
|
pending_slug = @sub.pending_plan.slug
|
||||||
|
interval = @sub.pending_billing_interval.presence || @sub.billing_interval
|
||||||
|
|
||||||
|
if @sub.stripe_subscription_id.present?
|
||||||
|
stripe_sub = ::Stripe::Subscription.retrieve(@sub.stripe_subscription_id)
|
||||||
|
current_price_id = stripe_sub.items.data.first.price.id
|
||||||
|
expected_price_id = PriceCatalog.price_id(plan_slug: pending_slug, interval: interval)
|
||||||
|
return false unless current_price_id == expected_price_id
|
||||||
|
|
||||||
|
inferred = PriceCatalog.infer_from_price_id(current_price_id)
|
||||||
|
if inferred
|
||||||
|
pending_slug, interval = inferred
|
||||||
|
end
|
||||||
|
period_start, period_end = SubscriptionPeriod.times(stripe_sub)
|
||||||
|
Billing::AssignPlan.call(
|
||||||
|
club: @club,
|
||||||
|
plan_slug: pending_slug,
|
||||||
|
status: map_status(stripe_sub.status),
|
||||||
|
stripe_attrs: {
|
||||||
|
stripe_customer_id: stripe_sub.customer,
|
||||||
|
stripe_subscription_id: stripe_sub.id,
|
||||||
|
current_period_start: period_start,
|
||||||
|
current_period_end: period_end,
|
||||||
|
cancel_at_period_end: stripe_sub.cancel_at_period_end,
|
||||||
|
billing_interval: interval,
|
||||||
|
pending_plan_id: nil,
|
||||||
|
pending_billing_interval: nil,
|
||||||
|
stripe_schedule_id: nil
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Billing::AssignPlan.call(
|
||||||
|
club: @club,
|
||||||
|
plan_slug: pending_slug,
|
||||||
|
stripe_attrs: {
|
||||||
|
billing_interval: interval,
|
||||||
|
pending_plan_id: nil,
|
||||||
|
pending_billing_interval: nil,
|
||||||
|
stripe_schedule_id: nil
|
||||||
|
}
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
true
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def map_status(stripe_status)
|
||||||
|
case stripe_status
|
||||||
|
when "trialing" then "trialing"
|
||||||
|
when "active" then "active"
|
||||||
|
when "past_due", "unpaid" then "past_due"
|
||||||
|
when "canceled", "incomplete_expired" then "canceled"
|
||||||
|
else "incomplete"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
29
backend/app/services/billing/stripe/cancel_subscription.rb
Normal file
29
backend/app/services/billing/stripe/cancel_subscription.rb
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
module Billing
|
||||||
|
module Stripe
|
||||||
|
class CancelSubscription
|
||||||
|
def self.call(club:)
|
||||||
|
new(club: club).call
|
||||||
|
end
|
||||||
|
|
||||||
|
def initialize(club:)
|
||||||
|
@club = club
|
||||||
|
end
|
||||||
|
|
||||||
|
def call
|
||||||
|
raise "Stripe non configurato" unless MatchLiveTv.stripe_enabled?
|
||||||
|
|
||||||
|
sub = @club.subscription
|
||||||
|
raise "Nessun abbonamento premium attivo" unless sub&.premium? && sub.stripe_subscription_id.present?
|
||||||
|
raise "Disdetta già programmata" if sub.cancel_at_period_end?
|
||||||
|
|
||||||
|
stripe_sub = ::Stripe::Subscription.update(
|
||||||
|
sub.stripe_subscription_id,
|
||||||
|
cancel_at_period_end: true
|
||||||
|
)
|
||||||
|
|
||||||
|
CheckoutSync.from_subscription(stripe_sub, club: @club)
|
||||||
|
@club.subscription.reload
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
135
backend/app/services/billing/stripe/change_plan.rb
Normal file
135
backend/app/services/billing/stripe/change_plan.rb
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
module Billing
|
||||||
|
module Stripe
|
||||||
|
class ChangePlan
|
||||||
|
VALID_PLANS = CheckoutSession::VALID_PLANS.freeze
|
||||||
|
|
||||||
|
def self.call(club:, plan_slug:, interval: nil)
|
||||||
|
new(club: club, plan_slug: plan_slug, interval: interval).call
|
||||||
|
end
|
||||||
|
|
||||||
|
def initialize(club:, plan_slug:, interval: nil)
|
||||||
|
@club = club
|
||||||
|
@plan_slug = plan_slug.to_s
|
||||||
|
@interval = interval
|
||||||
|
@sub = club.subscription
|
||||||
|
end
|
||||||
|
|
||||||
|
def call
|
||||||
|
raise "Stripe non configurato" unless MatchLiveTv.stripe_enabled?
|
||||||
|
raise "Piano non valido" unless VALID_PLANS.include?(@plan_slug)
|
||||||
|
|
||||||
|
raise "Abbonamento omaggio: contatta il supporto per cambiare piano a pagamento" if @sub&.admin_comped?
|
||||||
|
raise "Nessun abbonamento Stripe attivo" if @sub.blank? || @sub.stripe_subscription_id.blank?
|
||||||
|
|
||||||
|
interval = resolve_interval(@sub)
|
||||||
|
if @sub.plan.slug == @plan_slug && @sub.billing_interval == interval && !@sub.pending_plan_id?
|
||||||
|
raise "Sei già su questo piano e intervallo di fatturazione"
|
||||||
|
end
|
||||||
|
|
||||||
|
kind = PlanChangeKind.classify(
|
||||||
|
from_plan_slug: @sub.plan.slug,
|
||||||
|
from_interval: @sub.billing_interval,
|
||||||
|
to_plan_slug: @plan_slug,
|
||||||
|
to_interval: interval
|
||||||
|
)
|
||||||
|
|
||||||
|
case kind
|
||||||
|
when :upgrade
|
||||||
|
perform_upgrade!(interval: interval)
|
||||||
|
when :downgrade
|
||||||
|
ScheduleDowngrade.call(club: @club, plan_slug: @plan_slug, interval: interval)
|
||||||
|
else
|
||||||
|
raise "Sei già su questo piano e intervallo di fatturazione"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def perform_upgrade!(interval:)
|
||||||
|
release_schedule_if_any!
|
||||||
|
|
||||||
|
price_id = PriceCatalog.price_id(plan_slug: @plan_slug, interval: interval)
|
||||||
|
stripe_sub = ::Stripe::Subscription.retrieve(@sub.stripe_subscription_id)
|
||||||
|
item_id = stripe_sub.items.data.first.id
|
||||||
|
|
||||||
|
updated = ::Stripe::Subscription.update(
|
||||||
|
stripe_sub.id,
|
||||||
|
items: [{ id: item_id, price: price_id }],
|
||||||
|
metadata: { club_id: @club.id, plan_slug: @plan_slug, billing_interval: interval },
|
||||||
|
proration_behavior: "always_invoice",
|
||||||
|
payment_behavior: "error_if_incomplete"
|
||||||
|
)
|
||||||
|
|
||||||
|
invoice = pay_open_subscription_invoice!(updated.id)
|
||||||
|
apply_local_plan!(updated, interval: interval)
|
||||||
|
|
||||||
|
ChangePlanResult.new(
|
||||||
|
kind: :upgrade,
|
||||||
|
plan_slug: @plan_slug,
|
||||||
|
interval: interval,
|
||||||
|
effective_at: Time.current,
|
||||||
|
amount_cents: invoice&.amount_paid,
|
||||||
|
currency: invoice&.currency,
|
||||||
|
invoice_id: invoice&.id
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def release_schedule_if_any!
|
||||||
|
return if @sub.stripe_schedule_id.blank?
|
||||||
|
|
||||||
|
::Stripe::SubscriptionSchedule.release(@sub.stripe_schedule_id)
|
||||||
|
rescue ::Stripe::InvalidRequestError
|
||||||
|
nil
|
||||||
|
ensure
|
||||||
|
@sub.update!(stripe_schedule_id: nil, pending_plan_id: nil, pending_billing_interval: nil)
|
||||||
|
end
|
||||||
|
|
||||||
|
def pay_open_subscription_invoice!(stripe_sub_id)
|
||||||
|
invoice = ::Stripe::Invoice.list(subscription: stripe_sub_id, status: "open", limit: 1).data.first
|
||||||
|
return nil unless invoice
|
||||||
|
|
||||||
|
paid = invoice.status == "paid" ? invoice : ::Stripe::Invoice.pay(invoice.id)
|
||||||
|
RecordPayment.call(stripe_invoice: paid, club: @club) if paid.status == "paid"
|
||||||
|
paid
|
||||||
|
rescue ::Stripe::CardError => e
|
||||||
|
raise ::Stripe::CardError, "Pagamento non riuscito: #{e.message}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def resolve_interval(sub)
|
||||||
|
return PriceCatalog.normalize_interval(@interval) if @interval.present?
|
||||||
|
|
||||||
|
sub.billing_interval.presence || PriceCatalog::DEFAULT_INTERVAL
|
||||||
|
end
|
||||||
|
|
||||||
|
def apply_local_plan!(stripe_sub, interval:)
|
||||||
|
period_start, period_end = SubscriptionPeriod.times(stripe_sub)
|
||||||
|
Billing::AssignPlan.call(
|
||||||
|
club: @club,
|
||||||
|
plan_slug: @plan_slug,
|
||||||
|
status: map_status(stripe_sub.status),
|
||||||
|
stripe_attrs: {
|
||||||
|
stripe_customer_id: stripe_sub.customer,
|
||||||
|
stripe_subscription_id: stripe_sub.id,
|
||||||
|
current_period_start: period_start,
|
||||||
|
current_period_end: period_end,
|
||||||
|
cancel_at_period_end: stripe_sub.cancel_at_period_end,
|
||||||
|
billing_interval: interval,
|
||||||
|
pending_plan_id: nil,
|
||||||
|
pending_billing_interval: nil,
|
||||||
|
stripe_schedule_id: nil
|
||||||
|
}
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def map_status(stripe_status)
|
||||||
|
case stripe_status
|
||||||
|
when "trialing" then "trialing"
|
||||||
|
when "active" then "active"
|
||||||
|
when "past_due", "unpaid" then "past_due"
|
||||||
|
when "canceled", "incomplete_expired" then "canceled"
|
||||||
|
else "incomplete"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user