Remove code duplication and test PDF creation

This commit is contained in:
Maikel Linke
2019-02-06 14:07:13 +11:00
parent 7c5b430a37
commit d97fa60c31
4 changed files with 47 additions and 21 deletions

View File

@@ -37,9 +37,7 @@ Spree::Admin::OrdersController.class_eval do
end
def invoice
pdf = render_to_string pdf: "invoice-#{@order.number}.pdf",
template: invoice_template,
formats: [:html], encoding: "UTF-8"
pdf = InvoiceRenderer.new.render(@order)
Spree::OrderMailer.invoice_email(@order.id, pdf).deliver
flash[:success] = t('admin.orders.invoice_email_sent')
@@ -48,7 +46,7 @@ Spree::Admin::OrdersController.class_eval do
end
def print
render pdf: "invoice-#{@order.number}", template: invoice_template, encoding: "UTF-8"
render InvoiceRenderer.new.args(@order)
end
def print_ticket
@@ -61,10 +59,6 @@ Spree::Admin::OrdersController.class_eval do
private
def invoice_template
Spree::Config.invoice_style2? ? "spree/admin/orders/invoice2" : "spree/admin/orders/invoice"
end
def require_distributor_abn
unless @order.distributor.abn.present?
flash[:error] = t(:must_have_valid_business_number, enterprise_name: @order.distributor.name)

View File

@@ -1,5 +1,4 @@
class BulkInvoiceService
include WickedPdf::PdfHelper
attr_reader :id
def initialize
@@ -11,10 +10,7 @@ class BulkInvoiceService
orders = Spree::Order.where(id: order_ids)
orders.each do |order|
invoice = renderer.render_to_string pdf: "invoice-#{order.number}.pdf",
template: invoice_template,
formats: [:html], encoding: "UTF-8",
locals: { :@order => order }
invoice = InvoiceRenderer.new.render_to_string(order)
pdf << CombinePDF.parse(invoice)
end
@@ -41,14 +37,6 @@ class BulkInvoiceService
'tmp/invoices'
end
def renderer
ApplicationController.new
end
def invoice_template
Spree::Config.invoice_style2? ? "spree/admin/orders/invoice2" : "spree/admin/orders/invoice"
end
def file_directory
Dir.mkdir(directory) unless File.exist?(directory)
directory

View File

@@ -0,0 +1,29 @@
class InvoiceRenderer
def render_to_string(order)
renderer.render_to_string(args(order))
end
def args(order)
{
pdf: "invoice-#{order.number}.pdf",
template: invoice_template,
formats: [:html],
encoding: "UTF-8",
locals: { :@order => order }
}
end
private
def renderer
ApplicationController.new
end
def invoice_template
if Spree::Config.invoice_style2?
"spree/admin/orders/invoice2"
else
"spree/admin/orders/invoice"
end
end
end

View File

@@ -0,0 +1,15 @@
require 'spec_helper'
describe InvoiceRenderer do
let(:service) { described_class.new }
it "creates a PDF invoice" do
order = create(:completed_order_with_fees)
order.bill_address = order.ship_address
order.save!
result = service.render_to_string(order)
expect(result).to match /^%PDF/
end
end