Browse Source

added the posibility to change the price of all the variants of a product at the same time

Jose Miguel Ledon Nieblas 8 years ago
parent
commit
0a35234b80

+ 67 - 64
app/controllers/available_products_controller.rb

@@ -1,12 +1,11 @@
 class AvailableProductsController < ApplicationController
-
   before_action :set_available_product, only: [:edit_price, :update_price]
-  autocomplete :available_product, :name, :full => true
+  autocomplete :available_product, :name, full: true
 
   def stock
     @showcolumns = "minMax"
     # se utiliza para mandarle al datatable el numero de columnas y en que orden se deben de acomodar
-    @column_definition = [{ "data": "0"}, { "data": "1" }, { "data": "2" }, { "data": "3" }, { "data": "4" }, { "data": "5" }, { "data": "6" }, { "data": "7" }].to_json
+    @column_definition = [{ "data": "0" }, { "data": "1" }, { "data": "2" }, { "data": "3" }, { "data": "4" }, { "data": "5" }, { "data": "6" }, { "data": "7" }].to_json
 
     respond_to do |format|
       format.html
@@ -17,7 +16,7 @@ class AvailableProductsController < ApplicationController
   def initial_stock
     @showcolumns = "initial"
     # se utiliza para mandarle al datatable el numero de columnas y en que orden se deben de acomodar
-    @column_definition = [{ "data": "0"}, { "data": "1" }, { "data": "2" }, { "data": "3" }, { "data": "4" }, { "data": "5" }, { "data": "6" }].to_json
+    @column_definition = [{ "data": "0" }, { "data": "1" }, { "data": "2" }, { "data": "3" }, { "data": "4" }, { "data": "5" }, { "data": "6" }].to_json
 
     respond_to do |format|
       format.html
@@ -27,16 +26,11 @@ class AvailableProductsController < ApplicationController
 
   def stock_by_pointsale
     add_breadcrumb "Existencias", :stock_by_pointsale_path
-    if current_user.usertype == "S"
-      @selected = "W-#{current_user.warehouse_id}"
-    else
-      @selected = "P-#{current_user.pointsale_id}"
-    end
+    @selected = current_user.usertype == "S" ? "W-#{current_user.warehouse_id}" : "P-#{current_user.pointsale_id}"
     respond_to do |format|
       format.html
       format.json { render json: StockByPointsaleDatatable.new(view_context, current_user, @selected) }
     end
-
   end
 
   def edit_price
@@ -52,16 +46,28 @@ class AvailableProductsController < ApplicationController
         @available_product.audit_comment = message
         format.html { redirect_to products_url, success: message }
         format.json { head :no_content }
-        format.js {  flash[:success] = message }
+        format.js { flash[:success] = message }
       else
         format.js { render :edit_price }
-        format.json { render json: @available_product.errors,  status: :unprocessable_entity }
+        format.json { render json: @available_product.errors, status: :unprocessable_entity }
       end
     end
   end
 
+  def update_all_variants_prices
+    @product = Product.find(params[:product_id])
+    respond_to do |format|
+      if @product.is_parent
+        children_ids = @product.children.pluck(:id)
+        AvailableProduct.where('pointsale_id = (?) and product_id IN (?)', params[:pointsale_id], children_ids).update_all(price_sale: params[:new_price])
+        format.json { head :ok }
+      else
+        format.json { render json: @available_product.errors, status: :unprocessable_entity }
+      end
+    end
+  end
 
-  #POST /pointsales/5/available_products
+  # POST /pointsales/5/available_products
   def create
     @available_product = AvailableProduct.new(available_product_params)
 
@@ -74,51 +80,51 @@ class AvailableProductsController < ApplicationController
     end
   end
 
-
-  def updateStock
+  def update_stock
     min = params[:stock_min]
     max = params[:stock_max]
 
     respond_to do |format|
       if current_user.usertype == 'S'
-        WarehouseStock.where(id: params[:ids]).update_all(:stock_min => min, :stock_max => max)
+        WarehouseStock.where(id: params[:ids]).update_all(stock_min: min, stock_max: max)
       else
