Переглянути джерело

Change customer in new sale

Jacqueline Maldonado 7 роки тому
батько
коміт
bdb6ab5464

+ 83 - 43
app/controllers/pre_sales_controller.rb

@@ -2,9 +2,7 @@ class PreSalesController < ApplicationController
   before_action :set_pre_sale, only: [:show, :edit, :update, :destroy]
 
   # GET /pre_sales/new
-  def new
-    # @pre_sale = PreSale.new
-  end
+  def new; end
 
   # POST /pre_sales
   # POST /pre_sales.json
@@ -14,7 +12,7 @@ class PreSalesController < ApplicationController
     @pre_sale.user_id = current_user.id
 
     # Sumar los totales de los presales en caso que exista.
-    PreSale.where(:user_id => @pre_sale.user_id).each do |pre|
+    PreSale.where(user_id: @pre_sale.user_id).each do |pre|
       total_in_pre_sales = total_in_pre_sales + pre.total
     end
 
@@ -23,7 +21,7 @@ class PreSalesController < ApplicationController
 
     @pre_sale.get_totals
 
-    total_in_pre_sales = total_in_pre_sales + @pre_sale.total
+    total_in_pre_sales += @pre_sale.total
 
     respond_to do |format|
       if has_enough_stock?(@pre_sale)
@@ -37,7 +35,7 @@ class PreSalesController < ApplicationController
               format.json { render json: @pre_sale.errors.values, status: :unprocessable_entity }
             end
           else
-            @pre_sale.errors.add(:customer_id, "El cliente ya no tiene credito disponible.")
+            @pre_sale.errors.add(:customer_id, "El cliente ya no tiene crédito disponible.")
             format.json { render json: @pre_sale.errors.values, status: :unprocessable_entity }
           end
         elsif @pre_sale.sale_type == "cash"
@@ -64,21 +62,30 @@ class PreSalesController < ApplicationController
   # PATCH/PUT /pre_sales/1
   # PATCH/PUT /pre_sales/1.json
   def update
-    respond_to do |format|
-      @pre_sale.quantity = params[:pre_sale][:quantity].to_i
-      availableProduct = AvailableProduct.find_by(:pointsale_id => current_user.pointsale_id,
-        :product_id => @pre_sale.product_id)
+    @pre_sale.quantity = params[:pre_sale][:quantity].to_i
+    availableProduct = AvailableProduct.find_by(pointsale_id: current_user.pointsale_id, product_id: @pre_sale.product_id)
 
-      same_product_quantity = 0
-      PreSale.where(:user_id => current_user.id, :product_id => @pre_sale.product_id).where.not(:id => @pre_sale.id).each do |pre|
-        same_product_quantity += pre.quantity
-      end
+    same_product_quantity = 0
+    total_in_pre_sales = 0
+    PreSale.where(user_id: current_user.id, product_id: @pre_sale.product_id).where.not(id: @pre_sale.id).each do |pre|
+      total_in_pre_sales += pre.total
+      same_product_quantity += pre.quantity
+    end
 
-      if availableProduct.stock >= (same_product_quantity +  @pre_sale.quantity)
+    total_quantity = same_product_quantity + @pre_sale.quantity
+    respond_to do |format|
+      if availableProduct.stock >= total_quantity
         @pre_sale.get_totals
-
-        if @pre_sale.update(pre_sale_params)
-          format.json { render :json => @pre_sale }
+        total_in_pre_sales += @pre_sale.total
+        if !@pre_sale.credit?
+          @pre_sale.update(pre_sale_params)
+          format.json { render json: @pre_sale }
+        elsif @pre_sale.customer.sale_approved?(@pre_sale.customer.get_debiting + total_in_pre_sales)
+          @pre_sale.update(pre_sale_params)
+          format.json { render json: @pre_sale }
+        else
+          @pre_sale.errors.add(:base, "El cliente ya no tiene crédito disponible")
+          format.json { render json: @pre_sale.errors.values, status: :unprocessable_entity }
         end
       else
         @pre_sale.errors.add(:base, "Stock insuficiente del producto #{@pre_sale.product.name}")
@@ -103,10 +110,10 @@ class PreSalesController < ApplicationController
     @product = pointsale.products.find_by("barcode = ? and stock > 0", params[:barcode])
 
     if @product.blank?
-      format.js { render :action => "create" }
+      format.js { render action: "create" }
     else
       # ir sumando todos los presales que tiene, para ver si lo abarca el credito
-      PreSale.where(:user_id => current_user.id).each do |pre|
+      PreSale.where(user_id: current_user.id).each do |pre|
         total_in_pre_sales = total_in_pre_sales + pre.total
       end
 
@@ -131,16 +138,16 @@ class PreSalesController < ApplicationController
             debiting = @pre_sale.customer.get_debiting
             if @pre_sale.customer.sale_approved?(debiting + total_in_pre_sales)
               if @pre_sale.save
-                format.js { render :action => "create" }
+                format.js { render action: "create" }
               end
             else
-              @pre_sale.errors.add(:customer_id, "El cliente ya no tiene credito disponible.")
+              @pre_sale.errors.add(:customer_id, "El cliente ya no tiene crédito disponible.")
               format.json { render json: @pre_sale.errors.values, status: :unprocessable_entity }
-              format.js { render :action => "create" }
+              format.js { render action: "create" }
             end
           elsif @pre_sale.sale_type == "cash"
             if  @pre_sale.save
-              format.js { render :action => "create" }
+              format.js { render action: "create" }
             else
               format.json { render json: @pre_sale.errors.values, status: :unprocessable_entity }
             end
@@ -159,31 +166,64 @@ class PreSalesController < ApplicationController
     end
   end
 
-  private
-    # Use callbacks to share common setup or constraints between actions.
-    def set_pre_sale
-      @pre_sale = PreSale.find(params[:id])
-    end
-
-    # Never trust parameters from the scary internet, only allow the white list through.
-    def pre_sale_params
-      params.require(:pre_sale).permit(:customer_id, :user_id, :open_cash_register_id, :sale_type, :product_id, :quantity, :amount, :tax, :discount, :total, :barcode, :haggle)
+  def update_presale_customer
+    @pre_sales = PreSale.where(user_id: current_user.id)
+    @pre_sales.update_all(customer_id: params[:customer_id], sale_type: 1) if @pre_sales.present?
+    respond_to do |format|
+      format.json { head :ok }
     end
+  end
 
-    def has_enough_stock?(pre_sale)
-      same_product_quantity = 0
-      PreSale.where(:user_id => current_user.id, :product_id => pre_sale.product_id).each do |pre|
-        same_product_quantity += pre.quantity
+  def update_saletype
+    pre_sales = PreSale.where(user_id: current_user.id)
+    type =
+      case params[:type]
+      when "credit" then
+        0
+      when "cash" then
+        1
+      when "reserved" then
+        3
       end
 
