Class: Caboose::CheckoutController

Inherits:
ApplicationController show all
Defined in:
app/controllers/caboose/checkout_controller.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#add_ga_event, #admin_add, #admin_bulk_add, #admin_bulk_delete, #admin_bulk_update, #admin_delete, #admin_edit, #admin_index, #admin_json, #admin_json_single, #admin_update, #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

#addressObject



284
285
286
287
288
289
# File 'app/controllers/caboose/checkout_controller.rb', line 284

def address
  render :json => {
    :shipping_address => @invoice.shipping_address,
    :billing_address => @invoice.billing_address
  }
end

#attach_guestObject



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'app/controllers/caboose/checkout_controller.rb', line 423

def attach_guest
  resp = Caboose::StdClass.new      
  email = params[:email]      
  
  if email != params[:confirm_email]
    resp.error = "Emails do not match."
  elsif Caboose::User.where(:email => email, :is_guest => false).exists?
    resp.error = "A user with that email address already exists."
  else
    user = Caboose::User.where(:email => email, :is_guest => true).first
    if user.nil?        
      user = Caboose::User.create(:email => email)
      user.is_guest = true
      user.save
      user = Caboose::User.where(:email => email).first
    end                   
    @invoice.customer_id = user.id
    (user)
    
    if !@invoice.valid?        
      resp.errors = @invoice.errors.full_messages
    else
      @invoice.save
      resp.redirect = '/checkout/addresses'
    end
  end
  render :json => resp            
end

#attach_userObject



415
416
417
418
419
420
# File 'app/controllers/caboose/checkout_controller.rb', line 415

def attach_user              
  render :json => { :success => false, :errors => ['User is not logged in'] } and return if !logged_in?
  @invoice.customer_id = logged_in_user.id
  #Caboose.log("Attaching user to invoice: customer_id = #{@invoice.customer_id}")
  render :json => { :success => @invoice.save, :errors => @invoice.errors.full_messages, :logged_in => logged_in? }
end

#confirmObject



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
# File 'app/controllers/caboose/checkout_controller.rb', line 164

def confirm
  render :json => { :error => 'Not logged in.'            } and return if !logged_in?
  #render :json => { :error => 'Invalid billing address.'  } and return if @invoice.billing_address.nil?
  render :json => { :error => 'Invalid shipping address.' } and return if @invoice.has_shippable_items? && @invoice.shipping_address.nil?      
  render :json => { :error => 'Invalid shipping methods.' } and return if @invoice.has_shippable_items? && @invoice.has_empty_shipping_methods?      
  
  resp = Caboose::StdClass.new
  sc = @site.store_config
  
  # Make sure all the variants still exist      
  @invoice.line_items.each do |li|
    v = Variant.where(:id => li.variant_id).first
    if v.nil? || v.status == 'Deleted'
      render :json => { :error => 'One or more of the products you are purchasing are no longer available.' }
      return
    end
  end

  error = false      
  requires_payment = @invoice.line_items.count > 0 && @invoice.total > 0 && @invoice.payment_terms == Invoice::PAYMENT_TERMS_PIA       
  if requires_payment
  
    ot = nil
    case sc.pp_name
      when StoreConfig::PAYMENT_PROCESSOR_AUTHNET
                                
      when StoreConfig::PAYMENT_PROCESSOR_STRIPE
        Stripe.api_key = sc.stripe_secret_key.strip
        begin
          c = Stripe::Charge.create(
            :amount => (@invoice.total * 100).to_i,
            :currency => 'usd',
            :customer => logged_in_user.stripe_customer_id,
            :capture => false,
            :metadata => { :invoice_id => @invoice.id },
            :statement_descriptor => "Invoice ##{@invoice.id}"
          )
        rescue Exception => ex
          render :json => { :error => ex.message }
          return
        end
        ot = Caboose::InvoiceTransaction.create(
          :invoice_id        => @invoice.id,
          :transaction_id    => c.id,
          :transaction_type  => c.captured ? Caboose::InvoiceTransaction::TYPE_AUTHCAP : Caboose::InvoiceTransaction::TYPE_AUTHORIZE,
          :payment_processor => sc.pp_name,
          :amount            => c.amount/100.0,              
          :date_processed    => DateTime.now.utc,              
          :success           => c.status == 'succeeded'
        )                        
    end
    
    if !ot.success
      render :json => { :error => error }
      return        
    else        
      @invoice.financial_status = Invoice::FINANCIAL_STATUS_AUTHORIZED                                                   
      @invoice.take_gift_card_funds
    end
  end
  
  @invoice.status = Invoice::STATUS_PENDING
  @invoice.invoice_number = @site.store_config.next_invoice_number
  
  # 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
  
  # Emit invoice event      
  Caboose.plugin_hook('invoice_authorized', @invoice) if @invoice.total > 0 
  
  # Save the invoice
  @invoice.save
  
  # Decrement quantities of variants
  @invoice.decrement_quantities
  
  # Clear the cart and re-initialize                    
  session[:cart_id] = nil
  init_cart
  
  resp.success = true
  resp.redirect = '/checkout/thanks'      
  render :json => resp
