Class: Caboose::OrdersController

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

Instance Method Summary collapse

Methods inherited from ApplicationController

#before_action, #before_before_action, #hashify_query_string, #init_cart, #logged_in?, #logged_in_user, #login_user, #logout_user, #parse_url_params, #reject_param, #user_is_allowed, #user_is_allowed_to, #validate_cookie, #validate_token, #var, #verify_logged_in

Instance Method Details

#admin_deleteObject

DELETE /admin/orders/:id



246
247
248
249
250
251
252
# File 'app/controllers/caboose/orders_controller.rb', line 246

def admin_delete
  return if !user_is_allowed('orders', 'delete')
  Order.find(params[:id]).destroy
  render :json => Caboose::StdClass.new({
    :redirect => '/admin/orders'
  })
end

#admin_editObject

GET /admin/orders/:id



35
36
37
38
39
# File 'app/controllers/caboose/orders_controller.rb', line 35

def admin_edit
  return if !user_is_allowed('orders', 'edit')
  @order = Order.find(params[:id])
  render :layout => 'caboose/admin'
end

#admin_google_feedObject

GET /admin/orders/google-feed



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'app/controllers/caboose/orders_controller.rb', line 403

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 Order.exists?("status = 'shipped' and date_authorized is not null")
    d1 = Order.where("status = ? and date_authorized is not null", 'shipped').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 order id\ttracking number\tcarrier code\tother carrier name\tship date"]            
  if Order.exists?("status = 'shipped' and date_authorized > '#{d1.strftime("%F %T")}'")
    Order.where("status = ? and date_authorized > ?", 'shipped', d1).reorder(:id).all.each do |order|
      tracking_numbers = order.line_items.collect{ |li| li.tracking_number }.compact.uniq
      tn = tracking_numbers && tracking_numbers.count >= 1 ? tracking_numbers[0] : ""
      tsv << "#{order.id}\t#{tn}\tUPS\t\t#{order.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

GET /admin/orders



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/controllers/caboose/orders_controller.rb', line 5

def admin_index
  return if !user_is_allowed('orders', 'view')
  
  @pager = Caboose::PageBarGenerator.new(params, {
    'customer_id'          => '', 
    'status'               => 'pending',
    'shipping_method_code' => '',
    'id'                   => ''
  }, {
    'model'          => 'Caboose::Order',
    'sort'           => 'id',
    'desc'           => 1,
    'base_url'       => '/admin/orders',
    'use_url_params' => false
  })
  
  @orders    = @pager.items
  @customers = Caboose::User.reorder('last_name, first_name').all
  
  render :layout => 'caboose/admin'
end

#admin_jsonObject

GET /admin/orders/:id/json



159
160
161
162
163
# File 'app/controllers/caboose/orders_controller.rb', line 159

def admin_json
  return if !user_is_allowed('orders', 'edit')    
  order = Order.find(params[:id])
  render :json => order, :include => { :order_line_items => { :include => :variant }}
end

#admin_line_item_status_optionsObject

GET /admin/orders/line-item-status-options



255
256
257
258
259
260
261
262
263
264
265
# File 'app/controllers/caboose/orders_controller.rb', line 255

def admin_line_item_status_options
  arr = ['pending', 'ready to ship', 'shipped', 'backordered', 'canceled']
  options = []
  arr.each do |status|
    options << {
      :value => status,
      :text  => status
    }
  end
  render :json => options
end

#admin_mail_test_gmailObject

GET /admin/orders/test-gmail



397
398
399
400
# File 'app/controllers/caboose/orders_controller.rb', line 397

def admin_mail_test_gmail
  TestMailer.test_gmail.deliver
  render :text => "Sent email to [email protected] on #{DateTime.now.strftime("%F %T")}"
end

#admin_mail_test_infoObject

GET /admin/orders/test-info



391
392
393
394
# File 'app/controllers/caboose/orders_controller.rb', line 391

def admin_mail_test_info
  TestMailer.test_info.deliver
  render :text => "Sent email to [email protected] on #{DateTime.now.strftime("%F %T")}"
end

#admin_newObject

GET /admin/orders/new



28
29
30
31
32
# File 'app/controllers/caboose/orders_controller.rb', line 28

def admin_new
  return if !user_is_allowed('orders', 'add')
  @products = Product.by_title
  render :layout => 'caboose/admin'
end

#admin_printObject

GET /admin/orders/:id/print



166
167
168
169
170
171
172
173
174
175
# File 'app/controllers/caboose/orders_controller.rb', line 166

def admin_print
  return if !user_is_allowed('orders', 'edit')    
   
  pdf = OrderPdf.new
  pdf.order = Order.find(params[:id])             
  send_data pdf.to_pdf, :filename => "order_#{pdf.order.id}.pdf", :type => "application/pdf", :disposition => "inline"
  
  #@order = Order.find(params[:id])
  #render :layout => 'caboose/admin'
end

#admin_refundObject

