Class: Caboose::InvoicesController

Inherits:
ApplicationController show all
Defined in:
app/controllers/caboose/invoices_controller.rb,
app/controllers/caboose/invoice_reports_controller.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#add_ga_event, #admin_bulk_add, #admin_bulk_delete, #admin_bulk_update, #admin_json_single, #before_action, #before_before_action, #hashify_query_string, #init_cart, #logged_in?, #logged_in_user, #login_user, #logout_user, #parse_url_params, #reject_param, #under_construction_or_forwarding_domain?, #user_is_allowed, #user_is_allowed_to, #validate_cookie, #validate_token, #var, #verify_logged_in

Instance Method Details

#admin_addObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'app/controllers/caboose/invoices_controller.rb', line 55

def admin_add
  return if !user_is_allowed('invoices', 'add')
  invoice = Invoice.create(
    :site_id => @site.id,
    :status => Invoice::STATUS_PENDING,                          
    :financial_status => Invoice::FINANCIAL_STATUS_PENDING,
    :invoice_number => @site.store_config.next_invoice_number
  )
  InvoiceLog.create(
    :invoice_id     => invoice.id,
    :user_id        => logged_in_user.id,
    :date_logged    => DateTime.now.utc,
    :invoice_action => InvoiceLog::ACTION_INVOICE_CREATED                        
  )      
  render :json => { :sucess => true, :redirect => "/admin/invoices/#{invoice.id}" }
end

#admin_authorize_and_captureObject



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'app/controllers/caboose/invoices_controller.rb', line 121

def admin_authorize_and_capture
  return if !user_is_allowed('invoices', 'edit')
       
  invoice = Invoice.find(params[:id])
  resp = invoice.authorize_and_capture   
  
  # Send out emails
  #begin
  #  InvoicesMailer.configure_for_site(@site.id).customer_new_invoice(@invoice).deliver
  #  InvoicesMailer.configure_for_site(@site.id).fulfillment_new_invoice(@invoice).deliver
  #rescue
  #  puts "=================================================================="
  #  puts "Error sending out invoice confirmation emails for invoice ID #{@invoice.id}"
  #  puts "=================================================================="
  #end
  
  render :json => resp
end

#admin_calculate_handlingObject



98
99
100
101
102
103
104
105
# File 'app/controllers/caboose/invoices_controller.rb', line 98

def admin_calculate_handling
  return if !user_is_allowed('invoices', 'edit')
  invoice = Invoice.find(params[:id])
  invoice.handling = invoice.calculate_handling
  invoice.total = invoice.calculate_total
  invoice.save
  render :json => { :success => true }      
end

#admin_calculate_taxObject



88
89
90
91
92
93
94
95
# File 'app/controllers/caboose/invoices_controller.rb', line 88

def admin_calculate_tax
  return if !user_is_allowed('invoices', 'edit')
  invoice = Invoice.find(params[:id])
  invoice.tax = invoice.calculate_tax
  invoice.total = invoice.calculate_total
  invoice.save
  render :json => { :success => true }      
end

#admin_city_reportObject



298
299
300
301
302
303
304
305
306
# File 'app/controllers/caboose/invoices_controller.rb', line 298

def admin_city_report
  return if !user_is_allowed('invoices', 'view')

  @d1 = params[:d1] ? DateTime.strptime("#{params[:d1]} 00:00:00", '%Y-%m-%d %H:%M:%S') : DateTime.strptime(DateTime.now.strftime("%Y-%m-01 00:00:00"), '%Y-%m-%d %H:%M:%S')
  @d2 = params[:d2] ? DateTime.strptime("#{params[:d2]} 00:00:00", '%Y-%m-%d %H:%M:%S') : @d1 + 1.month      
  @rows = InvoiceReporter.city_report(@site.id, @d1, @d2)
  
  render :layout => 'caboose/admin'    
end

#admin_deleteObject



267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'app/controllers/caboose/invoices_controller.rb', line 267

def admin_delete
  return if !user_is_allowed('invoices', 'delete')
  Invoice.find(params[:id]).destroy      
  InvoiceLog.create(
    :invoice_id     => params[:id],
    :user_id        => logged_in_user.id,
    :date_logged    => DateTime.now.utc,
    :invoice_action => InvoiceLog::ACTION_INVOICE_DELETED                                                                          
  )      
  render :json => Caboose::StdClass.new({
    :redirect => '/admin/invoices'
  })