-      availableProduct = AvailableProduct.find_by(:pointsale_id => current_user.pointsale_id,
-        :product_id => pre_sale.product_id)
-
-      if availableProduct.stock >= (same_product_quantity +  pre_sale.quantity)
-        return true
+    respond_to do |format|
+      if pre_sales.blank?
+        format.json { head :ok }
       else
-        return false
+        if params[:type] != "credit" || pre_sales[0].customer.sale_approved?(pre_sales[0].customer.get_debiting + pre_sales.sum(:total))
+          pre_sales.update_all(sale_type: type)
+          format.json { head :ok }
+        else
+          pre_sales[0].errors.add(:base, "El cliente ya no tiene crédito disponible")
+          format.json { render json: pre_sales[0].errors.values, status: :unprocessable_entity }
+        end
       end
+    end
+  end
+
+  private
+  # Use callbacks to share common setup or constraints between actions.
+  def set_pre_sale
+    @pre_sale = PreSale.find(params[:id])
+  end
 
+  # Never trust parameters from the scary internet, only allow the white list through.
+  def pre_sale_params
+    params.require(:pre_sale).permit(:customer_id, :user_id, :open_cash_register_id, :sale_type, :product_id, :quantity, :amount, :tax, :discount, :total, :barcode, :haggle)
+  end
+
+  def has_enough_stock?(pre_sale)
+    same_product_quantity = 0
+    PreSale.where(user_id: current_user.id, product_id: pre_sale.product_id).each do |pre|
+      same_product_quantity += pre.quantity
     end
+
+    availableProduct = AvailableProduct.find_by(pointsale_id: current_user.pointsale_id, product_id: pre_sale.product_id)
+
+    if availableProduct.stock >= (same_product_quantity + pre_sale.quantity)
+      return true
+    else
+      return false
+    end
+  end
 end

+ 18 - 68
app/controllers/sales_controller.rb

@@ -15,7 +15,7 @@ class SalesController < ApplicationController
   def index
     today = Date.current
     thirty_day_ago = today - 30
-    @sales = current_user.usertype == 'A' ? Sale.includes(:customer, :user, :seller).where(date_sale: thirty_day_ago..today).where('saletype != 2').order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.includes(:customer, :user, :seller).where(date_sale: thirty_day_ago..today).where('saletype != 2').order(" created_at DESC ")
+    @sales = current_user.usertype == 'A' ? Sale.includes(:customer, :user, :seller, :sales_details).where(date_sale: thirty_day_ago..today).where.not(saletype: 2).order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.includes(:customer, :user, :seller).where(date_sale: thirty_day_ago..today).where.not(saletype: 2).order("created_at DESC")
   end
 
   def sales_reserved
@@ -71,58 +71,35 @@ class SalesController < ApplicationController
       @sale.open_cash_register_id = session[:open_cash_register_id]
       @sale.status = :notpaid
       @sale.expiration_date = Date.today + @pos_config.days_cancel_reserved if @sale.reserved?
-
       @sale.audit_comment = "Venta #{@sale.sale_code} por #{@sale.total} creada."
 
       if @sale.save
         # agregar detalles de la venta
         @pre_sales.each do |pre_sale|
-          detail = SalesDetail.new
-          detail.product_id = pre_sale.product_id
-          detail.unit_price = pre_sale.unit_price
-          detail.quantity = pre_sale.quantity
-          detail.amount = pre_sale.amount
-          detail.tax = pre_sale.tax
-          detail.discount = pre_sale.discount
-          detail.total = pre_sale.total
-          detail.special_price_id = pre_sale.special_price_id
-          detail.status = :active
-
+          detail = SalesDetail.new(product_id: pre_sale.product_id, unit_price: pre_sale.unit_price, quantity: pre_sale.quantity, amount: pre_sale.amount, tax: pre_sale.tax, discount: pre_sale.discount, total: pre_sale.total, special_price_id: pre_sale.special_price_id, status: :active)
           @sale.sales_details << detail
           pre_sale.destroy
           # actualizar stock del producto
           stock_product = AvailableProduct.find_by(product_id: detail.product_id, pointsale_id: @sale.get_pointsale.id)
           next if stock_product.blank?
           if stock_product.stock.present?
-            stock_product.stock = stock_product.stock - detail.quantity
+            stock_product.stock -= detail.quantity
             stock_product.save
           else
-            errors.add(:base, "No se tiene registrado el stock de alguno de los productos, es necesario configurarlo antes de generar una venta")
+            errors.add(:base, "No se tiene registrado el stock de alguno de los productos. Es necesario configurarlo antes de generar una venta")
             format.json { render json: @sale.errors.values, status: :unprocessable_entity }
           end
           # guardar en bitacora de inventario
-          move = InventoriesMove.new
-          move.product_id = detail.product_id
-          move.sale_id = @sale.id
-          move.quantity = detail.quantity
-          move.move_type = "outgoing"
-          move.reason = "sale"
+          move = InventoriesMove.new(product_id: detail.product_id, sale_id: @sale.id, quantity: detail.quantity, move_type: "outgoing", reason: "sale")
           move.save
         end
         # dependiendo el tipo de venta: contado/credito determina que hacer
         if @sale.cash?
           format.js { redirect_to new_cash_registers_move_path(sale: @sale.id) }
         elsif @sale.credit?
-          credit = Credit.new
-          credit.customer_id = @sale.customer_id
-          credit.pointsale_id = current_user.pointsale_id
-          credit.sale_id = @sale.id
-          credit.total = @sale.total
-          credit.rest = @sale.total
-          credit.status = "active"
-          credit.credit_note = @sale.credit_note if @sale.credit_note.present?
+          credit = Credit.new(customer_id: @sale.customer_id, pointsale_id: current_user.pointsale_id, sale_id: @sale.id, total: @sale.total, rest: @sale.total, status: "active", credit_note: @sale.credit_note.present? ? @sale.credit_note : "")
           credit.save
-          flash[:success] = "Venta a credito registrada al cliente: #{@sale.customer.nick_name} por $ #{@sale.total}"
+          flash[:success] = "Venta a crédito registrada al cliente: #{@sale.customer.nick_name} por $ #{@sale.total}"
           format.js { render 'create_credit_sale' }
         elsif @sale.reserved?
           format.js { redirect_to new_cash_registers_move_path(sale: @sale.id) }
@@ -164,15 +141,8 @@ class SalesController < ApplicationController
             if moves.present?
               if moves[0].open_cash_register.closed?
                 quantity_to_return = moves.sum(:quantity)