GET /admin/orders/:id/refund



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

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

  response = Caboose::StdClass.new({
    'refresh' => nil,
    'error' => nil,
    'success' => nil
  })

  order = Order.find(params[:id])

  if order.financial_status != 'captured'
    response.error = "This order hasn't been captured yet, you will need to void instead"
  else
    if PaymentProcessor.refund(order)
      order.update_attributes(
        :financial_status => 'refunded',
        :status => 'cancelled'
      )
      
      response.success = 'Order refunded successfully'
    else
      response.error = 'Error refunding order'
    end
    
    #if order.calculate_net < (order.amount_discounted || 0) || PaymentProcessor.refund(order)
    #  order.financial_status = 'refunded'
    #  order.status = 'refunded'
    #  order.save
    #  
    #  if order.discounts.any?
    #    discount = order.discounts.first
    #    amount_to_refund = order.calculate_net < order.amount_discounted ? order.calculate_net : order.amount_discounted
    #    discount.update_attribute(:amount_current, amount_to_refund + discount.amount_current)
    #  end
    #  
    #  response.success = "Order refunded successfully"
    #else
    #  response.error = "Error refunding order."
    #end
  end

  render json: response
  
  # return if !user_is_allowed('orders', 'edit')
  #     
  # response = Caboose::StdClass.new({
  #   'refresh' => nil,
  #   'error' => nil,
  #   'success' => nil
  # })
  #     
  # order = Order.find(params[:id])
  #     
  # if order.financial_status != 'captured'
  #   response.error = "This order hasn't been captured yet, you will need to void instead"
  # else
  #   if PaymentProcessor.refund(order)
  #     order.financial_status = 'refunded'
  #     order.status = 'refunded'
  #     order.save
  #     
  #     # Add the variant quantities ordered back
  #     order.cancel
  #     
  #     response.success = "Order refunded successfully"
  #   else
  #     response.error = "Error refunding order."
  #   end
  # end
  #     
  # render :json => response
end

#admin_resend_confirmationObject

POST /admin/orders/:id/resend-confirmation



150
151
152
153
154
155
156
# File 'app/controllers/caboose/orders_controller.rb', line 150

def admin_resend_confirmation
  if Order.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_status_optionsObject

GET /admin/orders/status-options



377
378
379
380
381
382
383
384
385
386
387
388
# File 'app/controllers/caboose/orders_controller.rb', line 377

def admin_status_options
  return if !user_is_allowed('categories', 'view')
  statuses = ['cart', 'pending', 'ready to ship', 'shipped', 'canceled']
  options = []
  statuses.each do |s|
    options << {
      'text' => s,
      'value' => s
    }
  end       
  render :json => options    
end

#admin_updateObject

PUT /admin/orders/:id



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

def admin_update
  return if !user_is_allowed('orders', 'edit')
  
  resp = Caboose::StdClass.new({'attributes' => {}})
  order = Order.find(params[:id])    
  
  save = true    
  params.each do |name,value|
    case name
      when 'tax'
        order.tax = value          
      when 'shipping'
        order.shipping = value
      when 'handling'
        order.handling = value
      when 'discount'
        order.discount = value        
      when 'status'
        order.status = value
        resp.attributes['status'] = {'text' => value}
    end
  end
  order.calculate_total    
  resp.success = save && order.save
  render :json => resp
end

#admin_update_line_itemObject

PUT /admin/orders/:order_id/line-items/:id



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

def admin_update_line_item
  return if !user_is_allowed('orders', 'edit')
  
  resp = Caboose::StdClass.new({'attributes' => {}})
  li = OrderLineItem.find(params[:id])    
  
  save = true
  send_status_email = false    
  params.each do |name,value|
    case name
      when 'quantity'
        li.quantity = value
        li.save
                      
        # Recalculate everything
        r = ShippingCalculator.rate(li.order, li.order.shipping_method_code)
        li.order.shipping = r['negotiated_rate'] / 100
        li.order.handling = (r['negotiated_rate'] / 100) * 0.05
        tax_rate = TaxCalculator.tax_rate(li.order.shipping_address)
        li.order.tax = li.order.subtotal * tax_rate
        li.order.calculate_total
        li.order.save
        
      when 'tracking_number'
        li.tracking_number = value
        send_status_email = true
      when 'status'
        li.status = value
        resp.attributes['status'] = {'text' => value}
        send_status_email = true
    end
  end
  if send_status_email       
    OrdersMailer.customer_status_updated(li.order).deliver
  end
  resp.success = save && li.save
  render :json => resp
end

#admin_voidObject

GET /admin/orders/:id/void



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'app/controllers/caboose/orders_controller.rb', line 42

def admin_void
  return if !user_is_allowed('orders', 'edit')
  
  response = Caboose::StdClass.new({
    'refresh' => nil,
    'error' => nil,
    'success' => nil
  })
  
  order = Order.find(params[:id])
  
  if order.financial_status == 'captured'
    response.error = "This order has already been captured, you will need to refund instead"
  else
    if PaymentProcessor.void(order)
      order.update_attributes(
        :financial_status => 'voided',
        :status => 'cancelled'
      )
      
      # Add the variant quantities ordered back
      #order.cancel
      
      response.success = "Order voided successfully"
    else
      response.error = "Error voiding order."
    end
  end

  render :json => response
end

#capture_fundsObject

GET /admin/orders/:id/capture



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'app/controllers/caboose/orders_controller.rb', line 268

def capture_funds
  return if !user_is_allowed('orders', 'edit')
  
  response = Caboose::StdClass.new({
    'refresh' => nil,
    'error'   => nil,
    'success' => nil
  })
  
  order = Order.find(params[:id])
  
  if order.financial_status == 'captured'
    resp.error = "Funds for this order have already been captured."    
  elsif order.total > order.auth_amount
    resp.error = "The order total exceeds the authorized amount."
  else
    if PaymentProcessor.capture(order)
      order.update_attribute(:financial_status, 'captured')
      response.success = 'Captured funds successfully'
    else
      response.error = 'Error capturing funds'
    end
      
    #if (order.discounts.any? && order.total < order.discounts.first.amount_current) || PaymentProcessor.capture(order)
    #  order.financial_status = 'captured'
    #  order.save
    #  
    #  if order.discounts.any?
    #    order.update_attribute(:amount_discounted, order.discounts.first.amount_current)
    #    order.update_gift_cards
    #  end
    #  
    #  response.success = "Captured funds successfully"
    #else
    #  response.error = "Error capturing funds."
    #end
  end
  
  render :json => response
end