Class: Caboose::ProductsController

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

Instance Method Summary collapse

Methods inherited from ApplicationController

#add_ga_event, #admin_bulk_add, #admin_bulk_delete, #admin_bulk_update, #admin_edit, #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

POST /admin/products



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'app/controllers/caboose/products_controller.rb', line 426

def admin_add
  return if !user_is_allowed('products', 'add')
  
  resp = Caboose::StdClass.new
  name = params[:name]
  
  if name.length == 0
    resp.error = "The title cannot be empty."
  else
    p = Product.new(:site_id => @site.id, :title => name)
    mc = MediaCategory.where(:site_id => @site.id).where("parent_id IS NULL").exists? ? MediaCategory.where(:site_id => @site.id).where("parent_id IS NULL").last : MediaCategory.create(:name => "Media", :site_id => @site.id)
    pc = MediaCategory.where(:name => "Products", :site_id => @site.id).exists? ? MediaCategory.where(:name => "Products", :site_id => @site.id).last : MediaCategory.create(:name => "Products", :site_id => @site.id, :parent_id => mc.id)
    c = MediaCategory.create(:site_id => @site.id, :name => name, :parent_id => pc.id)
    p.media_category_id = c.id
    p.save
    resp.redirect = "/admin/products/#{p.id}/general"
  end
  render :json => resp    
end

#admin_add_imageObject

POST /admin/products/:id/images



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'app/controllers/caboose/products_controller.rb', line 312

def admin_add_image
  return if !user_is_allowed('products', 'edit')
  product_id = params[:id]
  
  if (params[:new_image].nil?)
    render :text => "<script type='text/javascript'>parent.modal.autosize(\"<p class='note error'>You must provide an image.</p>\", 'new_image_message');</script>"
  else    
    img = ProductImage.new
    img.product_id = product_id
    img.image = params[:new_image]
    img.square_offset_x = 0
    img.square_offset_y = 0
    img.square_scale_factor = 1.00
    img.save
    render :text => "<script type='text/javascript'>parent.window.location.reload(true);</script>"
  end
end

#admin_combineObject

POST /admin/products/combine



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'app/controllers/caboose/products_controller.rb', line 478

def admin_combine
  product_ids = params[:product_ids]
  
  p = Product.new
  p.title       = params[:title]
  p.description = params[:description]
  p.option1     = params[:option1]
  p.option2     = params[:option2]
  p.option3     = params[:option3]      
  p.default1    = params[:default1]
  p.default2    = params[:default2]
  p.default3    = params[:default3]
  p.status      = 'Active'
  p.save
  
  product_ids.each do |pid|
    p = Product.find(pid)
    p.variants.each do |v|
    end
  end
end

#admin_combine_assign_titleObject

GET /admin/products/combine-step2



474
475
# File 'app/controllers/caboose/products_controller.rb', line 474

def admin_combine_assign_title
end

#admin_combine_select_productsObject

GET /admin/products/combine



470
471
# File 'app/controllers/caboose/products_controller.rb', line 470

def admin_combine_select_products
end

#admin_deleteObject

DELETE /admin/products/:id



447
448
449
450
451
452
453
454
455
# File 'app/controllers/caboose/products_controller.rb', line 447

def admin_delete
  return if !user_is_allowed('products', 'delete')
  p = Product.find(params[:id])
  p.status = 'Deleted'
  p.save
  render :json => Caboose::StdClass.new({
    :redirect => '/admin/products'
  })
end

#admin_delete_formObject

GET /admin/products/:id/delete



345
346
347
348
349
# File 'app/controllers/caboose/products_controller.rb', line 345

def admin_delete_form
  return if !user_is_allowed('products', 'edit')    
  @product = Product.find(params[:id])
  render :layout => 'caboose/admin'
end

#admin_edit_categoriesObject

GET /admin/products/:id/categories



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

def admin_edit_categories
  return if !user_is_allowed('products', 'edit')
  @product = Product.find(params[:id])
  @top_categories = Category.where(:parent_id => 1).reorder('name').all
  @selected_ids = @product.categories.collect{ |cat| cat.id }
  render :layout => 'caboose/admin'
end