-                new_cash_move = CashRegistersMove.new
+                new_cash_move = CashRegistersMove.new(open_cash_register_id: session[:open_cash_register_id], payment_method_id: PaymentMethod.find_by(isCash: 1).id, quantity: quantity_to_return, move_type: :egreso, sale_id: @sale.id, concept: :sale, status: :active)
                 new_cash_move.skip_received_validation = true
-                new_cash_move.open_cash_register_id = session[:open_cash_register_id]
-                new_cash_move.payment_method_id = PaymentMethod.find_by(isCash: 1).id
-                new_cash_move.quantity = quantity_to_return
-                new_cash_move.move_type = :egreso
-                new_cash_move.sale_id = @sale.id
-                new_cash_move.concept = :sale
-                new_cash_move.status = :active
                 new_cash_move.save
               else
                 moves.destroy_all
@@ -185,16 +155,8 @@ class SalesController < ApplicationController
           # si la caja sigue abierta, solo elimina los moves, si ya corto, genera un egreso por esa cantidad
           if moves.present?
             if moves[0].open_cash_register.closed?
-              new_cash_move = CashRegistersMove.new
+              new_cash_move = CashRegistersMove.new(open_cash_register_id: session[:open_cash_register_id], payment_method_id: PaymentMethod.find_by(isCash: true).id, quantity: moves.sum(:quantity), move_type: :egreso, sale_id: moves[0].sale_id, concept: :sale, ticket: moves[0].sale.sale_code, status: :active)
               new_cash_move.skip_received_validation = true
-              new_cash_move.open_cash_register_id = session[:open_cash_register_id]
-              new_cash_move.payment_method_id = PaymentMethod.find_by(isCash: true).id
-              new_cash_move.quantity = moves.sum(:quantity)
-              new_cash_move.move_type = :egreso
-              new_cash_move.sale_id = moves[0].sale_id
-              new_cash_move.concept = :sale
-              new_cash_move.ticket = moves[0].sale.sale_code
-              new_cash_move.status = :active
               new_cash_move.save
             else
               moves.destroy_all
@@ -213,12 +175,7 @@ class SalesController < ApplicationController
           stock = stock_product.stock + detail.quantity
           stock_product.update_attributes(stock: stock)
           # guardar en bitacora de inventario
-          move = InventoriesMove.new
-          move.product_id = detail.product_id
-          move.sale_id = @sale.id
-          move.quantity = detail.quantity
-          move.move_type = "incoming"
-          move.reason = @sale.reserved? ? "sale_reserved_cancelled" : "sale_cancel"
+          move = InventoriesMove.new(product_id: detail.product_id, sale_id: @sale.id, quantity: detail.quantity, move_type: "incoming", reason: (@sale.reserved? ? "sale_reserved_cancelled" : "sale_cancel"))
           move.save
         end
         format.html { redirect_to (@sale.reserved? ? sales_reserved_path : sales_url), warning: (@sale.reserved? ? "Apartado con folio #{@sale.sale_code} cancelado." : "Venta con folio #{@sale.sale_code} cancelado.") }
@@ -229,10 +186,12 @@ class SalesController < ApplicationController
   # rubocop:enable Metrics/BlockLength
 
   def find_sales_by_date
-    respond_to do |format|
+    if params[:begin_date].present? && params[:end_date].present?
       start_date = DateTime.parse(params[:begin_date])
       end_date = DateTime.parse(params[:end_date])
-      @sales = current_user.usertype == 'A' ? Sale.where(date_sale: start_date..end_date).where('saletype != 2').order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.where(date_sale: start_date..end_date).where('saletype != 2').order(" created_at DESC ")
+      @sales = current_user.usertype == 'A' ? Sale.where(date_sale: start_date..end_date).where.not(saletype: 2).order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.where(date_sale: start_date..end_date).where('saletype != 2').order(" created_at DESC ")
+    end
+    respond_to do |format|
       format.js
     end
   end
@@ -242,7 +201,7 @@ class SalesController < ApplicationController
       start_date = DateTime.parse(params[:begin_date])
       end_date = DateTime.parse(params[:end_date])
       cliente = params[:cliente]
-      @sales = Sale.where(date_sale: start_date..end_date, customer_id: cliente).where('saletype != 2').order(" id DESC ")
+      @sales = Sale.where(date_sale: start_date..end_date, customer_id: cliente).where.not(saletype: 2).order(" id DESC ")
       format.js { render action: "find_sales_by_date" }
     end
   end
@@ -268,12 +227,7 @@ class SalesController < ApplicationController
           stock = stock_product.stock + detail.quantity
           stock_product.update_attributes(stock: stock)
           # guardar en bitacora de inventario
-          move = InventoriesMove.new
-          move.product_id = detail.product_id
-          move.sale_id = @sale.id
-          move.quantity = detail.quantity
-          move.move_type = "incoming"
-          move.reason = "sale_expired"
+          move = InventoriesMove.new(product_id: detail.product_id, sale_id: @sale.id, quantity: detail.quantity, move_type: "incoming", reason: "sale_expired")
           move.save
         end
         format.html { redirect_to sales_reserved_url, warning: "Productos reingresados al inventario del apartado #{@sale.sale_code}." }
@@ -319,11 +273,7 @@ class SalesController < ApplicationController
     # ticket para credito
     respond_to do |format|
       sale = Sale.find(params[:sale_id])
-      debt = 0
-
-      sale.customer.credits.activos.each do |credit|
-        debt += credit.rest
-      end
+      debt = sale.customer.credits.activos.sum(:rest)
 
       format.pdf do
         render pdf: "ticket_credito_#{sale.id}", template: "sales/receipt_credit.pdf.erb", layout: 'receipt.html.erb', locals: { sale: sale, debt: debt }, show_as_html: params.key?('debug'), page_width: '80mm', page_height: '300mm'
@@ -450,6 +400,6 @@ class SalesController < ApplicationController
 
   # Never trust parameters from the scary internet, only allow the white list through.
   def sale_params
-    params.require(:sale).permit(:customer_id, :saletype, :amount, :tax, :discount, :total, :date_sale, :user_id, :seller_id, :sale_code, :credit_note)
+    params.require(:sale).permit(:customer_id, :saletype, :amount, :tax, :discount, :total, :date_sale, :user_id, :seller_id, :sale_code, :credit_note, :open_cash_register_id)
   end
 end

+ 12 - 13
app/views/customers/show.json.jbuilder

@@ -1,18 +1,17 @@
 json.extract! @customer, :id, :nick_name, :credit ,:credit_limit, :created_at, :updated_at, :status
 
