Last active
May 11, 2020 13:46
-
-
Save deneuxa/13480b0716963abf3221358c279f8e3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Waveapps::ExportInvoiceWorker | |
require 'zip' | |
require 'open-uri' | |
require 'csv' | |
include Sidekiq::Worker | |
include ActionView::Helpers::NumberHelper | |
sidekiq_options queue: :critical | |
BUSINESS_ID = "" | |
def perform | |
@start_date = Date.today.prev_month.beginning_of_month | |
@end_date = @start_date.end_of_month | |
invoices = Waveapps::Invoice.list_invoices(business_id: BUSINESS_ID, invoice_date_start: @start_date, invoice_date_end: @end_date).edges.map(&:node) | |
Zip::File.open(output_path, Zip::File::CREATE) do |zipfile| | |
csv_data = CSV.generate(force_quotes: false, col_sep: ";") do |csv| | |
csv << ["number", "date", "customer", "due date", "amount", "currency"] | |
invoices.each do |invoice| | |
csv << [invoice.invoice_number, invoice.invoice_date, invoice.customer.name, invoice.due_date, amount(invoice), currency(invoice)] | |
zipfile.get_output_stream(file_name(invoice)) { |f| f.write pdf_file(invoice) } | |
end | |
end | |
zipfile.get_output_stream("invoices from #{@start_date.strftime('%Y-%m-%d')} to #{@end_date.strftime('%Y-%m-%d')}.csv") { |f| f.write csv_data } | |
end | |
zip_data = File.open(output_path).read | |
File.delete(output_path) | |
BasicMailer.delay(queue: :critical).normal(%w(accounting@mail.com owner@mail.com), | |
"Invoices from #{@start_date.strftime('%d/%m/%Y')} to #{@end_date.strftime('%d/%m/%Y')}", | |
"See attachment", | |
attachments_list: {"Invoices-#{@start_date.strftime('%Y-%m-%d')}-#{@end_date.strftime('%Y-%m-%d')}.zip" => zip_data}) | |
end | |
private | |
def output_path | |
@output_path ||= "#{Rails.root}/tmp/#{SecureRandom.urlsafe_base64}.zip" | |
end | |
def file_name(invoice) | |
"Invoice_#{invoice.invoice_number}_#{invoice.customer.name}_#{amount(invoice)}#{currency(invoice)}.pdf" | |
end | |
def pdf_file(invoice) | |
open(invoice.pdf_url).read | |
end | |
def amount(invoice) | |
number_with_precision(invoice.amount_due.value.gsub(',', '').to_f + invoice.amount_paid.value.gsub(',', '').to_f, precision: 2, separator: '.') | |
end | |
def currency(invoice) | |
invoice.amount_due.currency.symbol | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment