Sfoglia il codice sorgente

Fixed bug when updating product price sale from purchases

Jacqueline Maldonado 7 anni fa
parent
commit
e7719a0726

+ 19 - 14
app/controllers/products_controller.rb

@@ -161,20 +161,22 @@ class ProductsController < ApplicationController
   end
 
   def edit_from_purchase
+    purchase_in_dollars = params[:is_in_dollars]
+    exchange = params[:exchange].to_f
+    if purchase_in_dollars == "true"
+      @product.price_base_dollars = params[:product][:price_base].to_f
+      price_in_peso = @product.price_base_dollars * exchange
+      @product.price_base = @product.price_base.present? ? price_in_peso : nil
+      @suggested_price_sale = (price_in_peso * (@pos_config.gain_margin / 100)) + price_in_peso
+    else
+      @product.price_base = params[:product][:price_base].to_f
+      price_in_dollars = @product.price_base / exchange if exchange != 0
+      @product.price_base_dollars = @product.price_base_dollars.present? ? price_in_dollars : nil
+      @suggested_price_sale = (@product.price_base * (@pos_config.gain_margin / 100)) + @product.price_base
+    end
+    @suggested_price_sale = 0 if @suggested_price_sale.nil?
+
     respond_to do |format|
-      purchase_in_dollars = params[:is_in_dollars]
-      exchange = params[:exchange].to_f
-      if purchase_in_dollars == "true"
-        @product.price_base_dollars = params[:product][:price_base].to_f
-        price_in_peso = @product.price_base_dollars * exchange
-        @product.price_base = @product.price_base.present? ? price_in_peso : nil
-        @suggested_price_sale = (price_in_peso * (@pos_config.gain_margin / 100)) + price_in_peso
-      else
-        @product.price_base = params[:product][:price_base].to_f
-        price_in_dollars = @product.price_base / exchange if exchange != 0
-        @product.price_base_dollars = @product.price_base_dollars.present? ? price_in_dollars : nil
-        @suggested_price_sale = (@product.price_base * (@pos_config.gain_margin / 100)) + @product.price_base
-      end
       @product.audit_comment = 'El producto ' + @product.sku + ' fue modificado.'
       @product.save
       format.json { head :no_content }
@@ -187,10 +189,12 @@ class ProductsController < ApplicationController
     unless @product.parent_id.nil?
       @product = Product.find(@product.parent_id)
     end
+    @product.price_base = params[:product][:price_base].to_f
+    @product.price_sale = params[:product][:price_sale].to_f
 
     message = "Se ha modificado el precio de venta base del producto " + @product.name
     respond_to do |format|
-      if @product.update(product_params)
+      if @product.save
         @product.children.each do |variant|
           variant.update_attributes(product_params)
           variant.save
@@ -199,6 +203,7 @@ class ProductsController < ApplicationController
         format.json { head :no_content }
         format.js { flash[:success] = message }
       else
+        @suggested_price_sale = params[:suggested_price_sale].to_f
         format.js { render :edit_from_purchase }
         format.json { render json: @available_product.errors, status: :unprocessable_entity }
       end

+ 27 - 25
app/models/pre_purchase.rb

@@ -1,29 +1,31 @@
 class PrePurchase < ActiveRecord::Base
-	belongs_to :supplier
-	belongs_to :user
-	belongs_to :pointsale
-	belongs_to :product
-	belongs_to :warehouse	
+  belongs_to :supplier
+  belongs_to :user
+  belongs_to :pointsale
+  belongs_to :product
+  belongs_to :warehouse
 
-	validates :supplier_id , :presence => { message: "Debe seleccionar proveedor para la compra." }, :on => [:create, :update]
-	validates :product_id , :presence => { message: "Debe seleccionar producto para la compra." }, :on => [:create, :update]
-    validates :pointsale_id , presence: { message: "Debe seleccionar un almacén o un punto de venta." }, :if => Proc.new {|c| c.warehouse_id.blank?} , :on => [:create, :update]
-    validates :warehouse_id , presence: { message: "Debe seleccionar un almacén o un punto de venta." }, :if => Proc.new {|c| c.pointsale_id.blank?} , :on => [:create, :update]
+  validates :supplier_id, presence: { message: "Debe seleccionar proveedor para la compra." }, on: [:create, :update]
+  validates :product_id, presence: { message: "Debe seleccionar producto para la compra." }, on: [:create, :update]
+  validates :pointsale_id, presence: { message: "Debe seleccionar un almacén o un punto de venta." }, if: Proc.new { |c| c.warehouse_id.blank? }, on: [:create, :update]
+  validates :warehouse_id, presence: { message: "Debe seleccionar un almacén o un punto de venta." }, if: Proc.new { |c| c.pointsale_id.blank? }, on: [:create, :update]
 