-	json.customer_debiting do
-		debiting = 0
+json.customer_debiting do
+	@debiting = @customer.credits.activos.sum(:rest)
+	json.customer_debiting @debiting
+end
 
-		 @customer.credits.activos.each do |credit|
-		 	debiting = debiting + credit.rest
-		 end
+json.available_credit do
+	json.available_credit @customer.credit_limit - @debiting
+end
 
-		json.customer_debiting debiting
+json.customer_payment do
+	payment = CreditPayment.where(customer_id: @customer.id).order("date_payment DESC").first
+	if !payment.blank?
+		json.customer_payment payment.date_payment.strftime("%d/%m/%Y")
 	end
-
-	json.customer_payment do
-		payment = CreditPayment.where(:customer_id => @customer.id).order("date_payment DESC").first
-		if !payment.blank?
-			json.customer_payment payment.date_payment.strftime("%d/%m/%Y")
-		end
-	end
+end

+ 8 - 18
app/views/pre_sales/_pre_sale.html.erb

@@ -3,9 +3,7 @@
     #
     <%= hidden_field_tag 'include_tax', pre_sale.product.include_sale_tax %>
   </td>
-  <td>
-    <%= pre_sale.product.sku %>
-  </td>
+  <td><%= pre_sale.product.sku %></td>
   <td class="text-center">
     <img src="<%= pre_sale.product.small_img %>" width="100" height="100"/>
   </td>
@@ -16,24 +14,16 @@
   <td>
     <input type="number" min="1" id="quantity_<%= pre_sale.id %>" class="form-control" id="quantity_<%= pre_sale.id %>" oninput="calculatePrice($(this))" value="<%= pre_sale.quantity %>" pattern="^[0-9]*[1-9][0-9]*$" title="La cantidad debe de ser mayor o igual a 1" required>
   </td>
-  <td>
-    <%= pre_sale.unit_price %>
-  </td>
-  <td>
-    <%= pre_sale.tax %>
-  </td>
-  <td>
-    <%= pre_sale.discount %>
-  </td>
-  <td>
-    <%= pre_sale.total %>
-  </td>
+  <td><%= pre_sale.unit_price %></td>
+  <td><%= pre_sale.tax %></td>
+  <td><%= pre_sale.discount %></td>
+  <td><%= pre_sale.total %></td>
   <td style="width:5%">
     <% if pre_sale.haggle == 0 %>
-      <%= link_to add_sale_haggle_path(pre_sale), :remote => true, :class => "btn btn-icon-only btn-primary hagglebutton", :title=>"Agregar regate" do %> 
+      <%= link_to add_sale_haggle_path(pre_sale), :remote => true, :class => "btn btn-icon-only btn-primary hagglebutton", :title=>"Agregar regate" do %>
         <i class="fa fa-tag"></i>
-      <% end %>      
+      <% end %>
     <% end %>
-    <button type="button" class="btn btn-icon-only btn-danger" onclick="deleteRow($(this))"><i class="fa fa-trash-o"></i></button>    
+    <button type="button" class="btn btn-icon-only btn-danger" onclick="deleteRow($(this))"><i class="fa fa-trash-o"></i></button>
   </td>
 </tr>

+ 7 - 9
app/views/pre_sales/create.js.erb

@@ -2,13 +2,13 @@
 	$("#error_explanation").empty();
 	$('#error_explanation').removeClass('hidden');
 	$("#error_explanation").append($("<div class='alert alert-danger'></div>"));
-    <% @pre_sale.errors.values.each do |message| %>
-        $("#error_explanation div").append($("<li />").html("<%= message.first.to_s %>"));
-        toastr["error"]("<%= message.first.to_s %>");
-    <% end %>
+  <% @pre_sale.errors.values.each do |message| %>
+    $("#error_explanation div").append($("<li />").html("<%= message.first.to_s %>"));
+    toastr["error"]("<%= message.first.to_s %>");
+  <% end %>
 <% elsif defined? @pre_sale %>
