1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-18 07:52:23 +01:00

refactored invoice pdf generation script

This commit is contained in:
Sylvain 2019-02-26 16:11:37 +01:00
parent 1c8e82df14
commit a2ce0c3753

View File

@ -1,12 +1,13 @@
module PDF # frozen_string_literal: true
class Invoice < Prawn::Document # Generate a downloadable PDF file for the recorded invoice
class PDF::Invoice < Prawn::Document
require 'stringio' require 'stringio'
include ActionView::Helpers::NumberHelper include ActionView::Helpers::NumberHelper
include ApplicationHelper include ApplicationHelper
def initialize(invoice, subscription_expiration_date) def initialize(invoice, subscription_expiration_date)
super(:margin => 70) super(margin: 70)
# fonts # fonts
opensans = Rails.root.join('vendor/assets/fonts/OpenSans-Regular.ttf').to_s opensans = Rails.root.join('vendor/assets/fonts/OpenSans-Regular.ttf').to_s
@ -16,38 +17,38 @@ module PDF
font_families.update( font_families.update(
'Open-Sans' => { 'Open-Sans' => {
:normal => {:file => opensans, :font => 'Open-Sans'}, normal: { file: opensans, font: 'Open-Sans' },
:bold => {:file => opensans_bold, :font => 'Open-Sans-Bold'}, bold: { file: opensans_bold, font: 'Open-Sans-Bold' },
:italic => {:file => opensans_italic, :font => 'Open-Sans-Oblique'}, italic: { file: opensans_italic, font: 'Open-Sans-Oblique' },
:bold_italic => {:file => opensans_bolditalic, :font => 'Open-Sans-BoldOblique'} bold_italic: { file: opensans_bolditalic, font: 'Open-Sans-BoldOblique' }
} }
) )
# logo # logo
img_b64 = Setting.find_by({name: 'invoice_logo'}) img_b64 = Setting.find_by(name: 'invoice_logo')
image StringIO.new( Base64.decode64(img_b64.value) ), :fit => [415,40] image StringIO.new(Base64.decode64(img_b64.value)), fit: [415, 40]
move_down 20 move_down 20
font('Open-Sans', :size => 10) do font('Open-Sans', size: 10) do
# general information # general information
if invoice.is_a?(Avoir) if invoice.is_a?(Avoir)
text I18n.t('invoices.refund_invoice_reference', REF:invoice.reference), :leading => 3 text I18n.t('invoices.refund_invoice_reference', REF: invoice.reference), leading: 3
else else
text I18n.t('invoices.invoice_reference', REF:invoice.reference), :leading => 3 text I18n.t('invoices.invoice_reference', REF: invoice.reference), leading: 3
end end
if Setting.find_by({name: 'invoice_code-active'}).value == 'true' if Setting.find_by(name: 'invoice_code-active').value == 'true'
text I18n.t('invoices.code', CODE:Setting.find_by({name: 'invoice_code-value'}).value), :leading => 3 text I18n.t('invoices.code', CODE: Setting.find_by(name: 'invoice_code-value').value), leading: 3
end end
if invoice.invoiced_type != WalletTransaction.name if invoice.invoiced_type != WalletTransaction.name
if invoice.is_a?(Avoir) if invoice.is_a?(Avoir)
text I18n.t('invoices.order_number', NUMBER:invoice.invoice.order_number), :leading => 3 text I18n.t('invoices.order_number', NUMBER: invoice.invoice.order_number), leading: 3
else else
text I18n.t('invoices.order_number', NUMBER:invoice.order_number), :leading => 3 text I18n.t('invoices.order_number', NUMBER: invoice.order_number), leading: 3
end end
end end
if invoice.is_a?(Avoir) if invoice.is_a?(Avoir)
text I18n.t('invoices.refund_invoice_issued_on_DATE', DATE:I18n.l(invoice.avoir_date.to_date)) text I18n.t('invoices.refund_invoice_issued_on_DATE', DATE: I18n.l(invoice.avoir_date.to_date))
else else
text I18n.t('invoices.invoice_issued_on_DATE', DATE:I18n.l(invoice.created_at.to_date)) text I18n.t('invoices.invoice_issued_on_DATE', DATE: I18n.l(invoice.created_at.to_date))
end end
# user/organization's information # user/organization's information
@ -59,36 +60,43 @@ module PDF
full_name = name full_name = name
end end
if invoice&.user&.profile&.organization&.address address = if invoice&.user&.profile&.organization&.address
address = invoice.user.profile.organization.address.address invoice.user.profile.organization.address.address
elsif invoice&.user&.profile&.address elsif invoice&.user&.profile&.address
address = invoice.user.profile.address.address invoice.user.profile.address.address
else else
address = '' ''
end end
text_box "<b>#{name}</b>\n#{invoice.user.email}\n#{address}", :at => [bounds.width - 130, bounds.top - 49], :width => 130, :align => :right, :inline_format => true text_box "<b>#{name}</b>\n#{invoice.user.email}\n#{address}",
at: [bounds.width - 130, bounds.top - 49],
width: 130,
align: :right,
inline_format: true
name = full_name name = full_name
# object # object
move_down 25 move_down 25
if invoice.is_a?(Avoir) if invoice.is_a?(Avoir)
if invoice.invoiced_type == WalletTransaction.name object = if invoice.invoiced_type == WalletTransaction.name
object = I18n.t('invoices.wallet_credit') I18n.t('invoices.wallet_credit')
else else
object = I18n.t('invoices.cancellation_of_invoice_REF', REF: invoice.invoice.reference) I18n.t('invoices.cancellation_of_invoice_REF', REF: invoice.invoice.reference)
end end
else else
case invoice.invoiced_type case invoice.invoiced_type
when 'Reservation' when 'Reservation'
object = I18n.t('invoices.reservation_of_USER_on_DATE_at_TIME', USER: name, DATE: I18n.l(invoice.invoiced.slots[0].start_at.to_date), TIME: I18n.l(invoice.invoiced.slots[0].start_at, format: :hour_minute)) object = I18n.t('invoices.reservation_of_USER_on_DATE_at_TIME',
USER: name,
DATE: I18n.l(invoice.invoiced.slots[0].start_at.to_date),
TIME: I18n.l(invoice.invoiced.slots[0].start_at, format: :hour_minute))
invoice.invoice_items.each do |item| invoice.invoice_items.each do |item|
if item.subscription_id next unless item.subscription_id
subscription = Subscription.find item.subscription_id subscription = Subscription.find item.subscription_id
object = "\n- #{object}\n- #{(invoice.is_a?(Avoir) ? I18n.t('invoices.cancellation')+' - ' : '') + subscription_verbose(subscription, name)}" object = "\n- #{object}\n- #{(invoice.is_a?(Avoir) ? I18n.t('invoices.cancellation') + ' - ' : '') + subscription_verbose(subscription, name)}"
break break
end end
end
when 'Subscription' when 'Subscription'
object = subscription_verbose(invoice.invoiced, name) object = subscription_verbose(invoice.invoiced, name)
when 'OfferDay' when 'OfferDay'
@ -97,13 +105,13 @@ module PDF
puts "ERROR : specified invoiced type (#{invoice.invoiced_type}) is unknown" puts "ERROR : specified invoiced type (#{invoice.invoiced_type}) is unknown"
end end
end end
text I18n.t('invoices.object')+' '+object text I18n.t('invoices.object') + ' ' + object
# details table of the invoice's elements # details table of the invoice's elements
move_down 20 move_down 20
text I18n.t('invoices.order_summary'), :leading => 4 text I18n.t('invoices.order_summary'), leading: 4
move_down 2 move_down 2
data = [ [I18n.t('invoices.details'), I18n.t('invoices.amount')] ] data = [[I18n.t('invoices.details'), I18n.t('invoices.amount')]]
total_calc = 0 total_calc = 0
# going through invoice_items # going through invoice_items
@ -111,16 +119,21 @@ module PDF
price = item.amount.to_i / 100.00 price = item.amount.to_i / 100.00
details = invoice.is_a?(Avoir) ? I18n.t('invoices.cancellation')+' - ' : '' details = invoice.is_a?(Avoir) ? I18n.t('invoices.cancellation') + ' - ' : ''
if item.subscription_id ### Subscription if item.subscription_id ### Subscription
subscription = Subscription.find item.subscription_id subscription = Subscription.find item.subscription_id
if invoice.invoiced_type == 'OfferDay' if invoice.invoiced_type == 'OfferDay'
details += I18n.t('invoices.subscription_extended_for_free_from_START_to_END', START:I18n.l(invoice.invoiced.start_at.to_date), END:I18n.l(invoice.invoiced.end_at.to_date)) details += I18n.t('invoices.subscription_extended_for_free_from_START_to_END',
START: I18n.l(invoice.invoiced.start_at.to_date),
END: I18n.l(invoice.invoiced.end_at.to_date))
else else
subscription_end_at = subscription_expiration_date.is_a?(Time) ? subscription_expiration_date : DateTime.parse(subscription_expiration_date) subscription_end_at = subscription_expiration_date.is_a?(Time) ? subscription_expiration_date : DateTime.parse(subscription_expiration_date)
subscription_start_at = subscription_end_at - subscription.plan.duration subscription_start_at = subscription_end_at - subscription.plan.duration
details += I18n.t('invoices.subscription_NAME_from_START_to_END', NAME:item.description, START:I18n.l(subscription_start_at.to_date), END:I18n.l(subscription_expiration_date.to_date)) details += I18n.t('invoices.subscription_NAME_from_START_to_END',
NAME: item.description,
START: I18n.l(subscription_start_at.to_date),
END: I18n.l(subscription_expiration_date.to_date))
end end
@ -138,9 +151,9 @@ module PDF
when 'Event' when 'Event'
details += I18n.t('invoices.event_reservation_DESCRIPTION', DESCRIPTION: item.description) details += I18n.t('invoices.event_reservation_DESCRIPTION', DESCRIPTION: item.description)
# details of the number of tickets # details of the number of tickets
details += "\n "+I18n.t('invoices.full_price_ticket', count: invoice.invoiced.nb_reserve_places) if invoice.invoiced.nb_reserve_places > 0 details += "\n " + I18n.t('invoices.full_price_ticket', count: invoice.invoiced.nb_reserve_places) if invoice.invoiced.nb_reserve_places.positive?
invoice.invoiced.tickets.each do |t| invoice.invoiced.tickets.each do |t|
details += "\n "+I18n.t('invoices.other_rate_ticket', count: t.booked, NAME: t.event_price_category.price_category.name) details += "\n " + I18n.t('invoices.other_rate_ticket', count: t.booked, NAME: t.event_price_category.price_category.name)
end end
### wallet credit ### wallet credit
when nil when nil
@ -165,8 +178,8 @@ module PDF
elsif cp.type == 'amount_off' elsif cp.type == 'amount_off'
# refunds of invoices with cash coupons: we need to ventilate coupons on paid items # refunds of invoices with cash coupons: we need to ventilate coupons on paid items
if invoice.is_a?(Avoir) if invoice.is_a?(Avoir)
paid_items = invoice.invoice.invoice_items.select{ |ii| ii.amount > 0 }.length paid_items = invoice.invoice.invoice_items.select{ |ii| ii.amount.positive? }.length
refund_items = invoice.invoice_items.select{ |ii| ii.amount > 0 }.length refund_items = invoice.invoice_items.select{ |ii| ii.amount.positive? }.length
discount = ((invoice.coupon.amount_off / paid_items) * refund_items) / 100.0 discount = ((invoice.coupon.amount_off / paid_items) * refund_items) / 100.0
else else
@ -176,7 +189,7 @@ module PDF
raise InvalidCouponError raise InvalidCouponError
end end
total_calc = total_calc - discount total_calc -= discount
# discount textual description # discount textual description
literal_discount = cp.percent_off literal_discount = cp.percent_off
@ -185,54 +198,55 @@ module PDF
end end
# add a row for the coupon # add a row for the coupon
data += [ [_t('invoices.coupon_CODE_discount_of_DISCOUNT', {CODE: cp.code, DISCOUNT: literal_discount, TYPE: cp.type}), number_to_currency(-discount)] ] data += [[_t('invoices.coupon_CODE_discount_of_DISCOUNT',
CODE: cp.code,
DISCOUNT: literal_discount,
TYPE: cp.type), number_to_currency(-discount)] ]
end end
# total verification # total verification
total = invoice.total / 100.0 total = invoice.total / 100.0
if total_calc != total puts "ERROR: totals are NOT equals => expected: #{total}, computed: #{total_calc}" if total_calc != total
puts "ERROR: totals are NOT equals => expected: #{total}, computed: #{total_calc}"
end
# TVA # TVA
if Setting.find_by({name: 'invoice_VAT-active'}).value == 'true' if Setting.find_by(name: 'invoice_VAT-active').value == 'true'
data += [ [I18n.t('invoices.total_including_all_taxes'), number_to_currency(total)] ] data += [[I18n.t('invoices.total_including_all_taxes'), number_to_currency(total)]]
vat_rate = Setting.find_by({name: 'invoice_VAT-rate'}).value.to_f vat_rate = Setting.find_by(name: 'invoice_VAT-rate').value.to_f
vat = total / (vat_rate / 100 + 1) vat = total / (vat_rate / 100 + 1)
data += [ [I18n.t('invoices.including_VAT_RATE', RATE: vat_rate), number_to_currency(total-vat)] ] data += [[I18n.t('invoices.including_VAT_RATE', RATE: vat_rate), number_to_currency(total - vat)]]
data += [ [I18n.t('invoices.including_total_excluding_taxes'), number_to_currency(vat)] ] data += [[I18n.t('invoices.including_total_excluding_taxes'), number_to_currency(vat)]]
data += [ [I18n.t('invoices.including_amount_payed_on_ordering'), number_to_currency(total)] ] data += [[I18n.t('invoices.including_amount_payed_on_ordering'), number_to_currency(total)]]
# checking the round number # checking the round number
rounded = sprintf('%.2f', vat).to_f + sprintf('%.2f', total-vat).to_f rounded = sprintf('%.2f', vat).to_f + sprintf('%.2f', total - vat).to_f
if rounded != sprintf('%.2f', total_calc).to_f if rounded != sprintf('%.2f', total_calc).to_f
puts "ERROR: rounding the numbers cause an invoice inconsistency. Total expected: #{sprintf('%.2f', total_calc)}, total computed: #{rounded}" puts "ERROR: rounding the numbers cause an invoice inconsistency. Total expected: #{sprintf('%.2f', total_calc)}, total computed: #{rounded}"
end end
else else
data += [ [I18n.t('invoices.total_amount'), number_to_currency(total)] ] data += [[I18n.t('invoices.total_amount'), number_to_currency(total)]]
end end
# display table # display table
table(data, :header => true, :column_widths => [400, 72], :cell_style => {:inline_format => true}) do table(data, header: true, column_widths: [400, 72], cell_style: { inline_format: true }) do
row(0).font_style = :bold row(0).font_style = :bold
column(1).style :align => :right column(1).style align: :right
if Setting.find_by({name: 'invoice_VAT-active'}).value == 'true' if Setting.find_by(name: 'invoice_VAT-active').value == 'true'
# Total incl. taxes # Total incl. taxes
row(-1).style :align => :right row(-1).style align: :right
row(-1).background_color = 'E4E4E4' row(-1).background_color = 'E4E4E4'
row(-1).font_style = :bold row(-1).font_style = :bold
# including VAT xx% # including VAT xx%
row(-2).style :align => :right row(-2).style align: :right
row(-2).background_color = 'E4E4E4' row(-2).background_color = 'E4E4E4'
row(-2).font_style = :italic row(-2).font_style = :italic
# including total excl. taxes # including total excl. taxes
row(-3).style :align => :right row(-3).style align: :right
row(-3).background_color = 'E4E4E4' row(-3).background_color = 'E4E4E4'
row(-3).font_style = :italic row(-3).font_style = :italic
# including amount payed on ordering # including amount payed on ordering
row(-4).style :align => :right row(-4).style align: :right
row(-4).background_color = 'E4E4E4' row(-4).background_color = 'E4E4E4'
row(-4).font_style = :bold row(-4).font_style = :bold
end end
@ -240,14 +254,12 @@ module PDF
# optional description for refunds # optional description for refunds
move_down 20 move_down 20
if invoice.is_a?(Avoir) and invoice.description text invoice.description if invoice.is_a?(Avoir) && invoice.description
text invoice.description
end
# payment details # payment details
move_down 20 move_down 20
if invoice.is_a?(Avoir) if invoice.is_a?(Avoir)
payment_verbose = I18n.t('invoices.refund_on_DATE', DATE:I18n.l(invoice.avoir_date.to_date))+' ' payment_verbose = I18n.t('invoices.refund_on_DATE', DATE:I18n.l(invoice.avoir_date.to_date)) + ' '
case invoice.avoir_mode case invoice.avoir_mode
when 'stripe' when 'stripe'
payment_verbose += I18n.t('invoices.by_stripe_online_payment') payment_verbose += I18n.t('invoices.by_stripe_online_payment')
@ -270,30 +282,28 @@ module PDF
# subtract the wallet amount for this invoice from the total # subtract the wallet amount for this invoice from the total
if invoice.wallet_amount if invoice.wallet_amount
wallet_amount = invoice.wallet_amount / 100.0 wallet_amount = invoice.wallet_amount / 100.0
total = total - wallet_amount total -= wallet_amount
end end
# payment method # payment method
if invoice.stp_invoice_id payment_verbose = if invoice.stp_invoice_id
payment_verbose = I18n.t('invoices.settlement_by_debit_card') I18n.t('invoices.settlement_by_debit_card')
else else
payment_verbose = I18n.t('invoices.settlement_done_at_the_reception') I18n.t('invoices.settlement_done_at_the_reception')
end end
# if the invoice was 100% payed with the wallet ... # if the invoice was 100% payed with the wallet ...
if total == 0 and wallet_amount payment_verbose = I18n.t('invoices.settlement_by_wallet') if total.zero? && wallet_amount
payment_verbose = I18n.t('invoices.settlement_by_wallet')
end
payment_verbose += ' '+I18n.t('invoices.on_DATE_at_TIME', DATE: I18n.l(invoice.created_at.to_date), TIME:I18n.l(invoice.created_at, format: :hour_minute)) payment_verbose += ' ' + I18n.t('invoices.on_DATE_at_TIME', DATE: I18n.l(invoice.created_at.to_date), TIME:I18n.l(invoice.created_at, format: :hour_minute))
if total > 0 or !invoice.wallet_amount if total.positive? || !invoice.wallet_amount
payment_verbose += ' '+I18n.t('invoices.for_an_amount_of_AMOUNT', AMOUNT: number_to_currency(total)) payment_verbose += ' ' + I18n.t('invoices.for_an_amount_of_AMOUNT', AMOUNT: number_to_currency(total))
end end
if invoice.wallet_amount if invoice.wallet_amount
if total > 0 if total.positive?
payment_verbose += ' '+I18n.t('invoices.and') + ' ' + I18n.t('invoices.by_wallet') + ' ' + I18n.t('invoices.for_an_amount_of_AMOUNT', AMOUNT: number_to_currency(wallet_amount)) payment_verbose += ' ' + I18n.t('invoices.and') + ' ' + I18n.t('invoices.by_wallet') + ' ' + I18n.t('invoices.for_an_amount_of_AMOUNT', AMOUNT: number_to_currency(wallet_amount))
else else
payment_verbose += ' '+I18n.t('invoices.for_an_amount_of_AMOUNT', AMOUNT: number_to_currency(wallet_amount)) payment_verbose += ' ' + I18n.t('invoices.for_an_amount_of_AMOUNT', AMOUNT: number_to_currency(wallet_amount))
end end
end end
end end
@ -301,27 +311,28 @@ module PDF
# important information # important information
move_down 40 move_down 40
txt = parse_html(Setting.find_by({name: 'invoice_text'}).value) txt = parse_html(Setting.find_by(name: 'invoice_text').value)
txt.each_line do |line| txt.each_line do |line|
text line, :style => :bold, :inline_format => true text line, style: :bold, inline_format: true
end end
# address and legals information # address and legals information
move_down 40 move_down 40
txt = parse_html(Setting.find_by({name: 'invoice_legals'}).value) txt = parse_html(Setting.find_by(name: 'invoice_legals').value)
txt.each_line do |line| txt.each_line do |line|
text line, :align => :right, :leading => 4, :inline_format => true text line, align: :right, leading: 4, inline_format: true
end end
end end
end end
private private
def reservation_dates_verbose(slot) def reservation_dates_verbose(slot)
if slot.start_at.to_date == slot.end_at.to_date if slot.start_at.to_date == slot.end_at.to_date
'- '+I18n.t('invoices.on_DATE_from_START_to_END', DATE: I18n.l(slot.start_at.to_date), START: I18n.l(slot.start_at, format: :hour_minute), END: I18n.l(slot.end_at, format: :hour_minute))+"\n" '- ' + I18n.t('invoices.on_DATE_from_START_to_END', DATE: I18n.l(slot.start_at.to_date), START: I18n.l(slot.start_at, format: :hour_minute), END: I18n.l(slot.end_at, format: :hour_minute)) + "\n"
else else
'- '+I18n.t('invoices.from_STARTDATE_to_ENDDATE_from_STARTTIME_to_ENDTIME', STARTDATE: I18n.l(slot.start_at.to_date), ENDDATE: I18n.l(slot.start_at.to_date), STARTTIME: I18n.l(slot.start_at, format: :hour_minute), ENDTIME: I18n.l(slot.end_at, format: :hour_minute))+"\n" '- ' + I18n.t('invoices.from_STARTDATE_to_ENDDATE_from_STARTTIME_to_ENDTIME', STARTDATE: I18n.l(slot.start_at.to_date), ENDDATE: I18n.l(slot.start_at.to_date), STARTTIME: I18n.l(slot.start_at, format: :hour_minute), ENDTIME: I18n.l(slot.end_at, format: :hour_minute)) + "\n"
end end
end end
@ -335,8 +346,6 @@ module PDF
I18n.t('invoices.subscription_of_NAME_extended_starting_from_STARTDATE_until_ENDDATE', NAME: username, STARTDATE: I18n.l(offer_day.start_at.to_date), ENDDATE: I18n.l(offer_day.end_at.to_date)) I18n.t('invoices.subscription_of_NAME_extended_starting_from_STARTDATE_until_ENDDATE', NAME: username, STARTDATE: I18n.l(offer_day.start_at.to_date), ENDDATE: I18n.l(offer_day.end_at.to_date))
end end
## ##
# Remove every unsupported html tag from the given html text (like <p>, <span>, ...). # Remove every unsupported html tag from the given html text (like <p>, <span>, ...).
# The supported tags are <b>, <u>, <i> and <br>. # The supported tags are <b>, <u>, <i> and <br>.
@ -344,7 +353,6 @@ module PDF
# @return [String] multi line simplified html text # @return [String] multi line simplified html text
## ##
def parse_html(html) def parse_html(html)
ActionController::Base.helpers.sanitize(html, tags: %w(b u i br)) ActionController::Base.helpers.sanitize(html, tags: %w[b u i br])
end
end end
end end