#admin_edit_collectionsObject

GET /admin/products/:id/collections



331
332
333
334
335
# File 'app/controllers/caboose/products_controller.rb', line 331

def admin_edit_collections
  return if !user_is_allowed('products', 'edit')    
  @product = Product.find(params[:id])
  render :layout => 'caboose/admin'
end

#admin_edit_descriptionObject

GET /admin/products/:id/description



260
261
262
263
264
# File 'app/controllers/caboose/products_controller.rb', line 260

def admin_edit_description   
  return if !user_is_allowed('products', 'edit')    
  @product = Product.find(params[:id])
  render :layout => 'caboose/admin'
end

#admin_edit_generalObject

GET /admin/products/:id/general



253
254
255
256
257
# File 'app/controllers/caboose/products_controller.rb', line 253

def admin_edit_general
  return if !user_is_allowed('products', 'edit')    
  @product = Product.find(params[:id])
  render :layout => 'caboose/admin'
end

#admin_edit_imagesObject

GET /admin/products/:id/images



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
308
309
# File 'app/controllers/caboose/products_controller.rb', line 283

def admin_edit_images    
  return if !user_is_allowed('products', 'edit')    
  @product = Product.find(params[:id])  
  config = YAML.load(File.read(Rails.root.join('config', 'aws.yml')))[Rails.env]      
  access_key = config['access_key_id']
  secret_key = config['secret_access_key']
  bucket     = config['bucket']      
  policy = {        
    "expiration" => 1.hour.from_now.utc.xmlschema,
    "conditions" => [
      { "bucket" => "#{bucket}-uploads" },          
      { "acl" => "public-read" },
      [ "starts-with", "$key", '' ],      
      [ 'starts-with', '$name', '' ],   
      [ 'starts-with', '$Filename', '' ],          
    ]
  }
  @policy = Base64.encode64(policy.to_json).gsub(/\n/,'')      
  @signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), secret_key, @policy)).gsub("\n","")
  @s3_upload_url = "https://#{bucket}-uploads.s3.amazonaws.com/"
  @aws_access_key_id = access_key                            
      
  @top_media_category = @product.media_category.parent
  @media_category = @product.media_category

  render :layout => 'caboose/admin'
end

#admin_edit_optionsObject

GET /admin/products/:id/options



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

def admin_edit_options
  return if !user_is_allowed('products', 'edit')    
  @product = Product.find(params[:id])
  render :layout => 'caboose/admin'          
end

#admin_edit_seoObject

GET /admin/products/:id/seo



338
339
340
341
342
# File 'app/controllers/caboose/products_controller.rb', line 338

def admin_edit_seo
  return if !user_is_allowed('products', 'edit')    
  @product = Product.find(params[:id])
  render :layout => 'caboose/admin'
end

#admin_indexObject

GET /admin/products



151
152
153
154
155
156
157
158
159
160
161
162
163
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
# File 'app/controllers/caboose/products_controller.rb', line 151

def admin_index
  return if !user_is_allowed('products', 'view')
  
  # Temporary patch for vendor name sorting; Fix this
  params[:sort] = 'store_vendors.name' if params[:sort] == 'vendor'
  
  @gen = Caboose::PageBarGenerator.new(params, {
    'site_id'        => @site.id,
    'vendor_name'    => '',
    'search_like'    => '', 
    'category_id'    => '',
    'category_name'  => '',
    'vendor_id'      => '',        
    'vendor_status'  => '',
    'price_gte'      => '',
    'price_lte'      => '',        
    'variant_status' => '',          
    'price'          => params[:filters] && params[:filters][:missing_prices] ? 0 : ''
  }, {
    'model'          => 'Caboose::Product',
    'sort'           => 'title',
    'desc'           => false,
    'base_url'       => '/admin/products',
    'items_per_page' => 25,
    'use_url_params' => false,
    
    'abbreviations' => {
      'search_like' => 'store_products.title_concat_vendor_name_like'
    },
    
    'includes' => {                           
      'category_id'    => [ 'categories' , 'id'     ],
      'category_name'  => [ 'categories' , 'name'   ],
      'vendor_id'      => [ 'vendor'     , 'id'     ],
      'vendor_name'    => [ 'vendor'     , 'name'   ],
      'vendor_status'  => [ 'vendor'     , 'status' ],
      'price_gte'      => [ 'variants'   , 'price'  ],
      'price_lte'      => [ 'variants'   , 'price'  ],
      'price'          => [ 'variants'   , 'price'  ],
      'variant_status' => [ 'variants'   , 'status' ]
    }
  })
  
  # Make a copy of all the items; so it can be filtered more
  @all_products = @gen.all_records      
  
  # Apply any extra filters
  if params[:filters]
    @all_products = @all_products.includes(:product_images).where('store_product_images.id IS NULL') if params[:filters][:missing_images]
    @all_products = @all_products.where('vendor_id IS NULL') if params[:filters][:no_vendor]
  end
  
  
  # Get the correct page of the results
  @products = @all_products.limit(@gen.limit).offset(@gen.offset)
  @category_options = Category.options(@site.id)
  
  render :layout => 'caboose/admin'