-	if($("#error_explanation_move").is(':visible')) {
-		$("#error_explanation_move").addClass('hidden');
+	if($("#error_explanation").is(':visible')) {
+		$("#error_explanation").addClass('hidden');
 	}
 	var table = $('#products_table').DataTable();
 	var newRow = $('<%= j render (@pre_sale) %>');
@@ -16,9 +16,7 @@
 	newRow.find('td:eq(0)').html(newRow.find('td:eq(0)').html().replace('#', x.fnGetData().length + 1));
 	table.row.add(newRow).draw();
 
-	//bloquear el agregar cliente para mantener congruencia
-    $('#customer_remote').removeAttr("href");
-    $('#customer_remote').attr("disabled", true);	
+  $('#customer_remote').remove();
 <% else %>
 	toastr["error"]("Error, No se encontró el producto.");
 <% end %>

+ 310 - 273
app/views/sales/_form.html.erb

@@ -1,12 +1,12 @@
 <%= form_for(@sale, :remote => true, :html => {:class=>"form-horizontal", :id=> "sale_form"}) do |f| %>
 	<div class="portlet-body form">
 		<!-- este error explanation se usa para mostrar errores de presales e inventarios -->
-		<div id="error_explanation"></div>
+		<!-- <div id="error_explanation"></div> -->
 		<!-- este error explanation es cuando falla alguna validacion de la venta en sí -->
 		<div class="alert alert-danger hidden" id="error_explanation_for_sale"></div>
 		<div class="row">
 			<!-- cuando no hay caja abierta -->
-			<% if @opened_cash_registers.blank?%>
+			<% if @opened_cash_registers.blank? %>
 				<div class="alert alert-block alert-danger fade in">
 	        <h4 class="alert-heading">¡AVISO! no hay caja abierta</h4>
 	        <p> Para realizar una venta es necesario abrir una caja registradora. </p>
@@ -57,11 +57,11 @@
 					<% end %>
 					<div class="input-group col-md-6 select2-bootstrap-prepend">
 						<% if @sale.open_cash_register.nil? %>
-							<%= f.select :open_cash_register_id, Pointsale.find(current_user.pointsale_id).open_cash_registers.abiertas.map{|o| [o.cash_register.name, o.id]}, {:prompt => "Seleccione"}, { :class => 'form-control select2', :disabled => @disabled_select } %>
+							<%= f.select :open_cash_register_id, Pointsale.find(current_user.pointsale_id).open_cash_registers.abiertas.map { |o| [o.cash_register.name, o.id] }, {:prompt => "Seleccione"}, { :class => 'form-control select2', :disabled => @disabled_select } %>
 						<% else %>
-              <%= f.select :open_cash_register_id, @opened_cash_registers.map{|o| [o.cash_register.name, o.id]}, {:include_blank => "Seleccione", :selected => @sale.open_cash_register.id}, {:class => "form-control", :disabled => true }   %>
+              <%= f.select :open_cash_register_id, @opened_cash_registers.map{|o| [o.cash_register.name, o.id]}, {:include_blank => "Seleccione", :selected => @sale.open_cash_register.id}, {:class => "form-control", :disabled => true } %>
 						<% end %>
-						<%= f.hidden_field :open_cash_register_id, {:id => 'open_cash'} %>
+						<%= f.hidden_field :open_cash_register_id, { :id => 'open_cash' } %>
 					</div>
 				</div>
 				<!-- cliente -->
@@ -69,14 +69,13 @@
 					<%= f.label :customer_id, "Cliente", {:class=>"col-md-3 control-label"} do %> Cliente
 					<span class="required">*</span>
 					<% end %>
-
 					<div class="input-group col-md-6 select2-bootstrap-prepend" style="float:left">
-						<%= f.collection_select :customer_id, Customer.vigentes, :id, :nick_name, {:prompt => "Seleccione", :selected => @sale.customer_id.present? ? @sale.customer_id : @general_public_id}, {:class => "form-control select2", :disabled => @disabled_select} %>
+						<%= f.collection_select :customer_id, Customer.vigentes, :id, :nick_name, { :prompt => "Seleccione", :selected => @sale.customer_id.present? ? @sale.customer_id : @general_public_id}, { :class => "form-control select2" } %>
 						<%= f.hidden_field :customer_id, :value => @sale.customer_id.present? ? @sale.customer_id : @general_public_id, :id => 'customer' %>
 					</div>
 					<div class="col-md-2">
 						<% if @pre_sales.count == 0 %>
-							<%= link_to new_customer_path, :remote => true, :class=>"btn btn-success", :id => :customer_remote  do %>
+							<%= link_to new_customer_path, remote: true, class: "btn btn-success", id: :customer_remote do %>
 								<i class="fa fa-plus"></i>
 							<% end %>
 						<% end %>
@@ -123,24 +122,28 @@
 				<div class="panel panel-info">
 					<!-- Default panel contents -->
 					<div class="panel-heading">
-							<h3 class="panel-title" id="customer_name"></h3>
+						<h3 class="panel-title" id="customer_name"></h3>
 					</div>
 					<!-- List group -->
 					<ul class="list-group">
-							<li class="list-group-item"> ¿Tiene crédito?
-									<span class="badge badge-info badge-roundless" id="has_credit"></span>
-							</li>
-							<li class="list-group-item"> Adeudo del cliente
-									<span class="badge badge-info badge-roundless" id="customer_debiting"></span>
-							</li>
-							<li class="list-group-item"> Límite de crédito
-									<span class="badge badge-info badge-roundless" id="credit_limit"></span>
-							</li>
-							<li class="list-group-item"> Fecha de último abono
-									<span class="badge badge-info badge-roundless" id="last_credit_payment"></span>
-							</li>
+						<li class="list-group-item"> ¿Tiene crédito?
+							<span class="badge badge-info badge-roundless" id="has_credit"></span>
+						</li>
+						<li class="list-group-item"> Adeudo del cliente
+							<span class="badge badge-info badge-roundless" id="customer_debiting"></span>
+						</li>
+						<%= hidden_field_tag :available_credit, 0 %>
+						<li class="list-group-item"> Límite de crédito
+							<span class="badge badge-info badge-roundless" id="credit_limit"></span>
+						</li>
+						<li class="list-group-item"> Fecha de último abono
+							<span class="badge badge-info badge-roundless" id="last_credit_payment"></span>
+						</li>
 					</ul>
 				</div>
+				<div class="from-group">
+					<div id="error_explanation"></div>
+				</div>
 			</div>
 		</div>
 
@@ -149,10 +152,8 @@
 		<div class="row">
 			<div class="col-md-12">
 				<div class="note note-info">
-						<h4 class="block">¡Nota!</h4>
-						<p> Para hacer una busqueda avanzada utiliza el siguiente formato, nombre del producto :atributo a buscar<br>
-						ejemplo. <strong>blusa :verde</strong> (Solo se puede buscar un atributo, ya sea estilo, talla ó color).</p>
-
+					<h4 class="block">¡Nota!</h4>
+					<p> Para hacer una búsqueda avanzada utiliza el siguiente formato, nombre del producto :atributo a buscar<br> ejemplo. <strong>blusa :verde</strong> (Sólo se puede buscar un atributo, ya sea estilo, talla o color).</p>
 				</div>
 			</div>
 			<div class='col-md-12'>
@@ -283,23 +284,6 @@
 			$('#save_sale').attr('disabled', false);
 		});
 
-		$('#sale_customer_id').on('change', function() {
-			$(this).attr('disabled', true);
-			$('#customer').val($(this).val());
-
-			//bloquear boton para agregar nuevo cliente ya que se selecciono o agrego uno
-			$('#customer_remote').removeAttr("href");
-			$('#customer_remote').attr("disabled", true);
-
-			// activar apartado y el credito se activa dependiendo si tiene o no,
-			// en la funcion fillCustomer
-			if ($('#sale_customer_id').val() != '<%= @general_public_id %>') {
-				$('#types_reserved').attr('disabled', false);
-				$('#types_reserved').closest('label').removeClass('disabled');
-			}
-			fillCustomerInfo();
-		});
-
 		$('#sale_open_cash_register_id').on('change', function() {
 			$(this).attr('disabled', true);
 			$('#open_cash').val($(this).val());
@@ -338,270 +322,323 @@
 		});
 	});
 
