stocks_datatable.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. class StocksDatatable
  2. delegate :params, :image_tag, :available_products_path, :products_initial_stock_path, to: :@view
  3. def initialize(view, user, showcolumns)
  4. @view = view
  5. @current_user = user
  6. @showcolumns = showcolumns
  7. end
  8. def as_json(_options = {})
  9. total =
  10. if @current_user.usertype == 'S'
  11. WarehouseStock.activos.where(warehouse_id: @current_user.warehouse_id)
  12. else
  13. AvailableProduct.activos.where(pointsale_id: @current_user.pointsale_id.present? ? @current_user.pointsale_id : params[:pointsale])
  14. end
  15. {
  16. sEcho: params[:sEcho].to_i,
  17. iTotalRecords: total.size,
  18. iTotalDisplayRecords: stock.total_entries,
  19. aaData: data
  20. }
  21. end
  22. private
  23. def data
  24. stock.map do |available|
  25. img = available.product.img_product? ? available.product.img_product.url(:small) : "/images/small/missing.png"
  26. category = available.product.categories[0]
  27. {
  28. 'DT_RowId' => "availableProduct_#{available.id}",
  29. '0' => '<input class="form-control checkboxes" type="checkbox"/>',
  30. '1' => (image_tag img),
  31. '2' => available.product.sku,
  32. '3' => available.product.name + '<br>' + available.product.display_attributes,
  33. '4' => (category.parent_id.zero? ? category.category : category.parent.category),
  34. '5' => (category.parent_id != 0 ? category.category : ' '),
  35. '6' => (@showcolumns == "minMax" ? available.stock_min : available.stock),
  36. '7' => (@showcolumns == "minMax" ? available.stock_max : nil)
  37. }.compact.reject { |_k, v| v.nil? }
  38. end
  39. end
  40. def stock
  41. @stock ||= fetch_stock
  42. end
  43. def fetch_stock
  44. stock =
  45. if @current_user.usertype == 'S'
  46. WarehouseStock.activos.includes(:product, :categories).where(warehouse_id: @current_user.warehouse_id).order('products.name')
  47. else
  48. AvailableProduct.activos.includes(:product, :categories).where(pointsale_id: @current_user.pointsale_id.present? ? @current_user.pointsale_id : params[:pointsale]).order('products.name')
  49. end
  50. stock = stock.page(page).per_page(per_page)
  51. stock = stock.where("products.sku ilike :search or products.name ilike :search", search: "%#{params[:busqueda]}%").order('products.name') unless params[:busqueda].blank?
  52. stock
  53. end
  54. def page
  55. params[:start].to_i / per_page + 1
  56. end
  57. def per_page
  58. params[:length].to_i > 0 ? params[:length].to_i : 20
  59. end
  60. def sort_column
  61. columns = %w[name]
  62. columns[params[:iSortCol_0].to_i]
  63. end
  64. def sort_direction
  65. params[:sSortDir_0] == "desc" ? "desc" : "asc"
  66. end
  67. end