end

#admin_jsonObject

GET /admin/products/json



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

def admin_json
  return if !user_is_allowed('products', 'view')
  
  # Temporary patch for vendor name sorting; Fix this
  params[:sort] = 'store_vendors.name' if params[:sort] == 'vendor'
  
  pager = Caboose::PageBarGenerator.new(params, {
    'site_id'      => @site.id,
    'vendor_name'  => '',
    'search_like'  => '',
    'category_id'  => '',
    'price'        => params[:filters] && params[:filters][:missing_prices] ? 0 : ''
  }, {
    'model'          => 'Caboose::Product',
    'sort'           => 'title',
    'desc'           => false,
    'base_url'       => '/admin/products',
    'items_per_page' => 25,
    'use_url_params' => false,        
    'abbreviations' => {
      'search_like' => 'store_products.title_concat_vendor_name_like'
    },        
    'includes' => {
      'category_id'  => [ 'categories' , 'id'    ],
      'vendor_name'  => [ 'vendor'     , 'name'  ],
      'price'        => [ 'variants'   , 'price' ]
    }
  })
  render :json => {
    :pager => pager,
    :models => pager.items
  }      
end

#admin_json_singleObject

GET /admin/products/:id/json



247
248
249
250
# File 'app/controllers/caboose/products_controller.rb', line 247

def admin_json_single
  p = Product.find(params[:id])
  render :json => p      
end

#admin_newObject

GET /admin/products/new



420
421
422
423
# File 'app/controllers/caboose/products_controller.rb', line 420

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

#admin_sortObject

GET /admin/products/sort



501
502
503
504
505
506
# File 'app/controllers/caboose/products_controller.rb', line 501

def admin_sort
  #@products   = Product.active
  #@vendors    = Vendor.active
  #@categories = Category.all      
  render :layout => 'caboose/admin'
end

#admin_stackable_group_optionsObject

GET /products/stackable-group-options



464
465
466
467
# File 'app/controllers/caboose/products_controller.rb', line 464

def admin_stackable_group_options
  arr = ['Active', 'Inactive', 'Deleted']
  render :json => arr.collect{ |status| { :value => status, :text => status }}      
end

#admin_status_optionsObject

GET /products/status-options



458
459
460
461
# File 'app/controllers/caboose/products_controller.rb', line 458

def admin_status_options
  arr = ['Active', 'Inactive', 'Deleted']      
  render :json => arr.collect{ |status| { :value => status, :text => status }}
end

#admin_updateObject

PUT /admin/products/:id



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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'app/controllers/caboose/products_controller.rb', line 352

