module Admin class BillingInvoicesController < BaseController before_action :set_club before_action :set_invoice, only: %i[edit update] def index @payments = @club.billing_payments.recent.includes(:invoice) @invoices = @club.billing_invoices.recent.includes(:billing_payment, pdf_attachment: :blob) end def new @payment = @club.billing_payments.find_by(id: params[:billing_payment_id]) if params[:billing_payment_id].present? if @payment&.invoice.present? redirect_to edit_admin_club_billing_invoice_path(@club, @payment.invoice), alert: "Esiste giĆ  una fattura per questo pagamento." return end @invoice = @club.billing_invoices.build( issued_on: Date.current, currency: "eur", source: "manual", status: "draft", billing_payment: @payment, amount_cents: @payment&.amount_cents, number: suggested_invoice_number ) 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 fattura #{@invoice.number} creata. Carica il PDF e invia al cliente." 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_club_billing_invoices_path(@club), notice: "Fattura #{@invoice.number} emessa e inviata a #{@club.billing_email}." elsif @invoice.save redirect_to admin_club_billing_invoices_path(@club), 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 suggested_invoice_number year = Date.current.year count = @club.billing_invoices.where("number LIKE ?", "%#{year}%").count + 1 "#{year}/#{count}" 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