-        AvailableProduct.where(id: params[:ids]).update_all(:stock_min => min, :stock_max => max)
+        AvailableProduct.where(id: params[:ids]).update_all(stock_min: min, stock_max: max)
       end
       format.json { head :ok }
     end
   end
 
-  def initialStock
+  def set_initial_stock
     respond_to do |format|
       if current_user.usertype == 'S'
-        WarehouseStock.where(id: params[:ids]).update_all(:stock => params[:stock])
+        WarehouseStock.where(id: params[:ids]).update_all(stock: params[:stock])
       else
-        AvailableProduct.where(id: params[:ids]).update_all(:stock => params[:stock])
+        AvailableProduct.where(id: params[:ids]).update_all(stock: params[:stock])
       end
       format.json { head :ok }
     end
   end
 
+  # rubocop:disable Metrics/BlockLength
   def print_stock
     respond_to do |format|
       location = params[:location]
       category = params[:category]
-      sub_category =  params[:sub_category]
-      search =  params[:search]
+      sub_category = params[:sub_category]
+      search = params[:search]
       size = params[:size].to_i
-      location_id = params[:location][2, params[:location].length] if !location.blank?
+      location_id = params[:location][2, params[:location].length] unless location.blank?
 
-      if ( current_user.usertype == 'S' && location.blank? ) || ( !location.blank? && location.first == 'W' )
-        stock = WarehouseStock.activos.includes(:warehouse, :categories).where(:warehouse_id => (location_id.blank? ? current_user.warehouse_id : location_id)).where('stock > 0')
-      elsif ( current_user.usertype != 'S' && location.blank? ) || ( !location.blank? && location.first == 'P' )
-        stock = AvailableProduct.activos.includes(:pointsale, :categories).where(:pointsale_id => (location_id.blank? ? current_user.pointsale_id : location_id) ).where('stock > 0')
+      if (current_user.usertype == 'S' && location.blank?) || (!location.blank? && location.first == 'W')
+        stock = WarehouseStock.activos.includes(:warehouse, :categories).where(warehouse_id: (location_id.blank? ? current_user.warehouse_id : location_id)).where('stock > 0')
+      elsif (current_user.usertype != 'S' && location.blank?) || (!location.blank? && location.first == 'P')
+        stock = AvailableProduct.activos.includes(:pointsale, :categories).where(pointsale_id: (location_id.blank? ? current_user.pointsale_id : location_id)).where('stock > 0')
       end
 
       if sub_category.present?
         stock = stock.joins(:categories).where('categories.id = ?', sub_category)
       elsif category.present?
-        subs_ids = Category.activos.where(:parent_id => category).pluck(:id)
+        subs_ids = Category.activos.where(parent_id: category).pluck(:id)
         stock = stock.joins(:categories).where('categories.id IN (?)', subs_ids)
       end
 
@@ -137,37 +143,33 @@ class AvailableProductsController < ApplicationController
       end
 
       format.pdf do
-        render pdf: "existencias",
-          template: "available_products/stock_by_pointsale.pdf.erb",
-          layout: "pdf_base.pdf.erb",
-          locals: { :stock => stock, :location => location, :category => category, :sub_category => sub_category, :search => search },
-          show_as_html: params.key?('debug'),
-          page_size: 'Letter'
+        render pdf: "existencias", template: "available_products/stock_by_pointsale.pdf.erb", layout: "pdf_base.pdf.erb", locals: { stock: stock, location: location, category: category, sub_category: sub_category, search: search }, show_as_html: params.key?('debug'), page_size: 'Letter'
       end
     end
   end
+  # rubocop:enable Metrics/BlockLength
 
   def total_products_by_pointsale
