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: t("admin.flash.invoice_upload_hint") 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: t("admin.flash.invoice_draft_created") 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: t("admin.flash.invoice_issued", number: @invoice.number, email: @club.billing_email) elsif @invoice.save redirect_to admin_billing_path(club_id: @club.id), notice: t("admin.flash.invoice_updated", number: @invoice.number) 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_action].to_s == "issue" 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