-		$('body').barcodeListener().on('barcode.valid', function(e, code) {
-			findProductByBarcode(code);
-		});
-
-		// initialize bloodhound engine
-		var bloodhound = new Bloodhound({
-			datumTokenizer: function (d) {
-				return Bloodhound.tokenizers.whitespace(d.value);
-			},
-			queryTokenizer: Bloodhound.tokenizers.whitespace,
-			remote: {
-				url: $('#typeahead').data('option-url'),
-				wildcard: '%QUERY'
-			}
-		});
-		bloodhound.initialize();
+	$('#sale_customer_id').on('change', function() {
+		// $(this).attr('disabled', true);
+		$('#customer').val($(this).val());
 
+		//bloquear boton para agregar nuevo cliente ya que se selecciono o agrego uno
+		$('#customer_remote').remove();
+		// $('#customer_remote').attr("disabled", true);
 
-		$('#typeahead').typeahead(
-			{
-				minLength: 3
-			},
-			{
-				displayKey: 'name',
-				source: bloodhound.ttAdapter(),
-				limit: Infinity,
-				templates: {
-					empty: [
-						'<div class="empty-message">',
-							'No se encontró ningun producto. Favor de verificar',
-						'</div>'
-					].join('\n'),
-					 suggestion: Handlebars.compile(
-							'<div class="media">' +
-								'<div class="pull-left">' +
-										'<div class="media-object">' +
-												'<img src="{{small_img}}" width="50" height="50"/>' +
-										'</div>' +
-								'</div>' +
-								'<div class="media-body">' +
-										'<h4 class="media-heading"><strong>{{sku}}</strong> | {{name}}</h4>' +
-										'<p>{{barcode}}</p>' +
-										'<p>{{description}}</p>' +
-										'<p>{{display_attributes}}</p>' +
-								'</div>' +
-							'</div>')
-				}
-		});
+		// activar apartado y el credito se activa dependiendo si tiene o no,
+		// en la funcion fillCustomer
+		if ($('#sale_customer_id').val() != '<%= @general_public_id %>') {
+			$('#types_reserved').attr('disabled', false);
+			$('#types_reserved').closest('label').removeClass('disabled');
+		}
+		updatePreSale($(this).val());
+	});
 