end

#ensure_line_itemsObject



9
10
11
# File 'app/controllers/caboose/checkout_controller.rb', line 9

def ensure_line_items
  redirect_to '/checkout/empty' if @invoice.line_items.empty?
end

#indexObject

Step 1 - Login or register



58
59
60
61
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
# File 'app/controllers/caboose/checkout_controller.rb', line 58

def index            
  if logged_in?
    if @invoice.customer_id.nil?
      @invoice.customer_id = logged_in_user.id
      @invoice.save
    end                        
    #redirect_to '/checkout/addresses'
    #return
    
    @invoice.verify_invoice_packages
    
    # See if any there are any empty invoice packages          
    #@invoice.invoice_packages.each do |op|
    #  count = 0
    #  @invoice.line_items.each do |li|
    #    count = count + 1 if li.invoice_package_id == op.id
    #  end
    #  op.destroy if count == 0
    #end
    #
    ## See if any line items aren't associated with an invoice package
    #line_items_attached = true
    #@invoice.line_items.each do |li|
    #  line_items_attached = false if li.invoice_package_id.nil?
    #end
    #  
    #ops = @invoice.invoice_packages
    #if ops.count == 0 || !line_items_attached
    #  @invoice.calculate
    #  LineItem.where(:invoice_id => @invoice.id).update_all(:invoice_package_id => nil)
    #  InvoicePackage.where(:invoice_id => @invoice.id).destroy_all          
    #  InvoicePackage.create_for_invoice(@invoice)
    #end
  
    #render :file => "caboose/checkout/checkout_#{@site.store_config.pp_name}"
    render :file => "caboose/checkout/checkout"                                                                                                                      
  end
end

#invoice_jsonObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/controllers/caboose/checkout_controller.rb', line 14

def invoice_json            
  render :json => @invoice.as_json(
    :include => [                          
      :customer,
      :shipping_address,
      :billing_address,
      :invoice_transactions,          
      { 
        :line_items => { 
          :include => { 
            :variant => { 
              :include => [
                { :product_images => { :methods => :urls }},
                { :product => { :include => { :product_images => { :methods => :urls }}}}
              ],
              :methods => :title
            }
          }
        }
      },
      { :invoice_packages => { :include => [:shipping_package, :shipping_method] }},          
      { :discounts => { :include => :gift_card }}
    ]        
  )      
end

#shipping_jsonObject

Step 3 - Shipping method



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'app/controllers/caboose/checkout_controller.rb', line 99

