stocks_datatable.rb 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. {
  27. 'DT_RowId' => "availableProduct_#{available.id}",
  28. '0' => '<input class="form-control checkboxes" type="checkbox"/>',
  29. '1' => (image_tag img),
  30. '2' => available.product.sku,
  31. '3' => available.product.name + '<br>' + available.product.display_attributes,
  32. '4' => (available.product.category.parent_id.zero? ? available.product.category.category : available.product.category.parent.category),
  33. '5' => (available.product.category.parent_id != 0 ? available.product.category.category : ' '),
  34. '6' => (@showcolumns == "minMax" ? available.stock_min : available.stock),
  35. '7' => (@showcolumns == "minMax" ? available.stock_max : nil)
  36. }.compact.reject { |_k, v| v.nil? }
  37. end
  38. end
  39. def stock
  40. @stock ||= fetch_stock
  41. end
  42. def fetch_stock
  43. stock =
  44. if @current_user.usertype == 'S'
  45. WarehouseStock.activos.includes(:product, :categories).where(warehouse_id: @current_user.warehouse_id).order('products.name')
  46. else
  47. AvailableProduct.activos.includes(:product, :categories).where(pointsale_id: @current_user.pointsale_id.present? ? @current_user.pointsale_id : params[:pointsale]).order('products.name')
  48. end
  49. stock = stock.page(page).per_page(per_page)
  50. stock = stock.where("products.sku ilike :search or products.name ilike :search", search: "%#{params[:busqueda]}%").order('products.name') unless params[:busqueda].blank?
  51. stock
  52. end
  53. def page
  54. params[:start].to_i / per_page + 1
  55. end
  56. def per_page
  57. params[:length].to_i > 0 ? params[:length].to_i : 20
  58. end
  59. def sort_column
  60. columns = %w[name]
  61. columns[params[:iSortCol_0].to_i]
  62. end
  63. def sort_direction
  64. params[:sSortDir_0] == "desc" ? "desc" : "asc"
  65. end
  66. end