end

#admin_editObject



75
76
77
78
79
80
81
82
83
84
85
# File 'app/controllers/caboose/invoices_controller.rb', line 75

def admin_edit
  return if !user_is_allowed('invoices', 'edit')
  @invoice = Invoice.where(:id => params[:id]).first
  @edituser = params[:user_id] ? User.find(params[:user_id]) : nil
  
  if params[:id].nil? || @invoice.nil?
    render :file => 'caboose/invoices/admin_invalid_invoice', :layout => 'caboose/admin'
    return
  end            
  render :layout => 'caboose/admin'
end

#admin_google_feedObject



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'app/controllers/caboose/invoices_controller.rb', line 360

def admin_google_feed
  d2 = DateTime.now
  d1 = DateTime.now
  if Caboose::Setting.exists?(:name => 'google_feed_date_last_submitted')                  
    d1 = Caboose::Setting.where(:name => 'google_feed_date_last_submitted').first.value      
    d1 = DateTime.parse(d1)
  elsif Invoice.exists?("status = ? and date_authorized is not null", Invoice::STATUS_PROCESSED)
    d1 = Invoice.where("status = ? and date_authorized is not null", Invoice::STATUS_PROCESSED).reorder("date_authorized DESC").limit(1).pluck('date_authorized')
    d1 = DateTime.parse(d1)
  end
  
  # Google Feed Docs
  # https://support.google.com/trustedstoresmerchant/answer/3272612?hl=en&ref_topic=3272286?hl=en
  tsv = ["merchant invoice id\ttracking number\tcarrier code\tother carrier name\tship date"]            
  if Invoice.exists?("status = ? and date_authorized > '#{d1.strftime("%F %T")}'", Invoice::STATUS_PROCESSED)
    Invoice.where("status = ? and date_authorized > ?", Invoice::STATUS_PROCESSED, d1).reorder(:id).all.each do |invoice|
      tracking_numbers = invoice.line_items.collect{ |li| li.tracking_number }.compact.uniq
      tn = tracking_numbers && tracking_numbers.count >= 1 ? tracking_numbers[0] : ""
      tsv << "#{invoice.id}\t#{tn}\tUPS\t\t#{invoice.date_shipped.strftime("%F")}"                              
    end
  end
  
  # Save when we made the last call
  setting = if Caboose::Setting.exists?(:name => 'google_feed_date_last_submitted')
    Caboose::Setting.where(:name => 'google_feed_date_last_submitted').first
  else
    Caboose::Setting.new(:name => 'google_feed_date_last_submitted')
  end
  
  setting.value = d2.strftime("%F %T")
  setting.save            
               
  # Print out the lines
  render :text => tsv.join("\n")
end

#admin_indexObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'app/controllers/caboose/invoices_controller.rb', line 6

def admin_index
  return if !user_is_allowed('invoices', 'view')
  
  @pager = Caboose::PageBarGenerator.new(params, {
    'site_id'              => @site.id,
    'customer_id'          => params[:user_id] ? params[:user_id] : '', 
    'status'               => Invoice::STATUS_PENDING,      
    'shipping_method_code' => '',
    'id'                   => '',
    'invoice_number'       => '',
    'total_lte'            => '',
    'total_gte'            => ''
  }, {
    'model'          => 'Caboose::Invoice',
    'sort'           => 'id',
    'desc'           => 1,
    'base_url'       => params[:user_id] ? "/admin/users/#{params[:user_id]}/invoices" : "/admin/invoices",
    'use_url_params' => false,
    'items_per_page' => 100
  })
  
  @edituser = params[:user_id] ? User.find(params[:user_id]) : nil
  @invoices  = @pager.items
  @customers = Caboose::User.where(:site_id => @site.id).reorder('last_name, first_name').all
  
  render :layout => 'caboose/admin'
end

#admin_jsonObject



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'app/controllers/caboose/invoices_controller.rb', line 170

def admin_json
  return if !user_is_allowed('invoices', 'edit')    
  invoice = Invoice.find(params[:id])
  if invoice.shipping_address_id.nil?
    sa = Address.create
    invoice.shipping_address_id = sa.id
    invoice.save
  end
  render :json => invoice.as_json(:include => [        
    { :line_items => { :include => { :variant => { :include => :product }}}},
    { :invoice_packages => { :include => [:shipping_package, :shipping_method] }},
    { :discounts => { :include => :gift_card }},
    :customer,
    :shipping_address,
    :billing_address,
    :invoice_transactions
  ])