-	def get_totals
-		if self.exchange.present? 
-			self.price_base = self.product.price_base_dollars
-		else
-			self.price_base = self.product.price_base
-		end
-		self.price_base = self.price_base.blank? ? 0 : self.price_base
-		self.amount = self.quantity * self.price_base
-		self.tax = 0.0
-		if self.product.include_purchase_tax == 1 && self.exchange.blank?
-			tax_percent = PosConfig.first.tax_percent
-	        self.tax = (((tax_percent / 100)  * self.amount) / ((100 + tax_percent) / 100)).round(2)	
-		end
-		self.total = self.amount
-		return true
-	end 
+  def get_totals
+    self.price_base =
+      if exchange.present?
+        product.price_base_dollars
+      else
+        product.price_base
+      end
+    self.price_base = 0 if price_base.nil?
+
+    self.amount = quantity * price_base
+    self.tax = 0.0
+    if product.include_purchase_tax? && exchange.blank?
+      tax_percent = PosConfig.first.tax_percent
+      self.tax = (((tax_percent / 100)  * amount) / ((100 + tax_percent) / 100)).round(2)
+    end
+    self.total = tax + amount
+    true
+  end
 end

+ 3 - 1
app/models/product.rb

@@ -36,7 +36,9 @@ class Product < ActiveRecord::Base
   validates_presence_of :category_ids, message: "Debe elegir por lo menos una línea de producto relacionada al producto."
   validates :barcode, uniqueness: { message: "El código de barras ya fue utilizado, favor de especificar otro." }, allow_blank: true
   validates_presence_of :name, message: "Debe capturar el nombre del producto."
-  validates_presence_of :price_sale, message: "Debe capturar el precio de venta del producto."
+  validates :price_sale,
+            presence: { message: "Debe capturar el precio de venta del producto." },
+            numericality: { greater_than: 0.00 }
 
   def valid_categories
     categories.count > 0

+ 3 - 7
app/views/pre_purchases/_pre_purchase.html.erb

@@ -14,15 +14,11 @@
     <%= pre_purchase.product.display_attributes %>
   </td>
   <td>
-    <input type="number" min="1" id="quantity_<%= pre_purchase.id %>" class="form-control" id="quantity_<%= pre_purchase.id %>" value="<%= pre_purchase.quantity %>" oninput="updateQuantity($(this))" pattern="^[0-9]*[1-9][0-9]*$" title="La cantidad debe de ser mayor o igual a 1" required>
+    <input type="number" min="1" id="quantity_<%= pre_purchase.id %>" class="form-control input-xsmall" id="quantity_<%= pre_purchase.id %>" value="<%= pre_purchase.quantity %>" oninput="updateQuantity($(this))" pattern="^[0-9]*[1-9][0-9]*$" title="La cantidad debe de ser mayor o igual a 1" required>
   </td>
   <td>
-    <% if pre_purchase.exchange.blank? %>
-      <input class="form-control" id="price_<%= pre_purchase.id %>" type="number" min="0" value="<%= pre_purchase.product.price_base %>"  oninput="updateProductPrice($(this))" title="El precio no puede ser 0" step="any" required />   
-    <% else %>
-      <input class="form-control" id="price_<%= pre_purchase.id %>" type="number" min="0" value="<%= pre_purchase.product.price_base_dollars %>"  oninput="updateProductPrice($(this))" title="El precio no puede ser 0" step="any" required />  
-    <% end %> 
-    <span class="hidden"><%=pre_purchase.product.id%></span>
+    <input class="form-control input-small" id="price_<%= pre_purchase.id %>" type="number" min="0" value="<%= pre_purchase.exchange.blank? ? pre_purchase.product.price_base : pre_purchase.product.price_base_dollars %>"  oninput="updateProductPrice($(this))" title="El precio no puede ser 0" step="any" required />
+    <span class="hidden"><%= pre_purchase.product.id %></span>
   </td>
   <td>
     <%= pre_purchase.tax %>

