Class: ReportPdf

Inherits:
Prawn::Document
  • Object
show all
Includes:
MoneyRails::ActionViewExtension, ReservationExportHelpers
Defined in:
app/my_lib/report_pdf.rb

Constant Summary collapse

TABLE_COLUMN_WIDTHS =
[
  50, # ID
  73, # Restaurant-Name
  50, # Customer-Name
  50, # Dining-Date
  45, # Dining-Time
  30, # Adult
  30, # Kids
  30, # Party-Size
  45, # Status
  50, # Special-Request
  60, # Package-Type
  60, # Package-Price
  50, # Restaurant-Revenue
  40, # Commision
  50, # Voucher-Code
  50, # Voucher-Amount
].freeze
TABLE_COLUMN_WIDTHS_F2 =
[
  50, # ID
  70, # Created-At
  60, # Service-Type
  50, # Distance
  40, # Pre-Payment
  60, # Payment-Type
  60, # Paid-At-Date
  60, # Paid-At-Time
  50, # Payment-Gateway
  50, # Payment-Gateway-Account
  70, # Old-Reservation-ID
].freeze

Constants included from ExportConstants

ExportConstants::CHANNEL_IDS_TO_SKIP, ExportConstants::DEFAULT_QUEUE, ExportConstants::EMAIL_BATCH_SIZE, ExportConstants::ERROR_CATEGORIES, ExportConstants::EXCEL_FILE_EXTENSION, ExportConstants::LARGE_DATASET_WARNING_THRESHOLD, ExportConstants::LONG_PROCESS_DAYS_THRESHOLD, ExportConstants::LONG_PROCESS_QUEUE, ExportConstants::MAX_RETRIES, ExportConstants::PDF_FILE_EXTENSION, ExportConstants::PROGRESS_MESSAGES, ExportConstants::PROGRESS_PHASES, ExportConstants::PROGRESS_UPDATE_BATCH_SIZE, ExportConstants::RESERVATION_BATCH_SIZE, ExportConstants::RETRY_BASE_INTERVAL, ExportConstants::RETRY_MAX_ELAPSED_TIME, ExportConstants::ZERO_COMMISSION_CHANNEL_ID

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ReservationExportHelpers

#calc_prepayment, #calculate_commission, #calculate_restaurant_revenue, #calculate_total_package_price, #date_format, #decimal_format, #format_add_on_names_with_quantity, #format_addon_names_for_report, #format_money, #format_package_names, #format_package_names_for_report, #format_package_names_with_quantity, #format_voucher_amount, #format_voucher_code, #get_reservation_distance, #paid_amount, #restaurant_delivery_fee, #sanitize_package_name, #sanitizer, #valid_email?, #voucher_amount, #voucher_code

Constructor Details

#initialize(reservations = nil, args = {}) ⇒ ReportPdf

Returns a new instance of ReportPdf.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/my_lib/report_pdf.rb', line 44

def initialize(reservations = nil, args = {})
  @reservations = reservations
  if args.present?
    args.to_h.with_indifferent_access.each do |k, v|
      send("#{k}=".to_sym, v)
    end
  end

  super(top_margin: 10, page_size: 'A4', page_layout: :landscape)
  font_families.update('Mitr' => {
                         normal: Rails.root.join('vendor/assets/fonts/mitr/Mitr-Regular.ttf'),
                         bold: Rails.root.join('vendor/assets/fonts/mitr/Mitr-Bold.ttf'),
                       })

  font 'Mitr'
  @pdf_url = {}
end

Instance Attribute Details

#date_filter_typeObject

Returns the value of attribute date_filter_type.



41
42
43
# File 'app/my_lib/report_pdf.rb', line 41

def date_filter_type
  @date_filter_type
end

#end_dateObject

Returns the value of attribute end_date.



41
42
43
# File 'app/my_lib/report_pdf.rb', line 41

def end_date
  @end_date
end

#pdf_urlObject

Returns the value of attribute pdf_url.



41
42
43
# File 'app/my_lib/report_pdf.rb', line 41

def pdf_url
  @pdf_url
end

#reservationsObject

Returns the value of attribute reservations.



41
42
43
# File 'app/my_lib/report_pdf.rb', line 41

def reservations
  @reservations
end

#restaurant_group_idObject

Returns the value of attribute restaurant_group_id.



41
42
43
# File 'app/my_lib/report_pdf.rb', line 41

def restaurant_group_id
  @restaurant_group_id
end

#restaurant_idObject

Returns the value of attribute restaurant_id.



41
42
43
# File 'app/my_lib/report_pdf.rb', line 41

def restaurant_id
  @restaurant_id
end

#staff_idObject

Returns the value of attribute staff_id.



41
42
43
# File 'app/my_lib/report_pdf.rb', line 41

def staff_id
  @staff_id
end

#start_dateObject

Returns the value of attribute start_date.



41
42
43
# File 'app/my_lib/report_pdf.rb', line 41

def start_date
  @start_date
end

Instance Method Details



231
232
233
234
235
236
237
238
239
# File 'app/my_lib/report_pdf.rb', line 231

def download_link
  link = attachment.pdf_url
  link = "#{Figaro.env.HH_HOST_URL!}#{link}" unless link.include? 'http'

  return link unless Figaro.bool_env! :ENABLE_CDN

  link.gsub(Figaro.env.CDN_URL, Figaro.env.HH_HOST_URL)
  link
end

#filepathObject



227
228
229
# File 'app/my_lib/report_pdf.rb', line 227

def filepath
  Rails.root.join('tmp', 'reports', file_name).to_s
end