end

#admin_newObject

GET /admin/invoices/new



49
50
51
52
# File 'app/controllers/caboose/invoices_controller.rb', line 49

def admin_new
  return if !user_is_allowed('invoices', 'add')      
  render :layout => 'caboose/admin'
end

#admin_optionsObject



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'app/controllers/caboose/invoices_controller.rb', line 320

def admin_options
  return if !user_is_allowed('invoices', 'view')
  
  options = []
  case params[:field]
    when 'status'
      statuses = [
        Invoice::STATUS_CART, 
        Invoice::STATUS_PENDING, 
        Invoice::STATUS_READY_TO_SHIP, 
        Invoice::STATUS_PROCESSED,             
        Invoice::STATUS_CANCELED
      ]
      options = statuses.collect{ |s| { 'text' => s.capitalize, 'value' => s }}
    when 'financial-status'
      statuses = [
        Invoice::FINANCIAL_STATUS_PENDING             ,
        Invoice::FINANCIAL_STATUS_AUTHORIZED          ,
        Invoice::FINANCIAL_STATUS_CAPTURED            ,
        Invoice::FINANCIAL_STATUS_REFUNDED            ,
        Invoice::FINANCIAL_STATUS_VOIDED              ,
        Invoice::FINANCIAL_STATUS_PAID_BY_CHECK       ,
        Invoice::FINANCIAL_STATUS_PAID_BY_OTHER_MEANS                
      ]
      options = statuses.collect{ |s| { 'text' => s.capitalize, 'value' => s }}
    when 'payment-terms'
      options = [
        { 'value' => Invoice::PAYMENT_TERMS_PIA   , 'text' => 'Pay In Advance' },
        { 'value' => Invoice::PAYMENT_TERMS_NET7  , 'text' => 'Net 7'          },
        { 'value' => Invoice::PAYMENT_TERMS_NET10 , 'text' => 'Net 10'         },
        { 'value' => Invoice::PAYMENT_TERMS_NET30 , 'text' => 'Net 30'         },
        { 'value' => Invoice::PAYMENT_TERMS_NET60 , 'text' => 'Net 60'         },
        { 'value' => Invoice::PAYMENT_TERMS_NET90 , 'text' => 'Net 90'         },
        { 'value' => Invoice::PAYMENT_TERMS_EOM   , 'text' => 'End of Month'   }            
      ]
  end          
  render :json => options    
end

#admin_printObject



190
191
192
193
194
195
196
197
198
# File 'app/controllers/caboose/invoices_controller.rb', line 190

def admin_print
  return if !user_is_allowed('invoices', 'edit')           
  
  pdf = @site.store_config.custom_invoice_pdf
  pdf = "InvoicePdf" if pdf.nil? || pdf.strip.length == 0                              
  eval("pdf = #{pdf}.new")
  pdf.invoice = Invoice.find(params[:id])             
  send_data pdf.to_pdf, :filename => "invoice_#{pdf.invoice.id}.pdf", :type => "application/pdf", :disposition => "inline"   
end

#admin_print_pendingObject



201
202
203
204
205
206
207
208
209
210
# File 'app/controllers/caboose/invoices_controller.rb', line 201

def admin_print_pending
  return if !user_is_allowed('invoices', 'edit')    
  
  pdf = PendingInvoicesPdf.new
  if params[:print_card_details]
    pdf.print_card_details = params[:print_card_details].to_i == 1
  end
  pdf.invoices = Invoice.where(:site_id => @site.id, :status => Invoice::STATUS_PENDING).all      
  send_data pdf.to_pdf, :filename => "pending_invoices.pdf", :type => "application/pdf", :disposition => "inline"            
end

#admin_refundObject



151
152
153
154
155
156
157
158
# File 'app/controllers/caboose/invoices_controller.rb', line 151

def admin_refund
  return if !user_is_allowed('invoices', 'edit')

  invoice = Invoice.find(params[:id])
  resp = invoice.refund 
  
  render :json => resp            
end

#admin_resend_confirmationObject



161
162
163
164
165
166
167
# File 'app/controllers/caboose/invoices_controller.rb', line 161

def admin_resend_confirmation
  if Invoice.find(params[:id]).resend_confirmation
    render :json => { success: "Confirmation re-sent successfully." }
  else
    render :json => { error: "There was an error re-sending the email." }
  end
