class AvailableProductsDatatable
delegate :params, :fa_icon, :available_products_path, :number_to_currency, to: :@view
def initialize(view, pointsale)
@view = view
@pointsale = pointsale
end
def as_json(*)
{
sEcho: params[:sEcho].to_i,
iTotalRecords: params[:table] == 'in_pointsale' ? @pointsale.products.activos_children.size : products.total_entries,
iTotalDisplayRecords: products.total_entries,
aaData: data
}
end
private
def data
if params[:table] == 'in_pointsale'
products.map do |available|
{
'DT_RowId' => "available_#{available.id}",
'0' => '',
'1' => available.product.sku,
'2' => get_display_name(available.product),
'3' => (available.product.category.parent_id.zero? ? available.product.category.category : available.product.category.parent.category),
'4' => (available.product.category.parent_id != 0 ? available.product.category.category : ' '),
'5' => available.stock
}.compact.reject { |_k, v| v.nil? }
end
else
products.map do |product|
{
'DT_RowId' => "product_#{product.id}",
'0' => '',
'1' => product.sku,
'2' => get_display_name(product),
'3' => (product.category.parent_id.zero? ? product.category.category : product.category.parent.category),
'4' => (product.category.parent_id != 0 ? product.category.category : ' '),
'5' => number_to_currency(product.price_sale, precision: 2)
}.compact.reject { |_k, v| v.nil? }
end
end
end
def get_display_name(product)
name = "
"
name += "#{product.display_attributes}
" if product.display_attributes.present?
name += ": #{product.barcode}
" if product.barcode.present?
name += "Descripción: #{product.description}" if product.barcode.present?
name
end
def products
@products ||= fetch_products
end
def fetch_products
products =
if params[:table] == 'in_pointsale'
AvailableProduct.joins(:product, :categories).activos.where(pointsale_id: params[:id]).activos
else
products_in_pointsale = @pointsale.products.activos_children.pluck(:id)
Product.joins(:category).activos_children.where.not(id: products_in_pointsale).order('products.name')
end
products = products.page(page).per_page(per_page)
search = params[:busqueda]
name_searched =
if search.include? ':'
search[0, search.index(':') - 1]
else
search
end
unless search.blank?
products = products.where("products.sku ilike :search or products.name ilike :search", search: "%#{name_searched}%").order('products.name')
if search.include? ':'
attribute = search[search.index(':') + 1, search.length]
products = products.where('products.attributes_json ilike :attribute', attribute: "%#{attribute}%")
end
end
products
end
def page
params[:start].to_i / per_page + 1
end
def per_page
params[:length].to_i > 0 ? params[:length].to_i : 20
end
def sort_column
columns = %w[name]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end