#generate_pdf(reservations, args = {}) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'app/my_lib/report_pdf.rb', line 197

def generate_pdf(reservations, args = {})
  [1, 2].each do |number|
    args[:file_number] = number
    args[:file_name] = "Hungry-Hub-report-#{Time.zone.today}-#{restaurant_id}#{Time.current_time.to_i}-#{number}.pdf"
    file_pdf = self.class.new(reservations, args)
    file_pdf.generate_pdf_table
    file_pdf.render_file(file_pdf.filepath)
    path = Rails.root.join(file_pdf.filepath)
    loop do
      break if path.exist?

      sleep 1
    end

    file_pdf.save_attachment
    @pdf_url["file_#{number}".to_sym] = file_pdf.download_link
  end
end

#generate_pdf_tableObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'app/my_lib/report_pdf.rb', line 62

def generate_pdf_table
  I18n.locale = :en
  data = []

  image_url = begin
    AdminSetting.report_pdf_image_url.present? && open(AdminSetting.report_pdf_image_url)
  rescue StandardError
    nil
  end
  banner = [[{ image: image_url, image_height: 110, image_width: 530, position: :center }]] if image_url.present?

  label = []
  if report_restaurant?
    label += [['Restaurant Name', restaurant.name]]
  elsif report_restaurant_group?
    label += [['Group Name', restaurant_group.name]]
  elsif report_staff_restaurants?
    group_name = if staff.default_restaurant.restaurant_group.present?
                   staff.default_restaurant.restaurant_group.name
                 else
                   staff.default_restaurant.name
                 end
    label += [['Group Name', group_name]]
  end

  case date_filter_type
  when 'single'
    label += [['Date', start_date.strftime('%d/%m/%Y')]]
  when 'range'
    label += [['Start Date', start_date.strftime('%d/%m/%Y')]]
    label += [['End Date', end_date.strftime('%d/%m/%Y')]]
  end

  bounding_box([0, 510], width: 230) do
    table(label, cell_style: { border_width: 0 })
    # transparent(0.5) { stroke_bounds }
  end
  if banner.present?
    bounding_box([370, 530], width: 250) do
      table(banner, cell_style: { border_width: 0 })
      # transparent(0.5) { stroke_bounds }
    end
  end

  move_down 20

  case file_number
  when 1
    if report_restaurant?
      data.push(%w[ID Customer-Name Dining-Date Dining-Time
                   Adult Kids Party-Size Status Special-Request Package-Type Package-Price
                   Restaurant-Revenue Commision Voucher-Code Voucher-Amount])
    elsif report_restaurant_group? || report_staff_restaurants?
      data.push(%w[ID Restaurant-Name Customer-Name Dining-Date Dining-Time
                   Adult Kids Party-Size Status Special-Request Package-Type Package-Price
                   Restaurant-Revenue Commision Voucher-Code Voucher-Amount])
    end
  when 2
    data.push(%w[ID Created-At Service-Type Distance Pre-Payment
                 Payment-Type Paid-At-Date Paid-At-Time Payment-Gateway
                 Payment-Gateway-Account Old-Reservation-ID])
  end

  reservations.find_each do |r|
    total_package_price = if r.package?
                            total = r.package_obj.formatted_packages.map do |item|
                              Money.new(item['price_cents'], item['price_currency']).amount
                            end.sum
                            decimal_format(total)
                          end
    row_data = case file_number
               when 1
                 row = if report_restaurant_group? || report_staff_restaurants?
                         [r.id, r.restaurant.name]
                       else
                         [r.id]
                       end
                 row + [
                   r.name,
                   r.date,
                   r.start_time_format,
                   r.adult,
                   r.kids,
                   r.party_size,
                   r.status,
                   r.special_request,
                   r.package? ? r.package_obj.type : '',
                   total_package_price,
                   restaurant_revenue_amount(r),
                   revenue_amount(r),
                   r.vouchers.present? ? r.voucher_codes_humanize : '',
                   r.vouchers.present? ? humanized_money(r.vouchers_amount) : '',
                 ]
               when 2
                 [
                   r.id,
                   date_format(r.created_at),
                   r.service_type_humanize,
                   get_reservation_distance(r.distance_to_restaurant),
                   calc_prepayment(r),
                   r.payment_type,
                   date_format(r.paid_at&.to_date),
                   r.paid_at&.strftime('%H:%M'),
                   r.payment_gateway,
                   r.,
                   r.old_reservation_id,
                 ]
               end
    data.push(row_data)
  end
  table(data, table_options(file_number))
end

#save_attachmentObject



216
217
218
219
# File 'app/my_lib/report_pdf.rb', line 216

def save_attachment
  self.attachment = store_to_attachment
  delete_report(attachment)
end

#store_to_attachmentObject



221
222
223
224
225
# File 'app/my_lib/report_pdf.rb', line 221

def store_to_attachment
  new_attachment = Attachment.new pdf: open(filepath)
  new_attachment.save!
  new_attachment
end

#table_options(file_number) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'app/my_lib/report_pdf.rb', line 175

def table_options(file_number)
  table_column_widths = TABLE_COLUMN_WIDTHS.dup
  restaurant_name_column = table_column_widths.index(73)
  if report_restaurant? && restaurant_name_column.present?
    table_column_widths.delete_at(restaurant_name_column)
  end

  config = if file_number == 1
             table_column_widths
           else
             TABLE_COLUMN_WIDTHS_F2
           end

  column_widths = {}
  config.each_with_index { |v, k| column_widths[k] = v }
  {
    cell_style: { size: 8 },
    column_widths: column_widths,
    header: true,
  }
end