def shipping_json
  render :json => { :error => 'Not logged in.'          } and return if !logged_in?
  render :json => { :error => 'No shippable items.'     } and return if !@invoice.has_shippable_items?
  render :json => { :error => 'Empty shipping address.' } and return if @invoice.shipping_address.nil?      
  
  @invoice.calculate
  
  #ops = @invoice.invoice_packages      
  #if params[:recalculate_invoice_packages] || ops.count == 0
  #  # Remove any invoice packages      
  #  LineItem.where(:invoice_id => @invoice.id).update_all(:invoice_package_id => nil)
  #  InvoicePackage.where(:invoice_id => @invoice.id).destroy_all      
  #    
  #  # Calculate what shipping packages we'll need            
  #  InvoicePackage.create_for_invoice(@invoice)
  #end

  # Now get the rates for those packages            
  rates = ShippingCalculator.rates(@invoice)      
  render :json => rates                  
end

#state_optionsObject



268
269
270
271
# File 'app/controllers/caboose/checkout_controller.rb', line 268

def state_options                            
  options = Caboose::States.all.collect { |abbr, state| { 'value' => abbr, 'text' => abbr }}
  render :json => options
end

#stripe_jsonObject



41
42
43
44
45
46
47
48
49
50
51
52
# File 'app/controllers/caboose/checkout_controller.rb', line 41

def stripe_json
  sc = @site.store_config
  u = logged_in_user
  render :json => {
    :stripe_key     => sc.stripe_publishable_key.strip,        
    :customer_id    => u.stripe_customer_id,                   
    :card_last4     => u.card_last4,     
    :card_brand     => u.card_brand,       
    :card_exp_month => u.card_exp_month, 
    :card_exp_year  => u.card_exp_year
  }          
end

#thanksObject



257
258
259
260
261
262
263
# File 'app/controllers/caboose/checkout_controller.rb', line 257

def thanks
  @logged_in_user = logged_in_user
  
  # Find the last invoice for the user
  @last_invoice = Invoice.where(:customer_id => @logged_in_user.id).reorder("id desc").limit(1).first            
  add_ga_event('Ecommerce', 'Checkout', 'Payment', (@last_invoice.total*100).to_i)
end

#update_addressesObject



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'app/controllers/caboose/checkout_controller.rb', line 292

def update_addresses
  
  # Grab or create addresses
  shipping_address = if @invoice.shipping_address then @invoice.shipping_address else Address.new end
  billing_address  = if @invoice.billing_address  then @invoice.billing_address  else Address.new end
        
  has_shippable_items = @invoice.has_shippable_items?
    
  # Shipping address
  if has_shippable_items
    shipping_address.first_name = params[:shipping][:first_name]
    shipping_address.last_name  = params[:shipping][:last_name]
    shipping_address.company    = params[:shipping][:company]
    shipping_address.address1   = params[:shipping][:address1]
    shipping_address.address2   = params[:shipping][:address2]
    shipping_address.city       = params[:shipping][:city]
    shipping_address.state      = params[:shipping][:state]
    shipping_address.zip        = params[:shipping][:zip]
  end
  
  # Billing address
  if has_shippable_items && params[:use_as_billing]
    billing_address.update_attributes(shipping_address.attributes)
  else
    billing_address.first_name = params[:billing][:first_name]
    billing_address.last_name  = params[:billing][:last_name]
    billing_address.company    = params[:billing][:company]
    billing_address.address1   = params[:billing][:address1]
    billing_address.address2   = params[:billing][:address2]
    billing_address.city       = params[:billing][:city]
    billing_address.state      = params[:billing][:state]
    billing_address.zip        = params[:billing][:zip]
  end
  
  # Save address info; generate ids      
  render :json => { :success => false, :errors => shipping_address.errors.full_messages, :address => 'shipping' } and return if has_shippable_items && !shipping_address.save
  render :json => { :success => false, :errors => billing_address.errors.full_messages, :address => 'billing' } and return if !billing_address.save
  
  # Associate address info with invoice
  @invoice.shipping_address_id = shipping_address.id
  @invoice.billing_address_id  = billing_address.id
  
  #render :json => { :redirect => 'checkout/shipping' }
  render :json => { :success => @invoice.save, :errors => @invoice.errors.full_messages }
end

#update_billing_addressObject



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'app/controllers/caboose/checkout_controller.rb', line 391

