Refactor: Introduce PdfServiceBase for shared PDF fetching functionality and update Invoice/Estimate controllers to utilize new services

This commit is contained in:
2026-02-28 21:59:01 -05:00
parent a34ae46358
commit f921f227e2
5 changed files with 90 additions and 49 deletions

View File

@@ -65,7 +65,8 @@ class EstimateController < ApplicationController
# Renders the estimate PDF or redirects with an error if rendering fails. # Renders the estimate PDF or redirects with an error if rendering fails.
def render_pdf(estimate) def render_pdf(estimate)
send_data( estimate.pdf, filename: "estimate #{estimate.doc_number}.pdf", disposition: :inline, type: "application/pdf" ) pdf, ref = EstimatePdfService.new(qbo: Qbo.first).fetch_pdf(doc_ids: [estimate.id])
send_data( pdf, filename: "estimate #{ref}.pdf", disposition: :inline, type: "application/pdf" )
rescue StandardError => e rescue StandardError => e
log "PDF render failed for Estimate #{estimate&.id}: #{e.message}" log "PDF render failed for Estimate #{estimate&.id}: #{e.message}"
redirect_back fallback_location: root_path, flash: { error: I18n.t(:notice_estimate_not_found) } redirect_back fallback_location: root_path, flash: { error: I18n.t(:notice_estimate_not_found) }

View File

@@ -13,11 +13,12 @@ class InvoiceController < ApplicationController
before_action :require_user, unless: -> { session[:token].nil? } before_action :require_user, unless: -> { session[:token].nil? }
skip_before_action :verify_authenticity_token, :check_if_login_required, unless: -> { session[:token].nil? } skip_before_action :verify_authenticity_token, :check_if_login_required, unless: -> { session[:token].nil? }
# Displays the invoice PDF in the browser or redirects with an error if not found.
def show def show
log "Processing request for #{request.original_url}" log "Processing request for #{request.original_url}"
invoice_ids = Array(params[:invoice_ids] || params[:id]) invoice_ids = Array(params[:invoice_ids] || params[:id])
pdf, ref = InvoicePdfService.new(qbo: Qbo.first) .fetch_pdf(invoice_ids: invoice_ids) pdf, ref = InvoicePdfService.new(qbo: Qbo.first).fetch_pdf(doc_ids: invoice_ids)
send_data pdf, filename: "invoice #{ref}.pdf", disposition: :inline, type: "application/pdf" send_data pdf, filename: "invoice #{ref}.pdf", disposition: :inline, type: "application/pdf"
@@ -28,6 +29,7 @@ class InvoiceController < ApplicationController
private private
# Logs messages with a consistent prefix for easier debugging.
def log(msg) def log(msg)
Rails.logger.info "[InvoiceController] #{msg}" Rails.logger.info "[InvoiceController] #{msg}"
end end

View File

@@ -0,0 +1,16 @@
#The MIT License (MIT)
#
#Copyright (c) 2016 - 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class EstimatePdfService < PdfServiceBase
def self.model_class
Estimate
end
end

View File

@@ -7,54 +7,10 @@
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. #The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# #
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class InvoicePdfService class InvoicePdfService < PdfServiceBase
require 'combine_pdf'
def initialize(qbo:) def self.model_class
@qbo = qbo Invoice
end end
# Fetches the PDF for the given invoice IDs. If multiple IDs are provided, their PDFs are combined into a single document.
def fetch_pdf(invoice_ids:)
log "Fetching PDFs for invoice IDs: #{invoice_ids.join(', ')}"
@qbo.perform_authenticated_request do |access_token|
service = Quickbooks::Service::Invoice.new(
company_id: @qbo.realm_id,
access_token: access_token
)
return single_pdf(service, invoice_ids.first) if invoice_ids.size == 1
combined_pdf(service, invoice_ids)
end
end
private
# Fetches a single PDF for the given invoice ID.
def single_pdf(service, id)
log "Fetching PDF for invoice ID: #{id}"
invoice = service.fetch_by_id(id)
[service.pdf(invoice), invoice.doc_number]
end
# Combines PDFs for multiple invoice IDs into a single PDF document and returns it along with a reference string.
def combined_pdf(service, ids)
log "Combining PDFs for invoice IDs: #{ids.join(', ')}"
pdf = CombinePDF.new
ref = []
ids.each do |id|
invoice = service.fetch_by_id(id)
ref << invoice.doc_number
pdf << CombinePDF.parse(service.pdf(invoice))
end
[pdf.to_pdf, ref.join(" ")]
end
def log(msg)
Rails.logger.info "[InvoicePdfService] #{msg}"
end
end end

View File

@@ -0,0 +1,66 @@
#The MIT License (MIT)
#
#Copyright (c) 2016 - 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class PdfServiceBase
require 'combine_pdf'
# Subclasses should initialize with a QBO client instance
def initialize(qbo:)
@qbo = qbo
@entity = self.class.model_class
end
# Subclasses must implement this to specify which document model to download pdf (e.g. Estimate, Invoice)
def self.model_class
raise NotImplementedError
end
# Fetches the PDF for the given entity IDs. If multiple IDs are provided, their PDFs are combined into a single document.
def fetch_pdf(doc_ids:)
log "Fetching PDFs for #{@entity} IDs: #{doc_ids.join(', ')}"
@qbo.perform_authenticated_request do |access_token|
service_class = "Quickbooks::Service::#{@entity.name}".constantize
service = service_class.new(company_id: @qbo.realm_id, access_token: access_token)
return single_pdf(service, doc_ids.first) if doc_ids.size == 1
combined_pdf(service, doc_ids)
end
end
private
# Fetches a single PDF for the given invoice ID.
def single_pdf(service, id)
log "Fetching PDF for #{@entity} ID: #{id}"
entity = service.fetch_by_id(id)
[service.pdf(entity), entity.doc_number]
end
# Combines PDFs for multiple entity IDs into a single PDF document and returns it along with a reference string.
def combined_pdf(service, ids)
log "Combining PDFs for #{@entity} IDs: #{ids.join(', ')}"
pdf = CombinePDF.new
ref = []
ids.each do |id|
entity = service.fetch_by_id(id)
ref << entity.doc_number
pdf << CombinePDF.parse(service.pdf(entity))
end
[pdf.to_pdf, ref.join(" ")]
end
# Logs messages with a consistent prefix for easier debugging.
def log(msg)
Rails.logger.info "[#{@entity}PdfService] #{msg}"
end
end