def admin_update
  return if !user_is_allowed('products', 'edit')
  
  resp = Caboose::StdClass.new({'attributes' => {}})
  product = Product.find(params[:id])    
  
  save = true    
  params.each do |name,value|
    case name
      when 'site_id'            then product.site_id            = value
      when 'vendor_id'          then product.vendor_id          = value
      when 'alternate_id'       then product.alternate_id       = value          
      when 'title'
        product.title = value
        c = MediaCategory.where(:id => product.media_category_id).last
        c.name = value
        c.save
      when 'caption'            then product.caption            = value
      when 'featured'           then product.featured           = value
      when 'description'        then product.description        = value          
      when 'vendor_id'          then product.vendor_id          = value
      when 'handle'             then product.handle             = value
      when 'seo_title'          then product.seo_title          = value
      when 'seo_description'    then product.seo_description    = value
      when 'status'             then product.status             = value
      when 'category_id'        then product.toggle_category(value[0], value[1])
      when 'stackable_group_id' then product.stackable_group_id = value
      when 'allow_gift_wrap'    then product.allow_gift_wrap    = value
      when 'gift_wrap_price'    then product.gift_wrap_price    = value
      when 'option1'            then product.option1            = value
      when 'option2'            then product.option2            = value
      when 'option3'            then product.option3            = value
      when 'default1'
        product.default1 = value
        Variant.where(:product_id => product.id, :option1 => nil).each do |p|
          p.option1 = value
          p.save
        end
      when 'default2'
        product.default2 = value
        Variant.where(:product_id => product.id, :option2 => nil).each do |p|
          p.option2 = value
          p.save
        end
      when 'default3'
        product.default3 = value
        Variant.where(:product_id => product.id, :option3 => nil).each do |p|
          p.option3 = value
          p.save
        end          
      when 'date_available'
        if value.strip.length == 0
          product.date_available = nil
        else
          begin
            product.date_available = DateTime.parse(value)
          rescue
            resp.error = "Invalid date"
            save = false
          end
        end          
    end
  end
  resp.success = save && product.save
  render :json => resp
end

#admin_update_sort_orderObject

PUT /admin/categories/:category_id/products/sort-order



509
510
511
512
513
514
515
516
517
# File 'app/controllers/caboose/products_controller.rb', line 509

def admin_update_sort_order
  cat_id = params[:category_id]      
  params[:product_ids].each_with_index do |product_id, i|
    cm = CategoryMembership.where(:category_id => cat_id, :product_id => product_id).first
    cm.sort_order = i
    cm.save
  end      
  render :json => { :success => true }
end

#admin_update_vendor_statusObject

GET /admin/products/update-vendor-status/:id



144
145
146
147
148
# File 'app/controllers/caboose/products_controller.rb', line 144

def admin_update_vendor_status
  vendor = Vendor.find(params[:id])
  vendor.status = params[:status]
  render :json => vendor.save
end

#api_detailsObject

GET /api/products/:id



529
530
531
532
# File 'app/controllers/caboose/products_controller.rb', line 529

def api_details
  p = Product.where(:id => params[:id]).first
  render :json => p ? p : { :error => 'Invalid product ID' }
end

#api_indexObject

GET /api/products



524
525
526
# File 'app/controllers/caboose/products_controller.rb', line 524

def api_index
  render :json => Product.where(:status => 'Active')
end

#api_variantsObject

GET /api/products/:id/variants



535
536
537
538
# File 'app/controllers/caboose/products_controller.rb', line 535

def api_variants
  p = Product.where(:id => params[:id]).first
  render :json => p ? p.variants : { :error => 'Invalid product ID' }
end

#indexObject

GET /products || GET /products/:id



13
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
39
40
41
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
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
# File 'app/controllers/caboose/products_controller.rb', line 13