def update_billing_address
  
  # Grab or create addresses
  ba = @invoice.billing_address
  if ba.nil?
    ba = Address.create
    @invoice.billing_address_id = ba.id
    @invoice.save
  end
                                                    
  ba.first_name = params[:first_name]
  ba.last_name  = params[:last_name]
  ba.company    = params[:company]
  ba.address1   = params[:address1]
  ba.address2   = params[:address2]
  ba.city       = params[:city]
  ba.state      = params[:state]
  ba.zip        = params[:zip]
  ba.save
                    
  render :json => { :success => true }
end

#update_shippingObject



453
454
455
456
457
458
459
460
461
# File 'app/controllers/caboose/checkout_controller.rb', line 453

def update_shipping
  op = InvoicePackage.find(params[:invoice_package_id])
  op.shipping_method_id = params[:shipping_method_id]
  op.total = params[:total]
  op.save
  op.invoice.calculate
                               
  render :json => { :success => true }               
end

#update_shipping_addressObject



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
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
# File 'app/controllers/caboose/checkout_controller.rb', line 339

def update_shipping_address      
  resp = Caboose::StdClass.new
        
  # Grab or create addresses
  sa = @invoice.shipping_address
  if sa.nil?
    sa = Address.create
    @invoice.shipping_address_id = sa.id
    @invoice.save
  end
        
  save = true
  recalc_shipping = false
  params.each do |name, value|
    case name                              
      when 'address1' then recalc_shipping = true if sa.address1 != value
      when 'address2' then recalc_shipping = true if sa.address2 != value          
      when 'city'     then recalc_shipping = true if sa.city     != value
      when 'state'    then recalc_shipping = true if sa.state    != value          
      when 'zip'      then recalc_shipping = true if sa.zip      != value          
    end        
    case name          
      when 'name'           then sa.name          = value          
      when 'first_name'     then sa.first_name    = value
      when 'last_name'      then sa.last_name     = value
      when 'street'         then sa.street        = value
      when 'address1'       then sa.address1      = value
      when 'address2'       then sa.address2      = value
      when 'company'        then sa.company       = value
      when 'city'           then sa.city          = value
      when 'state'          then sa.state         = value
      when 'province'       then sa.province      = value
      when 'province_code'  then sa.province_code = value
      when 'zip'            then sa.zip           = value
      when 'country'        then sa.country       = value
      when 'country_code'   then sa.country_code  = value
      when 'phone'          then sa.phone         = value
    end                 
  end      
  if recalc_shipping
    @invoice.invoice_packages.each do |op|          
      op.shipping_method_id = nil                         
      op.total = nil
      op.save
    end
  end

  resp.success = save && sa.save      
  render :json => resp            
end

#update_stripe_detailsObject

Step 5 - Update Stripe Details



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
# File 'app/controllers/caboose/checkout_controller.rb', line 123

def update_stripe_details
  render :json => false and return if !logged_in?
  
  sc = @site.store_config      
  Stripe.api_key = sc.stripe_secret_key.strip

  u = logged_in_user      
  
  c = nil
  if u.stripe_customer_id
    c = Stripe::Customer.retrieve(u.stripe_customer_id)
    begin          
      c.source = params[:token]
      c.save
    rescue          
      c = nil
    end
  end
  
  if c.nil?
    c = Stripe::Customer.create(
      :source => params[:token],
      :email => u.email,
      :metadata => { :user_id => u.id }          
    )
  end
  
  u.stripe_customer_id = c.id
  u.card_last4     = params[:card][:last4]
  u.card_brand     = params[:card][:brand]  
  u.card_exp_month = params[:card][:exp_month]
  u.card_exp_year  = params[:card][:exp_year]
  u.save
  
  render :json => {
    :success => true,
    :customer_id => u.stripe_customer_id
  }      
end

#verify_totalObject



274
275
276
277
278
279
280
281
# File 'app/controllers/caboose/checkout_controller.rb', line 274

def verify_total
  total = 0.00
  if logged_in?
    @invoice.calculate
    total = @invoice.total
  end
  render :json => total.to_f      
end