pdfshop/app/services/order_to_pdf.rb

65 lines
2.2 KiB
Ruby

# Creates PDF for order
class OrderToPdf
def initialize(order)
@order = order
end
def call
order_to_pdf
end
def path_to_file
"#{Rails.root}/storage/pdfs/zamowienie_#{order.beauty_id}.pdf"
end
def file_name
"zamowienie_#{order.beauty_id}.pdf"
end
private
attr_reader :order
def order_to_html_string
ret = "<html><head><meta charset='utf-8' /><style>body{font-family: "\
'Verdana, Geneva, sans-serif;}tr.border_bottom td {'\
'border-bottom:1pt solid black;}</style></head><body><h2>Zamówienie: '\
"#{order.beauty_id}</h2><br />"\
'<table width="100%"><thead>'\
'<tr><th>Produkt</th><th>'\
'Cena jednostkowa</th><th>Ilość</th><th>Suma</th></tr></thead><tbody>'
order.order_products.each do |op|
ret += "<tr class='border_bottom'><td><strong>#{op.product.name}</strong"\
"></td><td style='text-align:center;'>PLN #{format('%.2f', op.price)}<"\
"/td><td style='text-align:center;'>#{op.quantity}</td><td style='text"\
"-align:right;'>PLN #{format('%.2f', op.multiple_price)}</td></tr>"
end
ret += '</tbody><tfoot>'\
'<tr style="text-align:right;"><td colspan="3">Towar</td>'\
"<td>PLN #{format('%.2f', @order.order_value)}</td></tr>"\
'<tr style="text-align:right;"><td colspan="3">Wysyłka</td>'\
"<td >PLN #{format('%.2f', @order.shipping.price)}</td></tr>"\
'<tr style="text-align:right; font-weight:bold;">'\
'<td colspan="3">Razem do zapłaty</td>'\
"<td>PLN #{format('%.2f', @order.order_summary)}</td></tr></tfoot>"\
"</table><br/><h3>Adres dostawy</h3> <br/>#{order.full_name}<br/>"\
"#{order.address.gsub(/(\r\n|\n\r|\r|\n)/, '<br \>')}"\
'<br/><h3>Wiadomość od klienta:</h3>'\
"#{order.message_from_client.gsub(/(\r\n|\n\r|\r|\n)/, '<br \>')}"\
'</body></html>'
ret
end
def order_to_pdf
pdf = WickedPdf.new.pdf_from_string(order_to_html_string)
save_path = "#{Rails.root}/storage/pdfs"
FileUtils.mkdir_p save_path
file_name = "zamowienie_#{order.beauty_id}.pdf"
save_path += "/#{file_name}"
File.open(save_path, 'wb') do |file|
file << pdf
end
pdf
end
end