+ 83 - 88
app/views/products/_form_update_price.html.erb

@@ -1,111 +1,106 @@
 <!-- BEGIN FORM-->
-<%= form_for(@product, url: product_update_from_purchase_path(@product), :remote => true, :html => {:class=>"form-horizontal"}) do |f| %>
-<div class="portlet-body form">
-	<% if @product.errors.any? %>
-		<div class="alert alert-danger">
-			<strong>Tiene <%= pluralize(@product.errors.count, "error") %> no se puede guardar el producto</strong><br>
-		</div>
-	<% end %>
-	<div class="form-body">
-		<%= hidden_field_tag :gain_margin, @pos_config.gain_margin %>
-		<%= hidden_field_tag :product_id, @product.id %>
-		<%= f.hidden_field :price_base, :value => @product.price_base %>
-		<div class="row">
-			
-			<div class="col-md-12">
-				<div class="note note-success">
-			        <p> ¿Desea actualizar el precio de venta? el sugerido es en base al margen de ganancia establecido en la configuración.</p>
-			        <p>Al omitir, el precio de venta se mantendrá en: <strong><%= number_to_currency(@product.price_sale, precision: 2)%> MXN</strong></p>
+<%= form_for(@product, url: product_update_from_purchase_path(@product), remote: true, html: { class: "form-horizontal" }) do |f| %>
+	<div class="portlet-body form">
+		<% if @product.errors.any? %>
+			<div class="alert alert-danger">
+				<strong>Tiene <%= pluralize(@product.errors.count, "error") %> no se puede guardar el producto</strong><br>
+			</div>
+		<% end %>
+		<div class="form-body">
+			<%= hidden_field_tag :gain_margin, @pos_config.gain_margin %>
+			<%= hidden_field_tag :product_id, @product.id %>
+			<%= f.hidden_field :price_base, value: @product.price_base %>
+			<%= hidden_field_tag :suggested_price_sale, value: @suggested_price_sale %>
+			<div class="row">
+				<div class="col-md-12">
+					<div class="note note-success">
+		        <p> ¿Desea actualizar el precio de venta? el sugerido es en base al margen de ganancia establecido en la configuración.</p>
+		        <p>Al omitir, el precio de venta se mantendrá en: <strong><%= number_to_currency(@product.price_sale, precision: 2)%> MXN</strong></p>
 			    </div>
-				<div class="form-group">
-					<%= f.label :price_sale, "Precio de venta base", {:class=>"col-md-3 control-label"} %>
-					<div class="col-md-9">
+					<div class="form-group">
+						<%= f.label :price_sale, "Precio de venta base", { class: "col-md-3 control-label" } %>
 						<div class="col-md-9">
-							<div class="input-group">
-								<span class="input-group-addon"> $ </span>
-								<%= f.text_field :price_sale, :class=>"form-control mask_decimal", :value => @suggested_price_sale %>
-								<span class="input-group-addon"> MXN </span>
-							</div>	
-							<span class="help-block">El precio es sugerido. <br> Precio de compra 
-								<strong> 
-									<% if @product.is_in_dollars %>
-										<%= number_to_currency(@product.price_base_dollars, precision: 2) %> USD
-									<% else %>
-										<%= number_to_currency(@product.price_base, precision: 2) %> MXN
-									<% end %>
-								</strong> 
-							</span>													
+							<div class="col-md-9">
+								<div class="input-group">
+									<span class="input-group-addon"> $ </span>
+									<%= f.text_field :price_sale, class: "form-control mask_decimal", value: @suggested_price_sale %>
+									<span class="input-group-addon"> MXN </span>
+								</div>
+								<span class="help-block">El precio es sugerido. <br> Precio de compra
+									<strong>
+										<% if @product.is_in_dollars %>
+											<%= number_to_currency(@product.price_base_dollars, precision: 2) %> USD
+										<% else %>
+											<%= number_to_currency(@product.price_base, precision: 2) %> MXN
+										<% end %>
+									</strong>
+								</span>
+							</div>
 						</div>
 					</div>