-      location = params[:location]
-      category = params[:category]
-      sub_category =  params[:sub_category]
-      location_id = params[:location][2, params[:location].length] if !location.blank?
-
-      if location.first == 'P'
-        stock = AvailableProduct.activos.where(:pointsale_id => location_id )
-      elsif location.first == 'W'
-        stock = WarehouseStock.activos.where(:warehouse_id => location_id )
-      end
+    location = params[:location]
+    category = params[:category]
+    sub_category = params[:sub_category]
+    location_id = params[:location][2, params[:location].length] unless location.blank?
+
+    if location.first == 'P'
+      stock = AvailableProduct.activos.where(pointsale_id: location_id)
+    elsif location.first == 'W'
+      stock = WarehouseStock.activos.where(warehouse_id: location_id)
+    end
 
-      if sub_category.present?
-        stock = stock.joins(:categories).where('categories.id = ?', sub_category)
-      elsif category.present?
-        subs_ids = Category.activos.where(:parent_id => category).pluck(:id)
-        stock = stock.joins(:categories).where('categories.id IN (?)', subs_ids)
-      end
+    if sub_category.present?
+      stock = stock.joins(:categories).where('categories.id = ?', sub_category)
+    elsif category.present?
+      subs_ids = Category.activos.where(parent_id: category).pluck(:id)
+      stock = stock.joins(:categories).where('categories.id IN (?)', subs_ids)
+    end
 
-      total_prods = stock.sum(:stock)
-      render :json => total_prods
+    total_prods = stock.sum(:stock)
+    render json: total_prods
   end
 
   # DELETE //pointsales/5/available_products/1
@@ -180,18 +182,19 @@ class AvailableProductsController < ApplicationController
   end
 
   private
-    # Use callbacks to share common setup or constraints between actions.
-    def get_products
-      @products = Product.activos_children
-    end
-    # Use callbacks to share common setup or constraints between actions.
-    def set_available_product
-      @available_product = AvailableProduct.find(params[:available_product_id])
-    end
 
-    # Never trust parameters from the scary internet, only allow the white list through.
-    def available_product_params
-      params.require(:available_product).permit(:pointsale_id, :product_id, :stock_min, :stock_max, :stock, :ids, :price_sale)
-    end
+  # Use callbacks to share common setup or constraints between actions.
+  def get_products
+    @products = Product.activos_children
+  end
 
+  # Use callbacks to share common setup or constraints between actions.
+  def set_available_product
+    @available_product = AvailableProduct.find(params[:available_product_id])
+  end
+
+  # Never trust parameters from the scary internet, only allow the white list through.
+  def available_product_params
+    params.require(:available_product).permit(:pointsale_id, :product_id, :stock_min, :stock_max, :stock, :ids, :price_sale)
+  end
 end

+ 46 - 18
app/views/products/_list_prices.html.erb

@@ -1,6 +1,6 @@
 
 	<div class="row">
-		
+
 		<div class="col-md-12">
 			<p> Producto <strong><%= @product.name %></strong> con precio de venta (base) de <strong>$<%= @product.price_sale %></strong></p>
             <% if @product.pointsales.count > 0 %>
@@ -31,15 +31,28 @@
             </table>
             <% elsif @product.presentation %>
             <div class="well">
-                <div class="form-group">
-                    <label class="col-md-3 control-label">Punto de venta</label>
-                    <div class="col-md-9">
-                        <%= select_tag :pointsale_id, options_from_collection_for_select(@pointsales, :pointsale_id, :name), :include_blank => "Seleccione punto de venta",  class: "form-control select2" %>
-                        
+                <div class="form-horizontal">
+                    <div class="form-group">
+                        <label class="col-md-3 control-label">Punto de venta</label>
+                        <div class="col-md-9">
+                            <%= select_tag :pointsale_id, options_from_collection_for_select(@pointsales, :pointsale_id, :name), :include_blank => "Seleccione punto de venta",  class: "form-control select2" %>
+
+                        </div>
+                        <br>
+                    </div>
+                    <div class="form-group hidden" id="price_sale_div">
+                        <label class="col-md-3 control-label">Precio de venta</label>
+                        <div class="col-md-5">
+                            <div class="input-group">
+                                <span class="input-group-addon"> $ </span>
+                                <%= number_field_tag "price_sale", "", class: 'form-control mask_decimal' %>
+                            </div>
+                        </div>
+                        <div class="col-md-4" style="padding-left: 0px">
+                            <button type="button" class="btn green-dark" onclick="updateVariantPrices()">Aplicar a todo el estilo</button>
+                        </div>
                     </div>