def index
  
  # If id exists, is an integer and a product exists with the specified id then get the product
  if params[:id]        
    if params[:id] == 'sales'
      products = Caboose::Product.where(:site_id => @site.id, :status => Caboose::Product::STATUS_ACTIVE, :on_sale => true).all      
      @sale_categories = {}        
      products.each do |p|
        cat = 'Uncategorized'
        if p.categories.count > 0
          cats = p.categories.last.ancestry.collect{ |a| a.name }
          cats.shift
          cat = cats.join(' > ')
        end
        @sale_categories[cat] = [] if @sale_categories[cat].nil?
        @sale_categories[cat] << p
      end
      add_ga_event('Products', 'View', 'Sales')
      render 'caboose/products/sales' and return
      
    elsif params[:id].to_i > 0 && Product.exists?(params[:id])
      @product = Product.find(params[:id])
      render 'product/not_available' and return if @product.status == 'Inactive'
      
      @category       = @product.categories.first
      @review         = Review.new
      @reviews        = Review.where(:product_id => @product.id).limit(10).order("id DESC") || nil
      @logged_in_user = logged_in_user
      
      add_ga_event('Products', 'View', "Product #{@product.id}")
      render 'caboose/products/details' and return
    end
  end
  
  # Filter params from url
  url_without_params = request.fullpath.split('?').first
  
  # Find the category
  cat = Category.where(:site_id => @site.id, :url => url_without_params).first
  if cat.nil?
    cat = Category.where(:site_id => @site.id, :url => '/products').first
    cat = Category.create(:site_id => @site.id, :url => '/products') if cat.nil?          
  end
        
  # Set category ID
  params['category_id'] = cat.id
  
  # If this is the top-most category, collect all it's immediate children IDs
  params['category_id'] = cat.children.collect { |child| child.id } if cat.id == 1
  
  # Shove the original category ID into the first position if the param is an array
  params['category_id'].unshift(category.id) if params['category_id'].is_a?(Array)
  
  # Otherwise looking at a category or search parameters
  @pager = Caboose::Pager.new(params, {
    'site_id'         => @site.id,
    'on_sale'         => '',
    'category_id'     => '',
    'vendor_id'       => '',
    'vendor_name'     => '',
    'vendor_status'   => 'Active',
    'status'          => 'Active',
    'variant_status'  => 'Active',
    'price_gte'       => '',
    'price_lte'       => '',
    'alternate_id'    => '',
    'search_like'     => '',
    'cm_category_id'  => cat.id # This filters the CategoryMembership object that we'll be sorting on
  }, {
    'model'           => 'Caboose::Product',
    #'sort'            => if params[:sort] then params[:sort] else 'store_products.sort_order' end,
    #'sort'            => if params[:sort] then params[:sort] else 'store_category_memberships.sort_order' end,
    'sort'            => 'store_category_memberships.sort_order',
    'base_url'        => url_without_params,
    'items_per_page'  => 15,
    'use_url_params'  => false,
    
    'abbreviations'   => {
      'search_like'   => 'title_concat_store_products.alternate_id_concat_vendor_name_concat_category_name_like',
    },
    
    'includes' => {
      'cm_category_id'  => [ 'category_memberships' , 'category_id' ],          
      'category_id'     => [ 'categories'           , 'id'          ],
      'category_name'   => [ 'categories'           , 'name'        ],
      'vendor_id'       => [ 'vendor'               , 'id'          ],
      'vendor_name'     => [ 'vendor'               , 'name'        ],
      'vendor_status'   => [ 'vendor'               , 'status'      ],
      'price_gte'       => [ 'variants'             , 'price'       ],
      'price_lte'       => [ 'variants'             , 'price'       ],
      'variant_status'  => [ 'variants'             , 'status'      ]
    }
  })
  
  @sort_options = [
    { :name => 'Default',             :value => 'store_products.sort_order' },
    { :name => 'Price (Low to High)', :value => 'store_variants.price ASC'  },
    { :name => 'Price (High to Low)', :value => 'store_variants.price DESC' },
    { :name => 'Alphabetical (A-Z)',  :value => 'store_products.title ASC'  },
    { :name => 'Alphabetical (Z-A)',  :value => 'store_products.title DESC' },
  ]
  
  SearchFilter.delete_all
  
  @filter   = SearchFilter.find_from_url(request.fullpath, @pager, ['page'])
  @products = @pager.items
  @category = if @filter['category_id'] then Category.find(@filter['category_id'].to_i) else nil end
  
  @pager.set_item_count
  add_ga_event('Products', 'View', "Category #{cat.id}")      
end

#infoObject

GET /product/info



129
130
131
132
133
134
135
136
137
# File 'app/controllers/caboose/products_controller.rb', line 129

def info
  p = Product.find(params[:id])
  render :json => { 
    :product => p,
    :option1_values => p.option1_values,
    :option2_values => p.option2_values,
    :option3_values => p.option3_values
  }
end

#showObject



125
126
# File 'app/controllers/caboose/products_controller.rb', line 125

def show      
end