# Background job to create Stripe invoices for accounting records # # This job is responsible for creating post-payment invoices in Stripe # for accounting purposes after a successful payment class StripeInvoiceGenerationJob < ApplicationJob queue_as :default # Retry up to 3 times with exponential backoff retry_on StandardError, wait: :exponentially_longer, attempts: 3 # Don't retry on Stripe authentication errors discard_on Stripe::AuthenticationError def perform(order_id) order = Order.find(order_id) unless order.status == "paid" Rails.logger.warn "Attempted to create invoice for unpaid order #{order_id}" return end # Create the Stripe invoice service = StripeInvoiceService.new(order) stripe_invoice = service.create_post_payment_invoice if stripe_invoice # Store the invoice ID (you might want to persist this in the database) order.instance_variable_set(:@stripe_invoice_id, stripe_invoice.id) Rails.logger.info "Successfully created Stripe invoice #{stripe_invoice.id} for order #{order.id} via background job" # Optionally send notification email about invoice availability # InvoiceMailer.invoice_ready(order, stripe_invoice.id).deliver_now else error_msg = service.errors.join(", ") Rails.logger.error "Failed to create Stripe invoice for order #{order.id}: #{error_msg}" raise StandardError, "Invoice generation failed: #{error_msg}" end rescue ActiveRecord::RecordNotFound Rails.logger.error "Order #{order_id} not found for invoice generation" rescue Stripe::StripeError => e Rails.logger.error "Stripe error creating invoice for order #{order_id}: #{e.message}" raise e # Re-raise to trigger retry logic rescue => e Rails.logger.error "Unexpected error creating invoice for order #{order_id}: #{e.message}" raise e # Re-raise to trigger retry logic end end