end

#admin_send_for_authorizationObject



282
283
284
285
286
287
# File 'app/controllers/caboose/invoices_controller.rb', line 282

def admin_send_for_authorization
  return if !user_is_allowed('invoices', 'edit')
  invoice = Invoice.find(params[:id])
  invoice.delay(:queue => 'caboose_store').send_payment_authorization_email      
  render :json => { :success => true }
end

#admin_summary_reportObject

GET /admin/invoices/summary-report



309
310
311
312
313
314
315
316
317
# File 'app/controllers/caboose/invoices_controller.rb', line 309

def admin_summary_report
  return if !user_is_allowed('invoices', 'view')

  @d1 = params[:d1] ? DateTime.strptime("#{params[:d1]} 00:00:00", '%Y-%m-%d %H:%M:%S') : DateTime.strptime(DateTime.now.strftime("%Y-%m-01 00:00:00"), '%Y-%m-%d %H:%M:%S')
  @d2 = params[:d2] ? DateTime.strptime("#{params[:d2]} 00:00:00", '%Y-%m-%d %H:%M:%S') : @d1 + 1.month      
  @rows = InvoiceReporter.summary_report(@site.id, @d1, @d2)
  
  render :layout => 'caboose/admin'    
end

#admin_updateObject



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'app/controllers/caboose/invoices_controller.rb', line 213

def admin_update
  return if !user_is_allowed('invoices', 'edit')
  
  resp = Caboose::StdClass.new({'attributes' => {}})
  invoice = Invoice.find(params[:id])    
        
  save = true
  fields_to_log = ['tax','handling','custom_discount','financial_status','customer_id','notes','customer_notes','payment_terms','date_due','status']            
  params.each do |name,value|
    if fields_to_log.include?(name)                                                  
      InvoiceLog.create(
        :invoice_id     => invoice.id,
        :user_id        => logged_in_user.id,
        :date_logged    => DateTime.now.utc,
        :invoice_action => InvoiceLog::ACTION_INVOICE_UPDATED,
        :field          => name,
        :old_value      => invoice[name.to_sym],
        :new_value      => value                                                                  
      )
    end
    case name
      when 'tax' 
        invoice.tax = value
        invoice.total = invoice.calculate_total          
      when 'handling'
        invoice.handling = value
        invoice.total = invoice.calculate_total
      when 'custom_discount' 
        invoice.custom_discount = value
        invoice.discount = invoice.calculate_discount
        invoice.total = invoice.calculate_total
      when 'status'            
        invoice.status = value             
        invoice.date_processed = DateTime.now.utc if value == Invoice::STATUS_PROCESSED
        
      when 'financial_status'    then invoice.financial_status = value
      when 'customer_id'         then invoice.customer_id      = value          
      when 'notes'               then invoice.notes            = value
      when 'customer_notes'      then invoice.customer_notes   = value                    
      when 'payment_terms'       then invoice.payment_terms    = value          
      when 'date_due'            then invoice.date_due         = value
                        
    end                        
  end

  #invoice.calculate
  #invoice.calculate_total
  #resp.attributes['total'] = { 'value' => invoice.total }
  
  resp.success = save && invoice.save      
  render :json => resp
end

#admin_voidObject



141
142
143
144
145
146
147
148
# File 'app/controllers/caboose/invoices_controller.rb', line 141

def admin_void
  return if !user_is_allowed('invoices', 'edit')
        
  invoice = Invoice.find(params[:id])
  resp = invoice.void

  render :json => resp
end

#capture_fundsObject



108
109
110
111
112
113
114
115
116
117
118
# File 'app/controllers/caboose/invoices_controller.rb', line 108

def capture_funds
  return if !user_is_allowed('invoices', 'edit')
       
  invoice = Invoice.find(params[:id])
  resp = invoice.capture_funds   
  
  # Tell taxcloud the invoice was captured
  #Caboose::TaxCalculator.captured(invoice)
  
  render :json => resp
end

#refresh_transactionsObject



35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/controllers/caboose/invoices_controller.rb', line 35

def refresh_transactions      
  return if !user_is_allowed('invoices', 'add')
  
  resp = Caboose::StdClass.new
              
  invoice = Invoice.find(params[:id])
  invoice.refresh_transactions            
  resp.financial_status = invoice.financial_status
  resp.invoice_transactions = invoice.invoice_transactions.reorder(:date_processed).all
  
  render :json => resp
end