-                    <br>
                 </div>
-
             </div>
             <table id="variantes" class="table table-striped table-bordered table-advance table-hover hidden">
                 <thead>
@@ -52,7 +65,7 @@
                     </tr>
                 </thead>
                 <tbody>
-                    
+
                 </tbody>
             </table>
             <% else %>
@@ -61,12 +74,12 @@
             <% end %>
 		</div>
 	</div>
-	
+
 <script type="text/javascript">
-    
+
     $(document).ready(function(){
         App.init();
-        
+
     });
     $('#pointsale_id').on('change', function() {
         $('#variantes').find('tbody').empty();
@@ -75,23 +88,38 @@
                 type: "get",
                 url:  '/products/' + <%= @product.id %> +'/variantsprices/' + $(this).val(),
                 dataType: 'json',
-                success: function(data) { 
+                success: function(data) {
                     $('#variantes').removeClass("hidden");
                     for (var i = 0; i < data.length; i++) {
                         $('#variantes > tbody:last').append(
                             '<tr><td>'+ data[i].name +'</td><td>$ '+ data[i].price +'</td><td><a class="btn btn-icon-only green-dark" title="Cambiar precio" data-remote="true" href="/available_products/'+ data[i].available_product_id +'/edit_price"><i class="fa fa-dollar"></i></a></td></tr>'
                             );
                     }
-                    // console.log(data);
+                    $('#price_sale_div').removeClass('hidden');
                 }
             });
-        }
-        else{
+        } else{
             $('#variantes').addClass("hidden");
+            $('#price_sale_div').addClass('hidden');
+            $('#price_sale').val('');
         }
     });
 
-    
+    function updateVariantPrices() {
+        $.ajax({
+            type: "POST",
+            url: "/update_all_variants_prices",
+            dataType: "json",
+            data: {
+                pointsale_id: $('#pointsale_id').val(),
+                new_price: $('#price_sale').val(),
+                product_id: <%= @product.id %>
+            },
+            success: function(xhr, status, error) {
+                $('#dialog').modal('toggle');
+            }
+        });
+    }
 
 </script>
-	
+

+ 3 - 2
config/routes.rb

@@ -103,6 +103,7 @@ Rails.application.routes.draw do
     get 'edit_price' => 'available_products#edit_price'
     patch 'update_price' => 'available_products#update_price'
   end
+  post 'update_all_variants_prices' => 'available_products#update_all_variants_prices', defaults: { format: 'json' }
 
   resources :cash_outs
   get 'get_open_cash_registers' => 'cash_outs#get_open_cash_registers', defaults: { format: 'js' }
@@ -211,10 +212,10 @@ Rails.application.routes.draw do
   # rutas para el STOCK
   get 'stock_by_pointsale' => 'available_products#stock_by_pointsale', :as => 'stock_by_pointsale'
   get 'products_stock/:pointsale_id' => 'available_products#stock', :as => 'products_stock'
-  put 'updateStock' => 'available_products#updateStock', defaults: { format: 'json' }
+  put 'update_stock' => 'available_products#update_stock', defaults: { format: 'json' }
   get 'products_initial_stock/:pointsale_id' => 'available_products#initial_stock', :as => 'products_initial_stock'
   get 'print_stock_by_pointsale' => 'available_products#print_stock', :as => 'print_stock_by_pointsale'
-  put 'initialStock' => 'available_products#initialStock', defaults: { format: 'json' }
+  put 'set_initial_stock' => 'available_products#set_initial_stock', defaults: { format: 'json' }
   get 'total_products_by_pointsale' => 'available_products#total_products_by_pointsale', :format => :json
 
   # find de productos para el typeahead