-				</div>
-				<% if @product.pointsales_prices.count > 0 %>
-				<h4>Precios de venta por punto de venta </h4>
-				<div class="note note-warning">
+					<% if @product.pointsales_prices.count > 0 %>
+						<h4>Precios de venta por punto de venta </h4>
+						<div class="note note-warning">
 			        <p> Los siguientes puntos de venta cambiaron el precio. Puede modificarlo deacuerdo al precio base.</p>
-			        
-			    </div>
-
-				<table class="table table-striped table-bordered table-advance table-hover">
-	                <thead>
-	                    <tr>
-	                        <th width="35%">
-	                            <i class="fa fa-briefcase"></i> Punto de venta </th>
-	                        <th class="hidden-xs">
-	                            <i class="fa fa-user"></i> Precio </th>
-	                        
-	                    </tr>
-	                </thead>
-	                <tbody>
-	                	
-		                	<%= f.fields_for :available_products, @product.available_products do |ff| %>
-		                    <tr class="<%= ff.object.price_sale.nil? ? 'hidden' : '' %>">
-		                        <td> <%= Pointsale.find(ff.object.pointsale_id).name %></td>
-		                        <td><%= ff.hidden_field :id %>
-		                        	<div class="input-group">
-										<span class="input-group-addon"> $ </span>
-										<%= ff.text_field :price_sale, :class=>"form-control mask_decimal" %>
-										<span class="input-group-addon"> MXN </span>
-									</div>
-		                        </td>
-		                        
-		                    </tr>
-		                    <% end %>
-	                   	
-	                </tbody>
-	            </table>
-	            <% end %>
+				    </div>
+						<table class="table table-striped table-bordered table-advance table-hover">
+    	        <thead>
+                <tr>
+                  <th width="35%">
+                  	<i class="fa fa-briefcase"></i> Punto de venta
+                  </th>
+                	<th class="hidden-xs">
+                    <i class="fa fa-user"></i> Precio
+                  </th>
+              	</tr>
+          	  </thead>
+              <tbody>
+           		 	<%= f.fields_for :available_products, @product.available_products do |ff| %>
+                  <tr class="<%= ff.object.price_sale.nil? ? 'hidden' : '' %>">
+                    <td> <%= Pointsale.find(ff.object.pointsale_id).name %></td>
+                    <td>
+                    	<%= ff.hidden_field :id %>
+                    	<div class="input-group">
+												<span class="input-group-addon"> $ </span>
+												<%= ff.text_field :price_sale, class: "form-control mask_decimal" %>
+												<span class="input-group-addon"> MXN </span>
+											</div>
+                    </td>
+                  </tr>
+                <% end %>
+              </tbody>
+            </table>
+          <% end %>
+				</div>
 			</div>
 		</div>
-	</div>
-	<div>
+		<div>
 	    <h4 class="form-section"></h4>
-		<div class="row">
-			<div class="col-md-9">
-				<button type="submit" class="btn green" >Actualizar precio</button>
-				<button type="button" class="btn default" onclick="cerrarDialog()">Omitir</button>
+			<div class="row">
+				<div class="col-md-9">
+					<button type="submit" class="btn green" >Actualizar precio</button>
+					<button type="button" class="btn default" onclick="cerrarDialog()">Omitir</button>
+				</div>
 			</div>
 		</div>
 	</div>
-</div>
 <% end %>
 <script type="text/javascript">
 	function submitForm() {
 		var priceSale = $('#product_price_sale').val();
 		var productId = $('#product_id').val();
-        $.ajax({
-            type: "POST",
-          	url: "/products/" + productId + "/update_from_purchase",
-          	dataType: "json",
-          	data: {product: {price_sale: priceSale }},
-            success: function(xhr, status, error) {
-        		$('#dialog').modal('toggle');
-            }
-        });  
+    $.ajax({
+      type: "POST",
+    	url: "/products/" + productId + "/update_from_purchase",
+    	dataType: "json",
+    	data: {product: {price_sale: priceSale }},
+      success: function(xhr, status, error) {
+    		$('#dialog').modal('toggle');
+      }
+    });
 	}
 
 	function cerrarDialog() {
 		$('#dialog').modal('toggle');
 	}
-
 </script>
-