Rails 5 Prawn pdf show total table values - ruby-on-rails

In my view I have
<h4><%= number_to_currency #grand_total, precision: 0, unit: "EUR ", separator: "," %></h4>
This shows a correct total for a column. #grand_total is defined in my controller and it's the sum of total defined in model.
My model
class Ticketline < ActiveRecord::Base
belongs_to :ticket, :foreign_key => 'TICKET'
belongs_to :product, :foreign_key => 'PRODUCT'
def discount
(self.AMOUNT - self.TOTAL)
end
def total_amount
( pricesell = self.try(:PRICESELL) || 0
units = self.try(:UNITS) || 0
pricesell * units)
end
def total
(
price = self.try(:PRICE) || 0
units = self.UNITS || 0
price * units)
end
def consignor_cost
cost = product.location.try(:DISCOUNT_CONSIGNOR) || 0
cost ? (self.total * cost) : 0
end
def cost_of_goods_sold
cost = product.PRICEBUY || 0
cost ? (cost * self.TOTALUNITS) : 0
end
def gross_profit
(self.total - self.consignor_cost - self.cost_of_goods_sold)
end
class ProductSale < Ticketline
end
end
My controller
class ProductSalesController < TicketlinesController
def index
params.permit!
#q = Ticketline.joins(:product, :product => :location).group(:PRODUCT, :TICKET, :DISCOUNT_CONSIGNOR).select("PRODUCT, DISCOUNT_CONSIGNOR, UNITS, TICKET, SUM(ticketlines.PRICESELL*UNITS) AS AMOUNT, SUM(PRICE*UNITS) AS TOTAL, PRICE, UNITS, ticketlines.PRICESELL, SUM(UNITS) AS TOTALUNITS").ransack(params[:q])
#product_sales = #q.result.paginate(:page => params[:page], :per_page => 30)
#product_salesnp = #q.result
#amount_total = #q.result.map(&:total_amount).sum
#discount_total = #q.result.map(&:discount).sum
#grand_total = #q.result.map(&:total).sum
#consignor_cost_total = #q.result.map(&:consignor_cost).sum
#cost_of_goods_sold_total = #q.result.map(&:cost_of_goods_sold).sum
#gross_profit_total = #q.result.map(&:gross_profit).sum
respond_to do |format|
format.html
format.pdf do
pdf = SalesByProductPdf.new(#product_salesnp)
pdf.render_file "report.pdf"
send_data pdf.render, filename: 'report.pdf', type: 'application/pdf', disposition: 'inline'
end
end
end
end
On the pdf generated by prawn I want to show the same so I tried to enter on the corresponding pdf.rb file:
class SalesByProductPdf < Prawn::Document
include ActionView::Helpers::NumberHelper
def initialize(product_sales)
super()
#product_sales = product_sales
header
text_content
table_content
footer
end
def header
#something
end
def text_content
#something
end
def table_content
#something
end
def footer
text number_to_currency(grand_total, precision: 0, unit: "EUR ", separator: ",")
end
end
which gives me no error but shows no value.
What is the correct syntax?

You can explicitly include the ActionView::Helpers::NumberHelper module or whatever module you want in your prawn file.
Try passing in the #grand_total instance variable in your pdf file's initialize method:
class SalesByProductPdf < Prawn::Document
include ActionView::Helpers::NumberHelper
def initialize(product_salesnp, grand_total)
super()
#product_salesnp = product_salesnp
#grand_total = grand_total
header
text_content
table_content
footer
end
...
def footer
text number_to_currency(#grand_total, precision: 0, unit: "EUR ", separator: ",")
end
end
And pass in #grand_total in your controller too when you create a new Pdf object:
format.pdf do
pdf = SalesByProductPdf.new(#product_salesnp, #grand_total)
pdf.render_file "report.pdf"
send_data pdf.render, filename: 'report.pdf', type: 'application/pdf', disposition: 'inline'
end
Hopefully that should work..

Related

custom simple_form input date_flag

Trying to use f.input(:activated_at, as: :date_flag) to render as a checkbox, which sends down Time.now for true and nil for false.
https://github.com/postageapp/date_flag/blob/master/lib/date_flag.rb
https://raw.githubusercontent.com/heartcombo/simple_form/main/lib/simple_form/inputs/boolean_input.rb
# frozen_string_literal: true
class DateFlagInput < SimpleForm::Inputs::Base
def input(wrapper_options = {})
template.content_tag(:div, class: "form-check form-switch") do
template.concat(#builder.check_box(attribute_name, {class: 'form-check-input'}, Time.now, nil))
template.concat(template.label(attribute_name, label_text, {class: "form-check-label"}))
end
end
end
This code above gets me a bootstrap5 checkbox, which sends down the time, but cannot render a "checked".
I figured this out!
# frozen_string_literal: true
class DateFlagInput < SimpleForm::Inputs::BooleanInput
def input(wrapper_options = {})
flag_value = object.send(attribute_name)
# date_flag magic
input_html_options[:checked] = flag_value ? (flag_value <= Time.now) : false
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
merged_input_options[:class] = [input_html_classes]
template.content_tag(:div, class: container_class_name) do
build_hidden_field_for_checkbox +
build_check_box_without_hidden_field(merged_input_options) +
#builder.label(label_target, label_text, {class: boolean_label_class})
end
end
def label_translation
if SimpleForm.translate_labels && (translated_label = translate_from_namespace(:labels))
translated_label
elsif object.class.respond_to?(:human_attribute_name)
object.class.human_attribute_name(reflection_or_attribute_name.to_s.gsub(/_at$/, ''))
else
attribute_name.to_s.gsub(/_at$/, '').humanize.titleize
end
end
def container_class_name
"form-check"
end
def label(wrapper_options)
template.label_tag(nil, ' '.html_safe)
end
def input_html_classes
'form-check-input'
end
def boolean_label_class
"form-check-label"
end
def checked_value
Time.now
end
def unchecked_value
0
end
end
adding the checked: option to show how the checkbox should render.
the unchecked_value cannot be nil because nil does gets excluded from the params. using nil or 0 both worked for the unchecked_value!

How can I test these RSS parsing service objects?

I have some service objects that use Nokogiri to make AR instances. I created a rake task so that I can update the instances with a cron job. What I want to test is if it's adding items that weren't there before, ie:
Create an Importer with a url of spec/fixtures/feed.xml, feed.xml having 10 items.
Expect Show.count == 1 and Episode.count == 10
Edit spec/fixtures/feed.xml to have 11 items
Invoke rake task
Expect Show.count == 1 and Episode.count == 11
How could I test this in RSpec, or modify my code to be more testable?
# models/importer.rb
class Importer < ActiveRecord::Base
after_create :parse_importer
validates :title, presence: true
validates :url, presence: true
validates :feed_format, presence: true
private
def parse_importer
Parser.new(self)
end
end
# models/show.rb
class Show < ActiveRecord::Base
validates :title, presence: true
validates :title, uniqueness: true
has_many :episodes
attr_accessor :entries
end
# models/episode.rb
class Episode < ActiveRecord::Base
validates :title, presence: true
validates :title, uniqueness: true
belongs_to :show
end
#lib/tasks/admin.rake
namespace :admin do
desc "Checks all Importer URLs for new items."
task refresh: :environment do
#importers = Importer.all
#importers.each do |importer|
Parser.new(importer)
end
end
end
# services/parser.rb
class Parser
def initialize(importer)
feed = Feed.new(importer)
show = Show.where(rss_link: importer.url).first
if show # add new episodes
new_episodes = Itunes::Channel.refresh(feed.origin)
new_episodes.each do |new_episode|
show.episodes.create feed.episode(new_episode)
end
else # create a show and its episodes
new_show = Show.new(feed.show) if (feed && feed.show)
if (new_show.save && new_show.entries.any?)
new_show.entries.each do |entry|
new_show.episodes.create feed.episode(entry)
end
end
end
end
end
# services/feed.rb
class Feed
require "nokogiri"
require "open-uri"
require "formats/itunes"
attr_reader :params, :origin, :show, :episode
def initialize(params)
#params = params
end
def origin
#origin = Nokogiri::XML(open(params[:url]))
end
def format
#format = params[:feed_format]
end
def show
case format
when "iTunes"
Itunes::Channel.fresh(origin)
end
end
def episode(entry)
#entry = entry
case format
when "iTunes"
Itunes::Item.fresh(#entry)
end
end
end
# services/formats/itunes.rb
class Itunes
class Channel
def initialize(origin)
#origin = origin
end
def title
#origin.xpath("//channel/title").text
end
def description
#origin.xpath("//channel/description").text
end
def summary
#origin.xpath("//channel/*[name()='itunes:summary']").text
end
def subtitle
#origin.xpath("//channel/*[name()='itunes:subtitle']/text()").text
end
def rss_link
#origin.xpath("//channel/*[name()='atom:link']/#href").text
end
def main_link
#origin.xpath("//channel/link/text()").text
end
def docs_link
#origin.xpath("//channel/docs/text()").text
end
def release
#origin.xpath("//channel/pubDate/text()").text
end
def image
#origin.xpath("//channel/image/url/text()").text
end
def language
#origin.xpath("//channel/language/text()").text
end
def keywords
keywords_array(#origin)
end
def categories
category_array(#origin)
end
def explicit
explicit_check(#origin)
end
def entries
entry_array(#origin)
end
def self.fresh(origin)
#show = Itunes::Channel.new origin
return {
description: #show.description,
release: #show.release,
explicit: #show.explicit,
language: #show.language,
title: #show.title,
summary: #show.summary,
subtitle: #show.subtitle,
image: #show.image,
rss_link: #show.rss_link,
main_link: #show.main_link,
docs_link: #show.docs_link,
categories: #show.categories,
keywords: #show.keywords,
entries: #show.entries
}
end
def self.refresh(origin)
#show = Itunes::Channel.new origin
return #show.entries
end
private
def category_array(channel)
arr = []
channel.xpath("//channel/*[name()='itunes:category']/#text").each do |category|
arr.push(category.to_s)
end
return arr
end
def explicit_check(channel)
string = channel.xpath("//channel/*[name()='itunes:explicit']").text
if string === "yes" || string === "Yes"
true
else
false
end
end
def keywords_array(channel)
keywords = channel.xpath("//channel/*[name()='itunes:keywords']/text()").text
arr = keywords.split(",")
return arr
end
def entry_array(channel)
arr = []
channel.xpath("//item").each do |item|
arr.push(item)
end
return arr
end
end
class Item
def initialize(origin)
#origin = origin
end
def description
#origin.xpath("*[name()='itunes:subtitle']").text
end
def release
#origin.xpath("pubDate").text
end
def image
#origin.xpath("*[name()='itunes:image']/#href").text
end
def explicit
explicit_check(#origin)
end
def duration
#origin.xpath("*[name()='itunes:duration']").text
end
def title
#origin.xpath("title").text
end
def enclosure_url
#origin.xpath("enclosure/#url").text
end
def enclosure_length
#origin.xpath("enclosure/#length").text
end
def enclosure_type
#origin.xpath("enclosure/#type").text
end
def keywords
keywords_array(#origin.xpath("*[name()='itunes:keywords']").text)
end
def self.fresh(entry)
#episode = Itunes::Item.new entry
return {
description: #episode.description,
release: #episode.release,
image: #episode.image,
explicit: #episode.explicit,
duration: #episode.duration,
title: #episode.title,
enclosure_url: #episode.enclosure_url,
enclosure_length: #episode.enclosure_length,
enclosure_type: #episode.enclosure_type,
keywords: #episode.keywords
}
end
private
def explicit_check(item)
string = item.xpath("*[name()='itunes:explicit']").text
if string === "yes" || string === "Yes"
true
else
false
end
end
def keywords_array(item)
keywords = item.split(",")
return keywords
end
end
end
Before anything else, good for you for using service objects! I've been using this approach a great deal and find POROs preferable to fat models in many situations.
It appears the behavior you're interested in testing is contained in Parser.initialize.
First, I'd create a class method for Parser called parse. IMO, Parser.parse(importer) is clearer about what Parser is doing than is Parser.new(importer). So, it might look like:
#services/parser.rb
class Parser
class << self
def parse(importer)
#importer = importer
#feed = Feed.new(importer)
if #show = Show.where(rss_link: importer.url).first
create_new_episodes Itunes::Channel.refresh(#feed.origin)
else
create_show_and_episodes
end
end # parse
end
end
Then add the create_new_episodes and create_show_and_episodes class methods.
#services/parser.rb
class Parser
class << self
def parse(importer)
#importer = importer
#feed = Feed.new(importer)
if #show = Show.where(rss_link: #importer.url).first
create_new_episodes Itunes::Channel.refresh(#feed.origin)
else
create_show_and_episodes
end
end # parse
def create_new_episodes(new_episodes)
new_episodes.each do |new_episode|
#show.episodes.create #feed.episode(new_episode)
end
end # create_new_episodes
def create_show_and_episodes
new_show = Show.new(#feed.show) if (#feed && #feed.show)
if (new_show.save && new_show.entries.any?)
new_show.entries.each do |entry|
new_show.episodes.create #feed.episode(entry)
end
end
end # create_show_and_episodes
end
end
Now you have a Parser.create_new_episodes method that you can test independently. So, your test might look something like:
require 'rspec_helper'
describe Parser do
describe '.create_new_episodes' do
context 'when an initial parse has been completed' do
before(:each) do
first_file = Nokogiri::XML(open('spec/fixtures/feed_1.xml'))
#second_file = Nokogiri::XML(open('spec/fixtures/feed_2.xml'))
Parser.create_show_and_episodes first_file
end
it 'changes Episodes.count by 1' do
expect{Parser.create_new_episodes(#second_file)}.to change{Episodes.count}.by(1)
end
it 'changes Show.count by 0' do
expect{Parser.create_new_episodes(#second_file)}.to change{Show.count}.by(0)
end
end
end
end
Naturally, you'll need feed_1.xml and feed_2.xml in the spec\fixtures directory.
Apologies for any typos. And, I didn't run the code. So, might be buggy. Hope it helps.

download report/invoice as pdf format using payday gemfile in rails

My code is
class pdfController < ApplicationController
def index
#posts = Post.all
respond_to do |format|
format.html
format.pdf do
pdf = Prawn::Document.new
send_data pdf.render, :filename => "report.pdf", :type => "application/pdf", :disposition => "inline"
end
end
end
end
Now the problem is, pdf file downloaded. But I am getting an empty file, there is no report in that downloaded file.
And the code#posts = Post.all Post is a table, I can get the data from Post to downloaded pdf file.
As suggested in this post: http://adamalbrecht.com/2014/01/14/generate-clean-testable-pdf-reports-in-rails-with-prawn/
You can inherit Prawn::Document class for an easy configuration of your table border color and font size.
class PdfReport < Prawn::Document
# Often-Used Constants
TABLE_ROW_COLORS = ["FFFFFF","DDDDDD"]
TABLE_FONT_SIZE = 9
TABLE_BORDER_STYLE = :grid
def initialize(default_prawn_options={})
super(default_prawn_options)
font_size 10
end
def header(title=nil)
text "My Awesome Invoice!!", size: 18, style: :bold, align: :center
if title
text title, size: 14, style: :bold_italic, align: :center
end
end
def footer
# ...
end
# ... More helpers
end
Now, the above class is handful to use at other places by inheriting to some other classes, for example: posts reports, comments reports, etc. For your posts reports, We could do something like this:
class PostSummaryReportPdf < PdfReport
TABLE_WIDTHS = [20, 100, 30, 60]
TABLE_HEADERS = ["ID", "Name", "Date", "User"]
def initialize(posts=[])
super()
#posts = posts
header "Posts' Invoice Summary Report"
display_event_table
footer
end
private
def display_event_table
if table_data.empty?
text "No Events Found"
else
table table_data,
headers: TABLE_HEADERS,
column_widths: TABLE_WIDTHS,
row_colors: TABLE_ROW_COLORS,
font_size: TABLE_FONT_SIZE
end
end
def table_data
#table_data ||= #posts.map { |p| [p.id, p.name, p.created_at.strftime("%m/%d/%y"), p.created_by.try(:full_name)] }
end
end
Everything is now up and ready to be used in DRY-way within your controllers.
class pdfController < ApplicationController
def index
#posts = Post.all
respond_to do |format|
format.html
format.pdf do
pdf = PostSummaryReportPdf.new(#posts)
send_data pdf.render, :filename => "report.pdf", :type => "application/pdf", :disposition => "inline"
end
end
end
end
I hope that helps.

How to access an instance variable from a do block?

The following code does not work. It says undefined method 'table_name' for nil:NilClass
#members = Members.all
table member_list_rows do
if #members.table_name == members
row(0).background_color = '3498db'
end
end
Full code
class MemberPdf < Prawn::Document
def initialize(members, view, allcount)
super(top_margin: 50)
if members.size != allcount
#warn = " (Not all members)"
else
#all = " All"
end
text "Showing#{#all} #{members.size} Members", size: 18, style: :bold, align: :center, color: "636363"
text "#{#warn}", size: 11, align: :center, color: "858585"
#members = members
#view = view
member_list
end
def member_list
move_down 20
table member_list_rows do
self.row(0).align = :center
if #members.table_name == "members"
row(0).background_color = '3498db'
else
end
row(0).text_color = "FFFFFF"
self.row_colors = ["DDDDDD", "FFFFFF"]
self.header = true
#self.cell.text_color = "B3B3B3"
row(0).columns(0).style size: 20
end
end
def member_list_rows
[["Name", "Awardunit", "Address", "Contact", "Level of Entry", "Current Award", "Disabled?" ]] +
#members.map do |member|
[member.name, member.awardunit.name, member.address, member.name, member.entrylvl, member.currentaward, #view.yesno(member.disabled)]
end
end
end
Members controller
if params[:commit] == "Clear"
params[:q] = nil
end
respond_to do |format|
format.html
format.pdf do
pdf = MemberPdf.new(Member.search(params[:q]).result.order( 'name ASC' ), view_context, Member.all.size)
send_data pdf.render, filename: "Members_List.pdf", type: "application/pdf", disposition: "inline"
end
end
It is due to #members is nil.You are doing it wrong.
Change this
#members = Members.all #Wrong
to
#members = Member.all #Right
Always remember,the Model name should be singular.
Those are called Naming Conventions. For more information,read these Style guides(Ruby and Rails)
Most likely table method is changing context, in which you don't have access to the #members instance variable anymore. This can be achieved easily by this sample code:
def do_stuff(&block)
cls = Class.new
cls.instance_eval(&block)
end
#test_var = "test_var"
do_stuff { puts #test_var }
You will receive nothing, because #test_var does not exist in the cls.
Am not sure what you are doing with "table member_list_rows". Didn't get that.
In the third line though, it should be
if #members.table_name == "members"

Prevent ActionMailer to strip repeating spaces in plain message

I'm trying to have an table in text mail, so I write some helpers:
module MailerHelper
def field_width(text, width)
' ' * (width - text.length) + text
end
def cell(text, width)
output = '| ' + field_width(text, width-2) + " |\n"
output << '+-' + '-'*(width-2) + '-+'
end
end
Then in view I write it like this:
<%= cell 'Test', 10 %>
But that what I get (according to letter_opener) is:
| Test |
+----------+
As can you see, the spaces that are repeating before Test. My question is how to prevent ActionMailer (or anything else what is destroying my beautiful table) from doing that.
Mailer code:
def remind(client, invoices)
#client = client
#company = #client.company
#invoices = invoices.to_a
days_left = #invoices.first.pay_date - Date.today
message = #client.group.messages.find_by_period days_left.to_i
raise 'No messages for this invoices.' if message.nil?
#template = message.template || if days_left < 0
t 'message.before'
elsif days_left > 0
t 'message.after'
else
t 'message.today'
end
#text = liquid_parse #template
#html = markdown_parse #text
mail(:to => #client.email, :subject => t('message.title'))
end
private
def markdown_parse(text)
markdown = Redcarpet::Markdown.new Redcarpet::Render::HTML,
:autolink => true, :space_after_headers => true
markdown.render text
end
def liquid_parse(text)
renderer = Liquid::Template.parse text
renderer.render 'company' => #company, 'invoice' => #invoice, 'client' => #client
end
I've found bug. It was caused by Premailer what I use to inline CSS in HTML part.
class InlineCSSInterceptor
def self.delivering_email(message)
#message.text_part.body = Premailer.new(message.text_part.body.to_s, with_html_string: true).to_plain_text # this is line causing the problem.
message.html_part.body = Premailer.new(message.html_part.body.to_s, with_html_string: true).to_inline_css
end
end
Mailer.register_interceptor InlineCSSInterceptor

Resources