-		// this is the event that is fired when a user clicks on a suggestion
-		$('#typeahead').bind('typeahead:selected', function(event, datum, name) {
-			selectedProduct = datum;
+	$('#types_cash, #types_credit, #types_reserved').on('change', function() {
+		$("#sale_saletype").val($(this).val());
+		if($(this).val() == "cash"){
+			$("#save_sale").attr("disabled", false);
+		}
+		$.ajax({
+      type: "PUT",
+      url: "/update_saletype/" + $(this).val(),
+      dataType: "json",
+      success: function(xhr, status, error) {
+        toastr["warning"]("Se actualizó el tipo de venta");
+      },
+			error: function (xhr, status, errorThrown) {
+				toastr["error"](xhr.responseText.substr(3, (xhr.responseText.length -6)));
+			}
+    });
+	});
 
-			var openCash = $('#sale_open_cash_register_id').val();
-			var customer = $('#sale_customer_id').val();
-			var saleType = $('#sale_saletype').val();
-			var seller = $('#sale_seller_id').val();
+	function updatePreSale(customer_id) {
+		$.ajax({
+      type: "PUT",
+      url: "/update_presale_customer/" + customer_id,
+      dataType: "json",
+      success: function(xhr, status, error) {
+        toastr["warning"]("Se actualizó el cliente de venta");
+        fillCustomerInfo();
+      }
+    });
+	}
+
+	$('body').barcodeListener().on('barcode.valid', function(e, code) {
+		findProductByBarcode(code);
+	});
 
-			if (openCash && customer && saleType && seller ) {
-				$('#products_new').attr('disabled', false);
-			} else {
-				toastr["error"]("No ha ingresado toda la informacion requerida.");
+	// initialize bloodhound engine
+	var bloodhound = new Bloodhound({
+		datumTokenizer: function (d) {
+			return Bloodhound.tokenizers.whitespace(d.value);
+		},
+		queryTokenizer: Bloodhound.tokenizers.whitespace,
+		remote: {
+			url: $('#typeahead').data('option-url'),
+			wildcard: '%QUERY'
+		}
+	});
+	bloodhound.initialize();
+
+
+	$('#typeahead').typeahead(
+		{
+			minLength: 3
+		},
+		{
+			displayKey: 'name',
+			source: bloodhound.ttAdapter(),
+			limit: Infinity,
+			templates: {
+				empty: [
+					'<div class="empty-message">',
+						'No se encontró ningun producto. Favor de verificar',
+					'</div>'
+				].join('\n'),
+				 suggestion: Handlebars.compile(
+						'<div class="media">' +
+							'<div class="pull-left">' +
+									'<div class="media-object">' +
+											'<img src="{{small_img}}" width="50" height="50"/>' +
+									'</div>' +
+							'</div>' +
+							'<div class="media-body">' +
+									'<h4 class="media-heading"><strong>{{sku}}</strong> | {{name}}</h4>' +
+									'<p>{{barcode}}</p>' +
+									'<p>{{description}}</p>' +
+									'<p>{{display_attributes}}</p>' +
+							'</div>' +
+						'</div>')
 			}
+	});
 
-		});
+	// this is the event that is fired when a user clicks on a suggestion
+	$('#typeahead').bind('typeahead:selected', function(event, datum, name) {
+		selectedProduct = datum;
 
-		function addRow() {
-			if(selectedProduct) {
-				$('#pre_sale_customer_id').val($('#sale_customer_id').val());
-				$('#pre_sale_open_cash_register_id').val($('#sale_open_cash_register_id').val());
-				$('#pre_sale_sale_type').val($('#sale_saletype').val());
-				$('#pre_sale_product_id').val(selectedProduct.id);
-				$('#pre_sale_quantity').val(1);
-				$('#new_pre_sale').submit();
-				$('#typeahead').typeahead('val','');
-				$('#products_new').attr('disabled', true);
-			}
-		}
+		var openCash = $('#sale_open_cash_register_id').val();
+		var customer = $('#sale_customer_id').val();
+		var saleType = $('#sale_saletype').val();
+		var seller = $('#sale_seller_id').val();
 
-		function deleteRow(input) {
-			var table = $('#products_table').DataTable();
-			var idText = input.closest('tr').attr('id');
-			var preSaleId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
-			$.ajax({
-				type: "DELETE",
-				url: "/pre_sales/" + preSaleId,
-				dataType: "json",
-				data: "",
-				success: function(xhr, status, error) {
-					table.row(input.closest('tr')).remove().draw();
-					calculateTotals();
-				}
-			});
+		if (openCash && customer && saleType && seller ) {
+			$('#products_new').attr('disabled', false);
+		} else {
+			toastr["error"]("No ha ingresado toda la información requerida.");
 		}
+	});
 
-		function calculatePrice(input) {
-			if(input.val()) {
-				clearTimeout(timeout);
-				timeout = setTimeout(function () {
-					tax = 0;
-					quantity = parseInt(input.val());
-
-					var idText = input.closest('tr').attr('id');
-					var preSaleId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
-					$('#save_sale').attr('disabled', true);
-					$.ajax({
-							type: "PUT",
-							url: "/pre_sales/" + preSaleId,
-							dataType: "json",
-							data: {pre_sale: {quantity: input.val()}},
-							success: function(xhr, status, error) {
-
-								input.closest('tr').find('td:eq(6)').text(Math.round(xhr.tax * 100) / 100);
-
-								input.closest('tr').find('td:eq(7)').text(Math.round(xhr.discount * 100) / 100);
-
-								input.closest('tr').find('td:eq(8)').text(Math.round(xhr.total * 100) / 100);
-
-								calculateTotals();
-
-								$('#save_sale').attr('disabled', false);
-							},
-							error: function (xhr, status, errorThrown) {
-								toastr["error"](xhr.responseText.substr(3, (xhr.responseText.length -6)));
-							}
-					});
-				}, 500);
-			}
+	function addRow() {
+		if(selectedProduct) {
+			$('#pre_sale_customer_id').val($('#sale_customer_id').val());
+			$('#pre_sale_open_cash_register_id').val($('#sale_open_cash_register_id').val());
+			$('#pre_sale_sale_type').val($('#sale_saletype').val());
+			$('#pre_sale_product_id').val(selectedProduct.id);
+			$('#pre_sale_quantity').val(1);
+			$('#new_pre_sale').submit();
+			$('#typeahead').typeahead('val','');
+			$('#products_new').attr('disabled', true);
 		}
-
-		function calculateTotals() {
-			var amount = 0;
-			var discount = 0;
-			var tax = 0;
-			var total = 0;
-
-			if($('#products_table').dataTable().fnGetData().length > 0) {
-				$('#products_table tbody tr').each(function() {
-					quantity = parseFloat(($(this).find('td:nth-child(5) input').val()));
-					price = parseFloat($(this).find('td:nth-child(6)').text());
-					amount+= (quantity * price);
-				});
+	}
+
+	function deleteRow(input) {
+		var table = $('#products_table').DataTable();
+		var idText = input.closest('tr').attr('id');
+		var preSaleId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
+		$.ajax({
+			type: "DELETE",
+			url: "/pre_sales/" + preSaleId,
+			dataType: "json",
+			data: "",
+			success: function(xhr, status, error) {
+				table.row(input.closest('tr')).remove().draw();
+				calculateTotals();
 			}
+		});
+	}
+
+	function calculatePrice(input) {
+		if(input.val()) {
+			clearTimeout(timeout);
+			timeout = setTimeout(function () {
+				tax = 0;
+				quantity = parseInt(input.val());
+
+				var idText = input.closest('tr').attr('id');
+				var preSaleId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
+				$('#save_sale').attr('disabled', true);
+				$.ajax({
+						type: "PUT",
+						url: "/pre_sales/" + preSaleId,
+						dataType: "json",
+						data: { pre_sale: { quantity: input.val() } },
+						success: function(xhr, status, error) {
 
-			$('#products_table tbody tr td:nth-child(7)').each(function() {
-				 tax+= parseFloat($(this).text());
-			});
-			$('#products_table tbody tr td:nth-child(8)').each(function() {
-				 discount+= parseFloat($(this).text());
-			});
+							input.closest('tr').find('td:eq(6)').text(Math.round(xhr.tax * 100) / 100);
 
-			total = (amount - discount) + tax;
-			$('#tax').val(Math.round(tax * 100) / 100);
-			$('#discount').val(Math.round(discount * 100) / 100);
-			$('#amount').val(Math.round(amount * 100) / 100);
-			$('#total').val(Math.round(total * 100) / 100);
+							input.closest('tr').find('td:eq(7)').text(Math.round(xhr.discount * 100) / 100);
 
-		}
+							input.closest('tr').find('td:eq(8)').text(Math.round(xhr.total * 100) / 100);
 
-		function deletePreSales() {
-			$.ajax({
-				type: "get",
-				url:  '/delete_pre_sales',
-				dataType: 'json',
-				success: function(xhr, status, error) {
-					location.reload();
-				}
+							calculateTotals();
+
+							$('#save_sale').attr('disabled', false);
+						},
+						error: function (xhr, status, errorThrown) {
+							input.val(1);
+							toastr["error"](xhr.responseText.substr(3, (xhr.responseText.length -6)));
+						}
+				});
+			}, 500);
+		}
+	}
+
+	function calculateTotals() {
+		var amount = 0;
+		var discount = 0;
+		var tax = 0;
+		var total = 0;
+
+		if($('#products_table').dataTable().fnGetData().length > 0) {
+			$('#products_table tbody tr').each(function() {
+				quantity = parseFloat(($(this).find('td:nth-child(5) input').val()));
+				price = parseFloat($(this).find('td:nth-child(6)').text());
+				amount += (quantity * price);
 			});
 		}
 
-		function addSale() {
-			var $form = $('#sale_form');
-			var table = $('#products_table').dataTable();
+		$('#products_table tbody tr td:nth-child(7)').each(function() {
+			tax += parseFloat($(this).text());
+		});
+		$('#products_table tbody tr td:nth-child(8)').each(function() {
+			discount += parseFloat($(this).text());
+		});
 
-			if ($form[0].checkValidity()) {
-				if(table.fnGetData().length > 0) {
-					$('#sale_form').submit();
-					$('#save_sale').attr('disabled', true);
-				} else {
-					toastr["error"]("Error, Se debe agregar al menos un producto.");
-				}
-			} else {
-				toastr["error"]("La cantidad de los productos debe de ser mayor o igual a 1.");
+		total = (amount - discount) + tax;
+		$('#tax').val(Math.round(tax * 100) / 100);
+		$('#discount').val(Math.round(discount * 100) / 100);
+		$('#amount').val(Math.round(amount * 100) / 100);
+		$('#total').val(Math.round(total * 100) / 100);
+		if(total < parseFloat($("#available_credit").val())) {
+			$('#types_credit').attr('disabled', false);
+			$('#types_credit').closest('label').removeClass('disabled');
+		}
+	}
+
+	function deletePreSales() {
+		$.ajax({
+			type: "get",
+			url: '/delete_pre_sales',
+			dataType: 'json',
+			success: function(xhr, status, error) {
+				location.reload();
 			}
+		});
+	}
+
+	function addSale() {
+		var $form = $('#sale_form');
+		var table = $('#products_table').dataTable();
 
+		if ($form[0].checkValidity()) {
+			if(table.fnGetData().length > 0) {
+				$('#sale_form').submit();
+				$('#save_sale').attr('disabled', true);
+			} else {
+				toastr["error"]("Error, Se debe agregar al menos un producto.");
+			}
+		} else {
+			toastr["error"]("La cantidad de los productos debe de ser mayor o igual a 1.");
 		}
+	}
 
-		function fillCustomerInfo() {
-			var customerId = $('#customer').val();
-			var public_customer = "<%= @general_public_id %>";
-			if(customerId && customerId != public_customer) {
-				$.ajax({
-					type: "get",
-					url:  '/customers/' + customerId + ".json",
-					dataType: 'json',
-					success: function(data) {
-						if(data.credit) {
-								$('#customer_name').text(data.nick_name);
-								$('#has_credit').text(data.credit ? 'SI' : 'NO');
-								// $('#customer_debiting').text(formatter.format(data.customer_debiting.customer_debiting));
-								// $('#credit_limit').text(formatter.format(data.credit_limit));
-								$('#customer_debiting').text(accounting.formatMoney(data.customer_debiting.customer_debiting));
-								$('#credit_limit').text(accounting.formatMoney(data.credit_limit));
-								if(data.customer_payment) {
-									$('#last_credit_payment').text(data.customer_payment.customer_payment);
-								}
-								$('#customer_info').removeClass('hidden');
-								<% if @pre_sales.count == 0 %>
-									$('#types_credit').attr('disabled', false);
-									$('#types_credit').closest('label').removeClass('disabled');
-								<% end %>
-						} else {
-							// DISABLEAR EL DE CREDITO
+	function fillCustomerInfo() {
+		var customerId = $('#customer').val();
+		var public_customer = "<%= @general_public_id %>";
+		if(customerId) {
+			$.ajax({
+				type: "get",
+				url: '/customers/' + customerId + ".json",
+				dataType: 'json',
+				success: function(data) {
+					if(data.credit) {
+						$('#customer_name').text(data.nick_name);
+						$('#has_credit').text(data.credit ? 'SI' : 'NO');
+						// $('#customer_debiting').text(formatter.format(data.customer_debiting.customer_debiting));
+						// $('#credit_limit').text(formatter.format(data.credit_limit));
+						$('#customer_debiting').text(accounting.formatMoney(data.customer_debiting.customer_debiting));
+						$('#credit_limit').text(accounting.formatMoney(data.credit_limit));
+						if(data.customer_payment) {
+							$('#last_credit_payment').text(data.customer_payment.customer_payment);
+						}
+						$('#customer_info').removeClass('hidden');
+						$("#available_credit").val(data.available_credit.available_credit)
+						if(parseInt($("#total").val()) > parseInt(data.available_credit.available_credit)) {
+							$('#types_cash').click();
 							$('#types_credit').attr('disabled', true);
 							$('#types_credit').closest('label').addClass('disabled');
+						} else {
+							$('#types_credit').attr('disabled', false);
+							$('#types_credit').closest('label').removeClass('disabled');
 						}
+					} else {
+						// DISABLEAR EL DE CREDITO
+						$("#customer_info").addClass("hidden");
+						$('#types_cash').click();
+						$('#types_credit').attr('disabled', true);
+						$('#types_credit').closest('label').addClass('disabled');
 					}
-				});
-			}
+				}
+			});
 		}
+	}
 
-		function enumeratePreSales() {
-			if($('#reset_pre_sales').prop("disabled") == false) {
-				var table = $('#products_table').dataTable();
-				var counter = 1;
-				$('#products_table tbody tr').each(function() {
-					$(this).find('td:eq(0)').html($(this).find('td:eq(0)').html().replace('#', counter));
-					counter++;
-				});
-			}
+	function enumeratePreSales() {
+		if($('#reset_pre_sales').prop("disabled") == false) {
+			var table = $('#products_table').dataTable();
+			var counter = 1;
+			$('#products_table tbody tr').each(function() {
+				$(this).find('td:eq(0)').html($(this).find('td:eq(0)').html().replace('#', counter));
+				counter++;
+			});
 		}
+	}
 
-		function generateSaleCode() {
-			if($('#sale_open_cash_register_id').val()) {
-				$.ajax({
-					type: "get",
-					url:  '/get_next_sale_code/' + $('#sale_open_cash_register_id').val(),
-					dataType: 'text',
-					success: function(data) {
-						$('#sale_sale_code').val(data);
-					},
-				});
-			}
+	function generateSaleCode() {
+		if($('#sale_open_cash_register_id').val()) {
+			$.ajax({
+				type: "get",
+				url: '/get_next_sale_code/' + $('#sale_open_cash_register_id').val(),
+				dataType: 'text',
+				success: function(data) {
+					$('#sale_sale_code').val(data);
+				},
+			});
 		}
-
-		function findProductByBarcode(barcode) {
-			var customer = $('#sale_customer_id').val();
-			var openCash = $('#sale_open_cash_register_id').val();
-			var saleType = $('form input[type=radio]:checked').val();
-			var seller = $('#sale_seller_id').val();
-			if(customer && openCash && saleType && seller) {
-				$.ajax({
-					type: "get",
-					url:  '/add_pre_sale_by_barcode/' + barcode + "/" + customer + "/" + openCash + "/" + saleType,
-					dataType: 'script',
-					success: function(data) {
-						calculateTotals();
-					},
-				});
-			} else {
-				toastr["error"]("Falta seleccionar datos del formulario.");
-			}
+	}
+
+	function findProductByBarcode(barcode) {
+		var customer = $('#sale_customer_id').val();
+		var openCash = $('#sale_open_cash_register_id').val();
+		var saleType = $('form input[type=radio]:checked').val();
+		var seller = $('#sale_seller_id').val();
+		if(customer && openCash && saleType && seller) {
+			$.ajax({
+				type: "get",
+				url: '/add_pre_sale_by_barcode/' + barcode + "/" + customer + "/" + openCash + "/" + saleType,
+				dataType: 'script',
+				success: function(data) {
+					calculateTotals();
+				},
+			});
+		} else {
+			toastr["error"]("Falta seleccionar datos del formulario.");
 		}
+	}
 </script>
-
-
-

+ 2 - 0
config/routes.rb

@@ -150,12 +150,14 @@ Rails.application.routes.draw do
   get 'find_sales_by_dates_or_code' => 'sales#find_sales_by_dates_or_code', defaults: { format: 'js' }
   get 'sales_per_month_report' => 'sales#sales_per_month_report'
   get 'sales_per_month' => 'sales#sales_per_month', defaults: { format: 'js' }
+  put 'update_presale_customer/:customer_id' => 'pre_sales#update_presale_customer', as: 'update_presale_customer', format: :json
 
   resources :pre_sales, except: [:new, :show] do
     post 'create' => 'pre_sales#create', defaults: { format: 'js' }
     put 'edit' => 'pre_sales#update', defaults: { format: 'js' }
   end
   get 'add_pre_sale_by_barcode/:barcode/:customer_id/:open_cash_register_id/:sale_type' => 'pre_sales#add_pre_sale_by_barcode', defaults: { format: 'js' }
+  put 'update_saletype/:type' => 'pre_sales#update_saletype'
 
   resources :open_cash_registers do
     post 'create' => 'open_cash_registers#create', defaults: { format: 'js' }