Sfoglia il codice sorgente

Permissions for super user

Jacqueline Maldonado 7 anni fa
parent
commit
9e9650793d
40 ha cambiato i file con 1658 aggiunte e 1765 eliminazioni
  1. 33 27
      app/controllers/application_controller.rb
  2. 1 1
      app/controllers/cash_outs_controller.rb
  3. 1 1
      app/controllers/commissions_controller.rb
  4. 1 1
      app/controllers/dashboard_controller.rb
  5. 6 5
      app/controllers/expenses_controller.rb
  6. 84 85
      app/controllers/expensesconcepts_controller.rb
  7. 1 6
      app/controllers/pointsales_controller.rb
  8. 24 35
      app/controllers/product_wastes_controller.rb
  9. 1 1
      app/controllers/products_returns_controller.rb
  10. 86 102
      app/controllers/purchases_controller.rb
  11. 35 35
      app/controllers/sales_controller.rb
  12. 1 1
      app/controllers/transfers_controller.rb
  13. 12 0
      app/helpers/purchases_helper.rb
  14. 4 5
      app/views/available_products/_edit_price.html.erb
  15. 3 5
      app/views/available_products/stock_by_pointsale.html.erb
  16. 8 5
      app/views/cash_outs/_cash_out.html.erb
  17. 10 10
      app/views/cash_outs/index.html.erb
  18. 185 187
      app/views/cash_outs/show.html.erb
  19. 128 131
      app/views/commissions/_sellers_for_commissions.html.erb
  20. 58 72
      app/views/customers/customer_sales.html.erb
  21. 78 78
      app/views/dashboard/_dashboard_for_admin.html.erb
  22. 1 1
      app/views/dashboard/index.html.erb
  23. 68 80
      app/views/expenses/_form.html.erb
  24. 3 3
      app/views/expenses/index.html.erb
  25. 102 103
      app/views/expensesconcepts/index.html.erb
  26. 8 10
      app/views/product_wastes/index.html.erb
  27. 192 195
      app/views/products/edit_variants.html.erb
  28. 2 2
      app/views/products/index.html.erb
  29. 24 61
      app/views/products/show.html.erb
  30. 1 2
      app/views/products_returns/_form.html.erb
  31. 2 2
      app/views/products_returns/index.html.erb
  32. 379 383
      app/views/purchases/_form.html.erb
  33. 15 15
      app/views/purchases/_purchase.html.erb
  34. 48 62
      app/views/purchases/index.html.erb
  35. 11 11
      app/views/sales/_sale_reserved.html.erb
  36. 2 2
      app/views/sales/index.html.erb
  37. 11 11
      app/views/sales/sales_reserved.html.erb
  38. 27 27
      app/views/transfers/_form.html.erb
  39. 1 1
      app/views/transfers/index.html.erb
  40. 1 1
      app/views/transfers/new.html.erb

+ 33 - 27
app/controllers/application_controller.rb

@@ -75,36 +75,40 @@ class ApplicationController < ActionController::Base
 
   def find_from_stock
     query = params[:query]
+
+    location =
+      if current_user.usertype == "S"
+        Warehouse.find(current_user.warehouse_id).products
+      else
+        Pointsale.find(current_user.pointsale_id).products
+      end
+
     if query.include? ':' # search with attributes
       query_array = query.split(':')
       product_name = query_array[0]
       query_array.shift # delete the name of the product from the array to iterate the attributes
       attrs_query_string = ''
       query_array.each do |attribute|
-        if attribute.present?
-          attr_type = case attribute[0]
-                      when 'c'
-                        'colors'
-                      when 't'
-                        'sizes'
-                      when 'e'
-                        'styles'
-                      end
-          attribute[0] = "" # delete the attribute type character
-          attrs_query_string.concat(" AND attributes_json::json->>'#{attr_type}' ilike '%#{attribute}%'")
-        else
-          next
-        end
+        next if attribute.nil?
+        attr_type =
+          case attribute[0]
+          when 'c'
+            'colors'
+          when 't'
+            'sizes'
+          when 'e'
+            'styles'
+          end
+        attribute[0] = "" # delete the attribute type character
+        attrs_query_string.concat(" AND attributes_json::json->>'#{attr_type}' ilike '%#{attribute}%'")
       end
+      consult = location.name_sku_barcode_attribute_like(product_name, attrs_query_string)
     else
       product_name = query
+      consult = location.name_sku_barcode_like(params[:query])
     end
 
-    if current_user.usertype == 'S'
-      render json: query.include?(":") ? Warehouse.find(current_user.warehouse_id).products.name_sku_barcode_attribute_like(product_name, attrs_query_string).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes]) : Warehouse.find(current_user.warehouse_id).products.name_sku_barcode_like(params[:query]).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes])
-    else
-      render json: query.include?(":") ? Pointsale.find(current_user.pointsale_id).products.name_sku_barcode_attribute_like(product_name, attrs_query_string).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes]) : Pointsale.find(current_user.pointsale_id).products.name_sku_barcode_like(params[:query]).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes])
-    end
+    render json: consult.where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes])
   end
 
   # rubocop:disable Metrics/BlockNesting
@@ -216,14 +220,16 @@ class ApplicationController < ActionController::Base
   end
 
   def get_next_expense_code
-    if current_user.usertype == 'A'
-      next_id = Expense.where("expense_code ilike ?", '%ADM%').count.next
-      render json: "ADM-E-#{next_id}"
-    else
-      pointsale = OpenCashRegister.find(params[:open_cash_register_id]).cash_register.pointsale
-      next_id = pointsale.expenses.count.next
-      render json: "#{pointsale.prefix}-E-#{next_id}"
-    end
+    code =
+      if current_user.usertype == "A" || current_user.usertype == "SS"
+        next_id = Expense.where("expense_code ilike ?", '%ADM%').count.next
+        "ADM-E-#{next_id}"
+      else
+        pointsale = OpenCashRegister.find(params[:open_cash_register_id]).cash_register.pointsale
+        next_id = pointsale.expenses.count.next
+        "#{pointsale.prefix}-E-#{next_id}"
+      end
+    render json: code
   end
 
   def products_by_category_pointsale

+ 1 - 1
app/controllers/cash_outs_controller.rb

@@ -15,7 +15,7 @@ class CashOutsController < ApplicationController
   # GET /cash_outs.json
   def index
     case current_user.usertype
-    when "A"
+    when "A", "SS"
       @cash_outs = CashOut.all.includes(:open_cash_register, :user, :received_by).order('cash_outs.created_at desc')
     when "G"
       @cash_outs = Pointsale.find(current_user.pointsale_id).cash_outs.includes(:open_cash_register, :user, :received_by).order('cash_outs.created_at desc')

+ 1 - 1
app/controllers/commissions_controller.rb

@@ -11,7 +11,7 @@ class CommissionsController < ApplicationController
   # GET /commissions
   # GET /commissions.json
   def index
-    @commissions = current_user.usertype == 'A' ? Commission.all.includes(:pointsale, :user).order('created_at desc') : Commission.includes(:pointsale, :user).where(pointsale_id: current_user.pointsale_id).order('created_at desc')
+    @commissions = current_user.usertype == "A" || current_user.usertype == "SS" ? Commission.all.includes(:pointsale, :user).order('created_at desc') : Commission.includes(:pointsale, :user).where(pointsale_id: current_user.pointsale_id).order('created_at desc')
   end
 
   # GET /commissions/1

+ 1 - 1
app/controllers/dashboard_controller.rb

@@ -1,7 +1,7 @@
 class DashboardController < ApplicationController
   def index
     @open_cash = false
-    if current_user.usertype == 'A'
+    if current_user.usertype == "A" || current_user.usertype == "SS"
       # obtener ingresos por punto de venta
       @incomings = ActionController::Base.helpers.sanitize(CashRegistersMove.incomings_per_period('day'))
       # obtener ranking de productos y prepararlo para mandarlo al view

+ 6 - 5
app/controllers/expenses_controller.rb

@@ -14,7 +14,7 @@ class ExpensesController < ApplicationController
   # GET /expenses.json
   def index
     case current_user.usertype
-    when "A"
+    when "A", "SS"
       @from_pointsale = Expense.where.not(open_cash_register_id: nil).includes(:expensesconcept).order(" id DESC ")
       @general_expenses = Expense.where(open_cash_register_id: nil).includes(:expensesconcept).order(" id DESC ")
     when "G"
@@ -50,7 +50,7 @@ class ExpensesController < ApplicationController
       @concept_purchase_payment = Expensesconcept.find_by(expense_from_purchase: 1)
       @expense.status = :active
 
-      if current_user.usertype == "A"
+      if current_user.usertype == "A" || current_user.usertype == "SS"
         @expense.skip_open_cash_validation = true
         @expense.skip_open_cash_has_money = true
       else
@@ -67,7 +67,7 @@ class ExpensesController < ApplicationController
           end
         end
         # movimiento de efectivo
-        if current_user.usertype != "A"
+        if current_user.usertype != "A" || current_user.usertype != "SS"
           move = CashRegistersMove.new
           move.skip_received_validation = true
           move.expense_id = @expense.id
@@ -110,7 +110,7 @@ class ExpensesController < ApplicationController
   # DELETE /expenses/1.json
   def destroy
     respond_to do |format|
-      if current_user.usertype == 'A'
+      if current_user.usertype == "A" || current_user.usertype == "SS"
         @expense.skip_open_cash_validation = true
       end
 
@@ -129,7 +129,8 @@ class ExpensesController < ApplicationController
 
   def set_data
     @is_cashier = false
-    if current_user.usertype != "A"
+
+    if current_user.usertype != "A" && current_user.usertype != "SS"
       @expenses_concepts = Array.new
       Expensesconcept.where("status = 1 and allpoints = 'true'").each do |expense|
         @expenses_concepts << expense

+ 84 - 85
app/controllers/expensesconcepts_controller.rb

@@ -1,26 +1,26 @@
 class ExpensesconceptsController < ApplicationController
-	##--- Abilities
-	load_and_authorize_resource
+  ##--- Abilities
+  load_and_authorize_resource
 
-	##--- Breadcrum_rails
-	add_breadcrumb I18n.t("breadcrumbs." + controller_name), :expensesconcepts_path
-	add_breadcrumb "Nuevo Concepto de egreso" , :new_expensesconcept_path, only: :new
-	add_breadcrumb "Detalle del Concepto de egreso" , :expensesconcept_path, only: :show
-	add_breadcrumb "Editar Concepto de egreso" , :edit_expensesconcept_path, only: :edit
+  ##--- Breadcrum_rails
+  add_breadcrumb I18n.t("breadcrumbs." + controller_name), :expensesconcepts_path
+  add_breadcrumb "Nuevo Concepto de egreso", :new_expensesconcept_path, only: :new
+  add_breadcrumb "Detalle del Concepto de egreso", :expensesconcept_path, only: :show
+  add_breadcrumb "Editar Concepto de egreso", :edit_expensesconcept_path, only: :edit
 
-	before_action :set_expensesconcept, only: [:show, :edit, :update, :destroy]
-	before_action :get_filters, only: [:index, :show, :edit, :new]
-	# before_action :get_pointsales, only: [:create, :update]
+  before_action :set_expensesconcept, only: [:show, :edit, :update, :destroy]
+  before_action :get_filters, only: [:index, :show, :edit, :new]
+  # before_action :get_pointsales, only: [:create, :update]
 
-	# GET /expensesconcepts
-	# GET /expensesconcepts.json
-	def index
-    @concept_purchase_payment = Expensesconcept.find_by(:expense_from_purchase => 1)
-    if current_user.usertype == 'A'
+  # GET /expensesconcepts
+  # GET /expensesconcepts.json
+  def index
+    @concept_purchase_payment = Expensesconcept.find_by(expense_from_purchase: 1)
+    if current_user.usertype == "A" || current_user.usertype == "SS"
       @expensesconcepts = Expensesconcept.vigentes
     else
       @expensesconcepts = Array.new
-      Expensesconcept.where("status = 1 and allpoints = 'true'").each do |expense|
+      Expensesconcept.where(status: 1, allpoints: true).each do |expense|
         @expensesconcepts << expense
       end
 
@@ -31,7 +31,6 @@ class ExpensesconceptsController < ApplicationController
     end
   end
 
-
   # GET /expensesconcepts/new
   def new
     @expensesconcept = Expensesconcept.new
@@ -39,81 +38,81 @@ class ExpensesconceptsController < ApplicationController
 
   def create
     @expensesconcept = Expensesconcept.new(expensesconcept_params)
-		respond_to do |format|
-			@expensesconcept.audit_comment = "Concepto de egreso #{@expensesconcept.name} creado."
-			if @expensesconcept.save
-				# @expensesconcept.pointsales = @pointsales
-				format.html { redirect_to expensesconcepts_url, success: 'El concepto ' + @expensesconcept.name + ' fue creado.' }
-				format.json { render :show, status: :created, location: @expensesconcept }
-			else
-				format.html { render :new }
-				format.json { render json: @expensesconcept.errors, status: :unprocessable_entity }
-			end
-		end
-	end
+    respond_to do |format|
+      @expensesconcept.audit_comment = "Concepto de egreso #{@expensesconcept.name} creado."
+      if @expensesconcept.save
+        # @expensesconcept.pointsales = @pointsales
+        format.html { redirect_to expensesconcepts_url, success: 'El concepto ' + @expensesconcept.name + ' fue creado.' }
+        format.json { render :show, status: :created, location: @expensesconcept }
+      else
+        format.html { render :new }
+        format.json { render json: @expensesconcept.errors, status: :unprocessable_entity }
+      end
+    end
+  end
 
-	# PATCH/PUT /expensesconcepts/1
-	# PATCH/PUT /expensesconcepts/1.json
-	def update
-		respond_to do |format|
-			@expensesconcept.audit_comment = "Concepto de egreso #{@expensesconcept.name} modificado."
-			if @expensesconcept.update(expensesconcept_params)
+  # PATCH/PUT /expensesconcepts/1
+  # PATCH/PUT /expensesconcepts/1.json
+  def update
+    respond_to do |format|
+      @expensesconcept.audit_comment = "Concepto de egreso #{@expensesconcept.name} modificado."
+      if @expensesconcept.update(expensesconcept_params)
 
-				# @expensesconcept.pointsales = @pointsales
-				format.html { redirect_to expensesconcepts_url, success: 'El concepto ' + @expensesconcept.name + ' fue modificado.' }
-					format.json { render :show, status: :ok, location: @expensesconcept }
-			else
-				format.html { render :edit }
-				format.json { render json: @expensesconcept.errors, status: :unprocessable_entity }
-			end
-		end
-	end
+        # @expensesconcept.pointsales = @pointsales
+        format.html { redirect_to expensesconcepts_url, success: 'El concepto ' + @expensesconcept.name + ' fue modificado.' }
+        format.json { render :show, status: :ok, location: @expensesconcept }
+      else
+        format.html { render :edit }
+        format.json { render json: @expensesconcept.errors, status: :unprocessable_entity }
+      end
+    end
+  end
 
-	# DELETE /expensesconcepts/1
-	# DELETE /expensesconcepts/1.json
-	def destroy
-		#@expensesconcept.destroy
-		respond_to do |format|
-			@expensesconcept.audit_comment = "Concepto de egreso #{@expensesconcept.name} eliminado."
-			if @expensesconcept.update_attributes(:status => 0)
-						format.html { redirect_to expensesconcepts_url, warning: "El concepto " + @expensesconcept.name + " fue eliminado." }
-						format.json { head :no_content }
-			else
-				format.html { render :edit }
-				format.json { render json: @expensesconcept.errors, status: :unprocessable_entity }
-			end
-		end
-	end
+  # DELETE /expensesconcepts/1
+  # DELETE /expensesconcepts/1.json
+  def destroy
+    respond_to do |format|
+      @expensesconcept.audit_comment = "Concepto de egreso #{@expensesconcept.name} eliminado."
+      if @expensesconcept.update_attributes(status: 0)
+        format.html { redirect_to expensesconcepts_url, warning: "El concepto " + @expensesconcept.name + " fue eliminado." }
+        format.json { head :no_content }
+      else
+        format.html { render :edit }
+        format.json { render json: @expensesconcept.errors, status: :unprocessable_entity }
+      end
+    end
+  end
 
   private
-    # Use callbacks to share common setup or constraints between actions.
-    def set_expensesconcept
-      @expensesconcept = Expensesconcept.find(params[:id])
-    end
 
-    # Never trust parameters from the scary internet, only allow the white list through.
-    def expensesconcept_params
-      params.require(:expensesconcept).permit(:name, :description, :allpoints, :status, :pointsale_ids => [])
-    end
+  # Use callbacks to share common setup or constraints between actions.
+  def set_expensesconcept
+    @expensesconcept = Expensesconcept.find(params[:id])
+  end
 
-    def get_filters
-			if params[:current_page].blank?
-				@current_page = 1
-			else
-				@current_page = params[:current_page]
-			end
-			@filter = params[:filter]
-		end
+  # Never trust parameters from the scary internet, only allow the white list through.
+  def expensesconcept_params
+    params.require(:expensesconcept).permit(:name, :description, :allpoints, :status, pointsale_ids: [])
+  end
 
-    def get_pointsales
-        unless params[:expensesconcept][:pointsale_ids].nil? && params[:expensesconcept][:pointsale_ids].empty?
-            ## Issue arreglo primer elemento en blanco ...
-            params[:expensesconcept][:pointsale_ids] = params[:expensesconcept][:pointsale_ids].delete_if{ |x| x.empty? }
-            @pointsales = params[:expensesconcept][:pointsale_ids].map do |k|
-                Pointsale.find(k)
-            end
-        else
-            @pointsales = []
-        end
+  def get_filters
+    @current_page =
+      if params[:current_page].blank?
+        1
+      else
+        params[:current_page]
+      end
+    @filter = params[:filter]
+  end
+
+  def get_pointsales
+    @pointsales = []
+    unless params[:expensesconcept][:pointsale_ids].nil? && params[:expensesconcept][:pointsale_ids].empty?
+      ## Issue arreglo primer elemento en blanco ...
+      params[:expensesconcept][:pointsale_ids] = params[:expensesconcept][:pointsale_ids].delete_if(&:empty?)
+      @pointsales = params[:expensesconcept][:pointsale_ids].map do |k|
+        Pointsale.find(k)
+      end
     end
+  end
 end

+ 1 - 6
app/controllers/pointsales_controller.rb

@@ -50,12 +50,7 @@ class PointsalesController < ApplicationController
     respond_to do |format|
       if @pointsale.save
         @pointsale.users.first.pointsale_id = @pointsale.id
-        main_cash_register = CashRegister.new
-        main_cash_register.name = @pointsale.name + " Principal"
-        main_cash_register.description = "Caja registradora principal"
-        main_cash_register.pointsale_id = @pointsale.id
-        main_cash_register.main = 'yes'
-        main_cash_register.status = 'active'
+        main_cash_register = CashRegister.new(name: "#{@pointsale.name} Principal", description: "Caja registradora principal", pointsale_id: @pointsale.id, main: 'yes', status: 'active')
         main_cash_register.save
 
         format.html { redirect_to pointsales_url, success: "El punto de venta " + @pointsale.name + " fue creado." }

+ 24 - 35
app/controllers/product_wastes_controller.rb

@@ -13,13 +13,15 @@ class ProductWastesController < ApplicationController
   # GET /product_wastes
   # GET /product_wastes.json
   def index
-    if current_user.usertype == 'A'
-      @product_wastes = ProductWaste.includes(:product, :user, :pointsale, :warehouse).activos
-    elsif current_user.usertype == 'G' || current_user.usertype == 'C'
-      @product_wastes = ProductWaste.includes(:product, :user).where(pointsale_id: current_user.pointsale_id).activos
-    elsif current_user.usertype == 'S'
-      @product_wastes = ProductWaste.includes(:product, :user).where(warehouse_id: current_user.warehouse_id).activos
-    end
+    @product_wastes = ProductWaste.includes(:product, :user, :pointsale, :warehouse).activos
+    @product_wastes =
+      if current_user.usertype == 'G' || current_user.usertype == 'C'
+        @product_wastes.where(pointsale_id: current_user.pointsale_id)
+      elsif current_user.usertype == 'S'
+        @product_wastes.where(warehouse_id: current_user.warehouse_id)
+      else
+        @product_wastes
+      end
   end
 
   # GET /product_wastes/new
@@ -28,20 +30,21 @@ class ProductWastesController < ApplicationController
   # POST /product_wastes
   # POST /product_wastes.json
   def create
-    respond_to do |format|
-      @product_waste = ProductWaste.new(product_waste_params)
-      @product_waste.user_id = current_user.id
-      @product_waste.status = :active
+    @product_waste = ProductWaste.new(product_waste_params)
+    @product_waste.user_id = current_user.id
+    @product_waste.status = :active
 
-      if current_user.usertype == 'S'
-        @product_waste.warehouse_id = current_user.warehouse_id
-        @stock = WarehouseStock.find_by(warehouse_id: @product_waste.warehouse_id, product_id: @product_waste.product_id)
-      else
-        @product_waste.pointsale_id = current_user.pointsale_id
-        @stock = AvailableProduct.find_by(pointsale_id: @product_waste.pointsale_id, product_id: @product_waste.product_id)
-      end
+    if current_user.usertype == 'S'
+      @product_waste.warehouse_id = current_user.warehouse_id
+      @stock = WarehouseStock.find_by(warehouse_id: @product_waste.warehouse_id, product_id: @product_waste.product_id)
+    else
+      @product_waste.pointsale_id = current_user.pointsale_id
+      @stock = AvailableProduct.find_by(pointsale_id: @product_waste.pointsale_id, product_id: @product_waste.product_id)
+    end
+
+    respond_to do |format|
       if @stock.stock >= @product_waste.quantity
-        @product_waste.audit_comment = "Merma del producto #{@product_waste.product.name}  creada"
+        @product_waste.audit_comment = "Merma del producto #{@product_waste.product.name} creada"
         if @product_waste.save
           @stock.stock -= @product_waste.quantity
           @stock.save
@@ -50,31 +53,17 @@ class ProductWastesController < ApplicationController
           format.json { render json: @product_waste.errors.values, status: :unprocessable_entity }
         end
       else
-        @product_waste.errors.add(:base, "Stock insuficiente, solo se cuenta con #{@stock.stock} unidades del producto #{@product_waste.product.name}")
+        @product_waste.errors.add(:base, "Stock insuficiente, sólo se cuenta con #{@stock.stock} unidades del producto #{@product_waste.product.name}")
         format.json { render json: @product_waste.errors.values, status: :unprocessable_entity }
       end
     end
   end
 
-  # PATCH/PUT /product_wastes/1
-  # PATCH/PUT /product_wastes/1.json
-  def update
-    respond_to do |format|
-      if @product_waste.update(product_waste_params)
-        format.html { redirect_to @product_waste, notice: 'Product waste was successfully updated.' }
-        format.json { render :show, status: :ok, location: @product_waste }
-      else
-        format.html { render :edit }
-        format.json { render json: @product_waste.errors, status: :unprocessable_entity }
-      end
-    end
-  end
-
   # DELETE /product_wastes/1
   # DELETE /product_wastes/1.json
   def destroy
     respond_to do |format|
-      @product_waste.audit_comment = "Merma del producto #{@product_waste.product.name}  eliminada."
+      @product_waste.audit_comment = "Merma del producto #{@product_waste.product.name} eliminada."
       if @product_waste.update_attributes(status: :inactive)
         @stock = current_user.usertype == "S" ? WarehouseStock.find_by(warehouse_id: @product_waste.warehouse_id, product_id: @product_waste.product_id) : AvailableProduct.find_by(pointsale_id: @product_waste.pointsale_id, product_id: @product_waste.product_id)
         @stock.stock = @stock.stock + @product_waste.quantity

+ 1 - 1
app/controllers/products_returns_controller.rb

@@ -12,7 +12,7 @@ class ProductsReturnsController < ApplicationController
   # GET /products_returns
   # GET /products_returns.json
   def index
-    @products_returns = current_user.usertype == 'A' ? ProductsReturn.all.includes(:sale, :user, :pointsale) : Pointsale.find(current_user.pointsale_id).products_returns.includes(:sale, :user).order(" products_returns.id DESC ")
+    @products_returns = current_user.usertype == "A" || current_user.usertype == "SS" ? ProductsReturn.all.includes(:sale, :user, :pointsale) : Pointsale.find(current_user.pointsale_id).products_returns.includes(:sale, :user).order(" products_returns.id DESC ")
   end
 
   # GET /products_returns/1

+ 86 - 102
app/controllers/purchases_controller.rb

@@ -1,13 +1,12 @@
 class PurchasesController < ApplicationController
-
   ##--- Abilities
   load_and_authorize_resource
 
   ##--- Breadcrum_rails
   add_breadcrumb I18n.t("breadcrumbs." + controller_name), :purchases_path
   add_breadcrumb "Nueva " + I18n.t("breadcrumbs." + controller_name).singularize, :new_purchase_path, only: :new
-  add_breadcrumb "Detalle de la " + I18n.t("breadcrumbs." + controller_name).singularize , :purchase_path, only: :show
-  add_breadcrumb "Editar " + I18n.t("breadcrumbs." + controller_name).singularize , :edit_purchase_path, only: :edit
+  add_breadcrumb "Detalle de la " + I18n.t("breadcrumbs." + controller_name).singularize, :purchase_path, only: :show
+  add_breadcrumb "Editar " + I18n.t("breadcrumbs." + controller_name).singularize, :edit_purchase_path, only: :edit
 
   before_action :set_purchase, only: [:show, :edit, :update, :destroy]
   before_action :get_filters, only: [:index, :show, :edit, :new]
@@ -15,17 +14,17 @@ class PurchasesController < ApplicationController
   # GET /purchases
   # GET /purchases.json
   def index
-    if current_user.usertype == "A"
-      @purchases = Purchase.all.includes(:supplier, :pointsale, :warehouse, :user).order("created_at DESC")
-    else
-      @purchases = Purchase.includes(:supplier, :user).where(:pointsale_id => current_user.pointsale_id).order('created_at desc')
-    end
+    @purchases =
+      if current_user.usertype == "A" || current_user.usertype == "SS"
+        Purchase.all.includes(:supplier, :pointsale, :warehouse, :user).order("created_at DESC")
+      else
+        Purchase.includes(:supplier, :user).where(pointsale_id: current_user.pointsale_id).order('created_at desc')
+      end
   end
 
   # GET /purchases/1
   # GET /purchases/1.json
-  def show
-  end
+  def show; end
 
   # GET /purchases/new
   def new
@@ -38,18 +37,18 @@ class PurchasesController < ApplicationController
     @destiny = 'warehouse'
     @purchase = Purchase.new
     @purchase.purchase_details.new
-    @pre_purchases = PrePurchase.where(:user_id => current_user.id)
-    if @pre_purchases.size > 0
+    @pre_purchases = PrePurchase.where(user_id: current_user.id)
+    unless @pre_purchases.empty?
       @purchase.supplier_id = @pre_purchases[0].supplier_id
       @purchase.pointsale_id = @pre_purchases[0].pointsale_id
-      @purchase.warehouse_id =  @pre_purchases[0].warehouse_id
+      @purchase.warehouse_id = @pre_purchases[0].warehouse_id
       @destiny = @purchase.pointsale_id.present? ? 'pointsale' : 'warehouse'
       @purchase.exchange = @pre_purchases[0].exchange if @pre_purchases[0].exchange.present?
       @purchase.is_in_dollars = true if @pre_purchases[0].exchange.present?
       @disable_supplier = true
       @disable_pointsale = true
       @disable_warehouse = true
-      @disable_is_in_dollars =  true
+      @disable_is_in_dollars = true
       @disable_destiny = true
       @disabled_button = false
     end
@@ -68,7 +67,7 @@ class PurchasesController < ApplicationController
     @purchase = Purchase.new(purchase_params)
     @purchase.user_id = current_user.id
     @purchase.status = :notpaid
-    @pre_purchases = PrePurchase.where(:user_id => current_user.id)
+    @pre_purchases = PrePurchase.where(user_id: current_user.id)
 
     respond_to do |format|
       message = "compra #{@purchase.purchase_code} por #{@purchase.total} creada."
@@ -76,51 +75,7 @@ class PurchasesController < ApplicationController
       if @purchase.save
         @pre_purchases.each do |pre_purchase|
           # agregar detalles de la compra
-          detail = PurchaseDetail.new
-          detail.product_id = pre_purchase.product_id
-          detail.quantity = pre_purchase.quantity
-          detail.amount = pre_purchase.total
-          detail.price = pre_purchase.price_base
-          detail.tax = pre_purchase.tax
-          @purchase.purchase_details << detail
-          # actualizar stock del producto cuando es para punto de venta
-          if @purchase.pointsale_id.present?
-            stockProduct = AvailableProduct.find_by(:product_id => detail.product_id, :pointsale_id => @purchase.pointsale_id)
-            if stockProduct.present?
-              stockProduct.stock = 0 if stockProduct.stock.blank?
-              stockProduct.stock += detail.quantity
-              stockProduct.save
-            else
-              stockProduct = AvailableProduct.new
-              stockProduct.product_id = detail.product_id
-              stockProduct.pointsale_id = @purchase.pointsale_id
-              stockProduct.stock = detail.quantity
-              stockProduct.save
-            end
-          else
-            # actualizar stock del producto cuando es para punto de venta
-            stockProduct = WarehouseStock.find_by(:product_id => detail.product_id, :warehouse_id => @purchase.warehouse_id)
-            if stockProduct.present?
-              stockProduct.stock = 0 if stockProduct.stock.blank?
-              stockProduct.stock += detail.quantity
-              stockProduct.save
-            else
-              stockProduct = WarehouseStock.new
-              stockProduct.product_id = detail.product_id
-              stockProduct.warehouse_id = @purchase.warehouse_id
-              stockProduct.stock = detail.quantity
-              stockProduct.save
-            end
-          end
-          # guardar en bitacora de inventario
-          move = InventoriesMove.new
-          move.product_id = detail.product_id
-          move.purchase_id = @purchase.id
-          move.quantity = detail.quantity
-          move.move_type = "incoming"
-          move.reason = "purchase"
-          move.save
-
+          create_purchase_details(@purchase, pre_purchase)
           pre_purchase.destroy
         end
         format.html { redirect_to purchases_url, success: message }
@@ -137,34 +92,15 @@ class PurchasesController < ApplicationController
     respond_to do |format|
       message = "Compra #{@purchase.purchase_code} cancelada."
       @purchase.audit_comment = message
-      if @purchase.update_attributes(:status => :cancelled)
-        #checa si hay pagos de esta compra
-        CashRegistersMove.where(:purchase_id => @purchase.id).each do |move|
+      if @purchase.update_attributes(status: :cancelled)
+        # checa si hay pagos de esta compra
+        CashRegistersMove.where(purchase_id: @purchase.id).each do |move|
           new_cash_move = move.dup
           new_cash_move.move_type = :ingreso
           new_cash_move.save
         end
-
         @purchase.purchase_details.each do |detail|
-          detail.update_attributes(:status => :inactive)
-          #busca y actualiza el stock de productos
-          if @purchase.pointsale.present?
-            stockProduct = AvailableProduct.find_by(:product_id => detail.product_id, :pointsale_id => @purchase.pointsale_id)
-          else
-            stockProduct = WarehouseStock.find_by(:product_id => detail.product_id, :warehouse_id => @purchase.warehouse_id)
-          end
-          # restarle al stock del producto
-          stock = stockProduct.stock - detail.quantity
-          stockProduct.update_attributes(:stock => stock)
-
-          # guardar en bitacora de inventario
-          move = InventoriesMove.new
-          move.product_id = detail.product_id
-          move.purchase_id = @purchase.id
-          move.quantity = detail.quantity
-          move.move_type = "outgoing"
-          move.reason = "purchase_cancel"
-          move.save
+          destroy_purchase_details(@purchase, detail)
         end
         format.html { redirect_to purchases_url, warning: message }
         format.json { head :no_content }
@@ -176,35 +112,83 @@ class PurchasesController < ApplicationController
   end
 
   def find_purchases_by_date
-    startDate = DateTime.parse(params[:begin_date])
-    endDate = DateTime.parse(params[:end_date])
-    if current_user.usertype == "A"
-      @purchases = Purchase.includes(:supplier, :pointsale, :warehouse, :user).where(:purchase_date => startDate..endDate).order('purchase_date desc')
-    else
-      @purchases = Purchase.includes(:supplier, :user).where(:pointsale_id => current_user.pointsale_id, :created_at => startDate..endDate).order('purchase_date desc')
-    end
+    start_date = DateTime.parse(params[:begin_date])
+    end_date = DateTime.parse(params[:end_date])
+    @purchases =
+      if current_user.usertype == "A" || current_user.usertype == "SS"
+        Purchase.includes(:supplier, :pointsale, :warehouse, :user).where(purchase_date: start_date..end_date).order('purchase_date desc')
+      else
+        Purchase.includes(:supplier, :user).where(pointsale_id: current_user.pointsale_id, created_at: start_date..end_date).order('purchase_date desc')
+      end
     respond_to do |format|
       format.js
     end
   end
 
   private
-    # Use callbacks to share common setup or constraints between actions.
-    def set_purchase
-      @purchase = Purchase.find(params[:id])
-    end
 
-    def get_filters
+  # Use callbacks to share common setup or constraints between actions.
+  def set_purchase
+    @purchase = Purchase.find(params[:id])
+  end
+
+  def get_filters
+    @current_page =
       if params[:current_page].blank?
-        @current_page = 1
+        1
       else
-        @current_page = params[:current_page]
+        params[:current_page]
       end
-      @filter = params[:filter]
-    end
+    @filter = params[:filter]
+  end
 
-    # Never trust parameters from the scary internet, only allow the white list through.
-    def purchase_params
-      params.require(:purchase).permit(:supplier_id, :pointsale_id, :warehouse_id ,:purchase_code, :amount, :tax, :total, :observations, :purchase_date, :is_in_dollars, :exchange)
+  def create_purchase_details(purchase, pre_purchase)
+    detail = PurchaseDetail.new(product_id: pre_purchase.product_id, quantity: pre_purchase.quantity, amount: pre_purchase.total, price: pre_purchase.price_base, tax: pre_purchase.tax)
+    purchase.purchase_details << detail
+    # actualizar stock del producto cuando es para punto de venta
+    if purchase.pointsale_id.present?
+      stock_product = AvailableProduct.find_by(product_id: detail.product_id, pointsale_id: purchase.pointsale_id)
+      if stock_product.nil?
+        stock_product = AvailableProduct.create(product_id: detail.product_id, pointsale_id: purchase.pointsale_id, stock: detail.quantity)
+      else
+        stock_product = 0 if stock_product.stock.blank?
+        stock_product.stock += detail.quantity
+      end
+    else
+      # actualizar stock del producto cuando es para almacen
+      stock_product = WarehouseStock.find_by(product_id: detail.product_id, warehouse_id: purchase.warehouse_id)
+      if stock_product.nil?
+        stock_product = WarehouseStock.create(product_id: detail.product_id, warehouse_id: purchase.warehouse_id, stock: detail.quantity)
+      else
+        stock_product = 0 if stock_product.stock.blank?
+        stock_product.stock += detail.quantity
+      end
     end
+    stock_product.save
+
+    # guardar en bitacora de inventario
+    InventoriesMove.create(product_id: detail.product_id, purchase_id: purchase.id, quantity: detail.quantity, move_type: "incoming", reason: "purchase")
+  end
+
+  def destroy_purchase_details(purchase, purchase_detail)
+    purchase_detail.update_attributes(status: :inactive)
+    # busca y actualiza el stock de productos
+    stock_product =
+      if purchase.pointsale.present?
+        AvailableProduct.find_by(product_id: purchase_detail.product_id, pointsale_id: purchase.pointsale_id)
+      else
+        WarehouseStock.find_by(product_id: purchase_detail.product_id, warehouse_id: purchase.warehouse_id)
+      end
+    # restarle al stock del producto
+    stock = stock_product.stock - purchase_detail.quantity
+    stock_product.update_attributes(stock: stock)
+
+    # guardar en bitacora de inventario
+    InventoriesMove.create(product_id: purchase_detail.product_id, purchase_id: purchase.id, quantity: purchase_detail.quantity, move_type: "outgoing", reason: "purchase_cancel")
+  end
+
+  # Never trust parameters from the scary internet, only allow the white list through.
+  def purchase_params
+    params.require(:purchase).permit(:supplier_id, :pointsale_id, :warehouse_id, :purchase_code, :amount, :tax, :total, :observations, :purchase_date, :is_in_dollars, :exchange)
+  end
 end

+ 35 - 35
app/controllers/sales_controller.rb

@@ -15,13 +15,13 @@ class SalesController < ApplicationController
   def index
     today = Date.current
     thirty_day_ago = today - 30
-    @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")
+    @sales = current_user.usertype == "A" || current_user.usertype == "SS" ? 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
     beg_of_month = Date.current.beginning_of_month
     end_of_month = Date.current.end_of_month
-    @sales = current_user.usertype == 'A' ? Sale.where(saletype: 2).order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.where(saletype: 2).order(" created_at DESC")
+    @sales = current_user.usertype == "A" || current_user.usertype == "SS" ? Sale.where(saletype: 2).order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.where(saletype: 2).order(" created_at DESC")
   end
 
   # GET /sales/1
@@ -193,7 +193,7 @@ class SalesController < ApplicationController
       start_date = Date.today.beginning_of_month
       end_date = Date.today.end_of_month
     end
-    @sales = current_user.usertype == 'A' ? Sale.includes(:customer, :user, :seller, :sales_details).where(date_sale: start_date..end_date).where.not(saletype: 2).order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.includes(:customer, :user, :seller, :sales_details).where(date_sale: start_date..end_date).where.not(saletype: 2).order(" created_at DESC ")
+    @sales = current_user.usertype == "A" || current_user.usertype == "SS" ? Sale.includes(:customer, :user, :seller, :sales_details).where(date_sale: start_date..end_date).where.not(saletype: 2).order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.includes(:customer, :user, :seller, :sales_details).where(date_sale: start_date..end_date).where.not(saletype: 2).order(" created_at DESC ")
     respond_to do |format|
       format.js
     end
@@ -223,7 +223,7 @@ class SalesController < ApplicationController
       start_date = Date.today.beginning_of_month
       end_date = Date.today.end_of_month
     end
-    @sales = current_user.usertype == 'A' ? Sale.includes(:customer, :user, :seller, :sales_details).where(date_sale: start_date..end_date, saletype: 2).order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.includes(:customer, :user, :seller, :sales_details).where(date_sale: start_date..end_date).where(saletype: 2).order(" created_at DESC ")
+    @sales = current_user.usertype == "A" || current_user.usertype == "SS" ? Sale.includes(:customer, :user, :seller, :sales_details).where(date_sale: start_date..end_date, saletype: 2).order(" created_at DESC ") : Pointsale.find(current_user.pointsale_id).sales.includes(:customer, :user, :seller, :sales_details).where(date_sale: start_date..end_date).where(saletype: 2).order(" created_at DESC ")
 
     respond_to do |format|
       format.js
@@ -366,38 +366,38 @@ class SalesController < ApplicationController
   end
 
   def sales_per_month
-    respond_to do |format|
-      # start_date = DateTime.parse(params[:start_date])
-      # end_date = DateTime.parse(params[:end_date])
-      start_date = DateTime.parse(params[:start_date]).in_time_zone(Time.zone).beginning_of_day + 1.days
-      end_date = DateTime.parse(params[:end_date]).in_time_zone(Time.zone).end_of_day + 1.days
-      @cash_sales_total = 0
-      @reserved_sales_total = 0
-      @credit_sales_total = 0
-
-      if params[:pointsale_id].present?
-        @pointsale = Pointsale.find(params[:pointsale_id])
-        @incomes_in_period = @pointsale.cash_registers_moves.joins(:sale).where(move_type: '1', created_at: start_date..end_date)
-        @sales = @pointsale.sales.activas.where(created_at: start_date..end_date).order("id DESC")
-      else
-        @incomes_in_period = CashRegistersMove.joins(:sale).where(move_type: '1', created_at: start_date..end_date)
-        @sales = Sale.activas.where(created_at: start_date..end_date).order("id DESC")
-      end
+    # start_date = DateTime.parse(params[:start_date])
+    # end_date = DateTime.parse(params[:end_date])
+    start_date = DateTime.parse(params[:start_date]).in_time_zone(Time.zone).beginning_of_day + 1.days
+    end_date = DateTime.parse(params[:end_date]).in_time_zone(Time.zone).end_of_day + 1.days
+    @cash_sales_total = 0
+    @reserved_sales_total = 0
+    @credit_sales_total = 0
+
+    if params[:pointsale_id].present?
+      @pointsale = Pointsale.find(params[:pointsale_id])
+      @incomes_in_period = @pointsale.cash_registers_moves.joins(:sale).where(move_type: '1', created_at: start_date..end_date)
+      @sales = @pointsale.sales.includes(:sales_details, :user, :seller).activas.where(created_at: start_date..end_date).order("id DESC")
+    else
+      @incomes_in_period = CashRegistersMove.joins(:sale).where(move_type: '1', created_at: start_date..end_date)
+      @sales = Sale.includes(:sales_details, :user, :seller).activas.where(created_at: start_date..end_date).order("id DESC")
+    end
 
-      @sales_quantity = @sales.size
-      @prods_total = SalesDetail.where("sale_id IN (?)", @sales.pluck(:id)).sum(:quantity).round
-      # @cash_sales_income = CashRegistersMove.activos.where("sale_id IN (?)", @sales.where(saletype: 1).pluck(:id)).where(created_at: start_date..end_date).sum(:quantity)
-      # @reserved_sales_income = CashRegistersMove.activos.where("sale_id IN (?)", @sales.where(saletype: 2).pluck(:id)).where(created_at: start_date..end_date).sum(:quantity)
-      # @credit_sales_income = CashRegistersMove.activos.where("sale_id IN (?)", @sales.where(saletype: 0).pluck(:id)).where(created_at: start_date..end_date).sum(:quantity)
-      @cash_sales_income = @incomes_in_period.where('sales.saletype = 1').sum(:quantity)
-      @reserved_sales_income = @incomes_in_period.where('sales.saletype = 2').sum(:quantity)
-      @credit_sales_income = @incomes_in_period.where('sales.saletype = 0').sum(:quantity)
-      @sales_income = @incomes_in_period.sum(:quantity)
-
-      @cash_sales_total = @sales.where(saletype: 1).sum(:total)
-      @reserved_sales_total = @sales.where(saletype: 2).sum(:total)
-      @credit_sales_total = @sales.where(saletype: 0).sum(:total)
-      @sales_total = @sales.sum(:total)
+    @sales_quantity = @sales.size
+    @prods_total = SalesDetail.where("sale_id IN (?)", @sales.pluck(:id)).sum(:quantity).round
+    # @cash_sales_income = CashRegistersMove.activos.where("sale_id IN (?)", @sales.where(saletype: 1).pluck(:id)).where(created_at: start_date..end_date).sum(:quantity)
+    # @reserved_sales_income = CashRegistersMove.activos.where("sale_id IN (?)", @sales.where(saletype: 2).pluck(:id)).where(created_at: start_date..end_date).sum(:quantity)
+    # @credit_sales_income = CashRegistersMove.activos.where("sale_id IN (?)", @sales.where(saletype: 0).pluck(:id)).where(created_at: start_date..end_date).sum(:quantity)
+    @cash_sales_income = @incomes_in_period.where('sales.saletype = ?', 1).sum(:quantity)
+    @reserved_sales_income = @incomes_in_period.where('sales.saletype = ?', 2).sum(:quantity)
+    @credit_sales_income = @incomes_in_period.where('sales.saletype = ?', 0).sum(:quantity)
+    @sales_income = @incomes_in_period.sum(:quantity)
+
+    @cash_sales_total = @sales.where(saletype: 1).sum(:total)
+    @reserved_sales_total = @sales.where(saletype: 2).sum(:total)
+    @credit_sales_total = @sales.where(saletype: 0).sum(:total)
+    @sales_total = @sales.sum(:total)
+    respond_to do |format|
       format.js
     end
   end

+ 1 - 1
app/controllers/transfers_controller.rb

@@ -16,7 +16,7 @@ class TransfersController < ApplicationController
   # GET /transfers.json
   def index
     @transfers = Transfer.includes(:user, :received_by, :transfer_details).all.order('id DESC, transfer_date DESC')
-    unless current_user.usertype == "A"
+    unless current_user.usertype == "A" || current_user.usertype == "SS"
       is_destiny =
         if current_user.usertype == "S"
           id_filter = current_user.warehouse_id

+ 12 - 0
app/helpers/purchases_helper.rb

@@ -1,2 +1,14 @@
 module PurchasesHelper
+  def purchase_status(purchase)
+    case purchase.status
+    when "paid"
+      content_tag(:span, "Pagada", class: "label label-sm label-success")
+    when "cancelled"
+      content_tag(:span, "Cancelada", class: "label label-sm label-danger")
+    when "parcial"
+      content_tag(:span, "Abonada", class: "label label-sm label-warning")
+    when "notpaid"
+      content_tag(:span, "Pte. de pago", class: "label label-sm label-default")
+    end
+  end
 end

+ 4 - 5
app/views/available_products/_edit_price.html.erb

@@ -7,9 +7,9 @@
 	<% end %>
 	<div class="form-body">
 		<div class="row">
-			
+
 			<div class="col-md-12">
-				<% if current_user.usertype == "A" %>
+				<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 				<p> Punto de venta: <%= @available_product.pointsale.name %></p>
 				<% end %>
 				<p> Producto: <%= @product.name %> con precio de venta (base) de $<%= @product.price_sale %>
@@ -31,13 +31,12 @@
 		</div>
 	</div>
 	<div class="form-actions">
-	    
 		<div class="row">
 			<div class="col-md-offset-3 col-md-9">
-				<%= f.submit 'Actualizar precio', {:class=>"btn green"} %> 
+				<%= f.submit 'Actualizar precio', {:class=>"btn green"} %>
 				<button type="button" data-dismiss="modal" class="btn">Cancelar</button>
 			</div>
 		</div>
 	</div>
 </div>
-<% end %>
+<% end %>

+ 3 - 5
app/views/available_products/stock_by_pointsale.html.erb

@@ -59,7 +59,7 @@
 														<!-- sub- categoria -->
 														<%= label :sub_category, "", {:class=>"col-md-1 control-label"} do %>Sublínea <% end %>
 														<div class="col-md-3 select2-bootstrap-prepend">
-															<%= select_tag "sub_category", options_from_collection_for_select(Category.activos.where('parent_id != 0'), :id, :category), :include_blank => "Todas",  class: "form-control select2 clereable" %>
+															<%= select_tag "sub_category", options_from_collection_for_select(Category.activos.where('parent_id != 0'), :id, :category), :include_blank => "Todas", class: "form-control select2 clereable" %>
 														</div>
 													</div>
 												</div>
@@ -71,7 +71,7 @@
 														<div class="uppercase font-hg font-blue-sharp" id="total_prods"></div>
 													</div>
 												</div>
-												<% if current_user.usertype == 'A' %>
+												<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 													<div class="col-md-3 col-sm-4 col-xs-6 ">
 														<div class="text-center well" id="container_total_invested" style="margin-bottom: 0px">
 															<div class="font-grey-mint font-sm">Total invertido en pesos </div>
@@ -129,8 +129,6 @@
 		if (sub_category) { uri += '&sub_category=' + sub_category; }
 		if (search) { uri += '&search=' + encodeURIComponent(search); }
 
-		window.open('/print_stock_by_pointsale.pdf?' + uri, 'New tab', '' );
-
+		window.open('/print_stock_by_pointsale.pdf?' + uri, 'New tab', '');
 	}
 </script>
-

+ 8 - 5
app/views/cash_outs/_cash_out.html.erb

@@ -1,14 +1,14 @@
 <tr id="cash_out_<%= cash_out.id %>">
   <td><%= cash_out.id %></td>
-  <% if current_user.usertype == "A" %>
+  <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
     <td>
-    <%= OpenCashRegister.get_pointsale(cash_out.open_cash_register_id, "open_cash_register").name %> 
-    </td> 
+    <%= OpenCashRegister.get_pointsale(cash_out.open_cash_register_id, "open_cash_register").name %>
+    </td>
   <% end %>
   <td><%= cash_out.open_cash_register.cash_register.name %> </td>
   <td><%= number_to_currency(cash_out.amount_in, precision: 2) %> </td>
   <td><%= number_to_currency(cash_out.amount_out, precision: 2)  %></td>
-  <td><%= number_to_currency(cash_out.amount_in - cash_out.amount_out, precision: 2)  %></td>  
+  <td><%= number_to_currency(cash_out.amount_in - cash_out.amount_out, precision: 2)  %></td>
   <td><%= l(cash_out.created_at, :format => '%d/%B/%Y') %></td>
   <td><%= cash_out.user.first_name %></td>
   <td><%= (cash_out.received_by.blank? ? "" : cash_out.received_by.first_name) %></td>
@@ -16,5 +16,8 @@
     <%= link_to cash_out, {:class=>"btn btn-icon-only default", :title=>"Ver corte de caja"} do %>
       <i class="fa fa-search"></i>
     <% end %>
+    <%= link_to print_cash_out_receipt_path(cash_out.id, format: 'pdf'), {:class=>"btn btn-icon-only default", :target => "blank"} do %>
+      <i class="fa fa-print"></i>
+    <% end %>
   </td>
-</tr>
+</tr>

+ 10 - 10
app/views/cash_outs/index.html.erb

@@ -44,15 +44,15 @@
                     <span class="caption-subject bold uppercase">Lista de cortes de caja</span>
                   </div>
                    <div class="actions">
-                    <% if current_user.usertype == "G" %>
-                      <% if can? :create, CashOut %>
-                        <%= link_to new_open_cash_register_path, :remote => true, :class => 'btn btn bold green margin-top pull-right', :title => "Abrir caja registradora" do %> Abrir caja <i class="fa fa-plus"></i><% end %> <br>
-                        <%= link_to get_open_cash_registers_path, remote: true, data: { toggle: "modal", target: "#get_open_cash_register" }, :class=>"btn bold green pull-right", :title=>"Realizar corte de caja", :style=> "margin-top:10px"  do %> Realizar corte de caja <i class="fa fa-plus"></i>
+                    <% if can? :create, OpenCashRegister %>
+                      <%= link_to new_open_cash_register_path, remote: true, class: 'btn btn bold green margin-top pull-right', title: "Abrir caja registradora" do %> Abrir caja <i class="fa fa-plus"></i><% end %> <br>
+                    <% end %>
+                    <% if can? :get_open_cash_registers, CashOut %>
+                      <%= link_to get_open_cash_registers_path, remote: true, data: { toggle: "modal", target: "#get_open_cash_register" }, class: "btn bold green pull-right", title: "Realizar corte de caja", style: "margin-top:10px"  do %> Realizar corte de caja <i class="fa fa-plus"></i>
                         <% end %>
-                      <% end %>
                     <% end %>
-                    <% if current_user.usertype == "A" %>
-                      <%= link_to opened_cash_registers_path, {:class=>"btn bold green pull-right"} do %> <i class="fa fa-search"></i>&nbsp Ver cajas abiertas <% end %>
+                    <% if can? :opened_cash_registers, CashOut %>
+                      <%= link_to opened_cash_registers_path, { class: "btn bold green pull-right" } do %> <i class="fa fa-search"></i>&nbsp Ver cajas abiertas <% end %>
                     <% end %>
                   </div>
                 </div>
@@ -65,7 +65,7 @@
                             <%= label_tag :pointsale, "pointsale", {:class=>"col-md-2 control-label"} do %> Punto de venta
                             <% end %>
                             <div class="col-md-3">
-                              <%= select_tag "pointsale", options_from_collection_for_select(Pointsale.vigentes, :id, :name, :selected => current_user.pointsale_id), :include_blank => "Todas", :disabled => (true unless current_user.usertype == 'A'),  class: "form-control select2 col-md-3" %>
+                              <%= select_tag "pointsale", options_from_collection_for_select(Pointsale.vigentes, :id, :name, :selected => current_user.pointsale_id), :include_blank => "Todas", :disabled => (true unless current_user.usertype == "A" || current_user.usertype == "SS"),  class: "form-control select2 col-md-3" %>
                             </div>
                             <%= label_tag :begin_date, "Fecha", {:class=>"col-md-1 control-label"} do %> Desde
                             <% end %>
@@ -100,7 +100,7 @@
                     <thead>
                       <tr>
                         <th>#</th>
-                        <% if current_user.usertype == "A" %>
+                        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                           <th>Punto de venta</th>
                         <% end %>
                         <th>Caja registradora</th>
@@ -117,7 +117,7 @@
                       <% @cash_outs.each_with_index do |cash_out, key| %>
                       <tr>
                         <td><%= cash_out.id %></td>
-                        <% if current_user.usertype == "A" %>
+                        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                           <td>
                           <%= OpenCashRegister.get_pointsale(cash_out.open_cash_register_id, "open_cash_register").name %>
                           </td>

+ 185 - 187
app/views/cash_outs/show.html.erb

@@ -18,12 +18,11 @@
 		<div class="page-content">
 			<div class="container-fluid">
 				<div class="pull-right margin-bottom-10 ">
-                    <a class="btn blue hidden-print" onclick="javascript:window.print();"> Imprimir
-                        <i class="fa fa-print"></i>
-                    </a>
-					<%= link_to  cash_outs_path(:filter => @filter, :current_page => @current_page), {:class=>"fr-space btn blue-hoki hidden-print"} do %>
-						<i class="fa fa-angle-left "></i>
-						Regresar
+          <a class="btn blue hidden-print" onclick="javascript:window.print();"> Imprimir
+	          <i class="fa fa-print"></i>
+          </a>
+					<%= link_to cash_outs_path(:filter => @filter, :current_page => @current_page), {:class=>"fr-space btn blue-hoki hidden-print"} do %>
+						<i class="fa fa-angle-left "></i> Regresar
 					<% end %>
 				</div>
 				<!-- BEGIN PAGE BREADCRUMBS -->
@@ -52,7 +51,7 @@
 												&nbsp&nbsp Fecha:</div>
 												<div class="col-md-6 value"> <%= l(@cash_out.created_at, :format => '%A, %d de %B de %Y') %>  </div>
 											</div>
-											<% if current_user.usertype == "A" %>
+											<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 												<div class="row static-info">
 													<div class="col-md-6 name"><i class="fa fa-fw fa-cart-plus"></i> &nbsp Punto de venta:</div>
 													<div class="col-md-6 value"> <%= OpenCashRegister.get_pointsale(@cash_out.open_cash_register_id, "open_cash_register").name %>  </div>
@@ -81,33 +80,33 @@
 
 										<!-- para la vista de impresion -->
 										<ul class="list-unstyled visible-print">
-                                            <li>
-                                                <i class="fa fa-calendar-o"></i>&nbsp Fecha:
-                                                <strong><%= l(@cash_out.created_at, :format => '%A, %d de %B de %Y') %> </strong>
-                                            </li>
-                                            <% if current_user.usertype == "A" %>
-	                                            <li>
-	                                                <i class="fa fa-fw fa-cart-plus"></i>&nbsp Punto de venta:
-	                                                <strong><%= OpenCashRegister.get_pointsale(@cash_out.open_cash_register_id, "open_cash_register").name %></strong>
-	                                            </li>
-                                            <% end %>
-                                            <li>
-                                                <i class="fa fa-fw fa-cart-plus"></i>&nbsp Caja registradora:
-                                                <strong> <%= @cash_out.open_cash_register.cash_register.name %></strong>
-                                            </li>
-                                            <li>
-                                                <i class="fa fa-odnoklassniki"></i>&nbsp Realizó:
-                                                <strong> <%= @cash_out.user.first_name %> </strong>
-                                            </li>
-                                            <li>
-                                                <i class="fa fa-odnoklassniki"></i>&nbsp Recibió:
-                                                <strong> <%= @cash_out.received_by.first_name %> </strong>
-                                            </li>
-                                            <li>
-                                                <i class="fa fa-odnoklassniki"></i>&nbsp Observaciones:
-                                                <strong> <%= @cash_out.observations %> </strong>
-                                            </li>
-                                        </ul>
+                      <li>
+                        <i class="fa fa-calendar-o"></i>&nbsp Fecha:
+                        <strong><%= l(@cash_out.created_at, :format => '%A, %d de %B de %Y') %> </strong>
+                      </li>
+                      <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+                        <li>
+                          <i class="fa fa-fw fa-cart-plus"></i>&nbsp Punto de venta:
+                          <strong><%= OpenCashRegister.get_pointsale(@cash_out.open_cash_register_id, "open_cash_register").name %></strong>
+                        </li>
+                      <% end %>
+                      <li>
+                        <i class="fa fa-fw fa-cart-plus"></i>&nbsp Caja registradora:
+                        <strong> <%= @cash_out.open_cash_register.cash_register.name %></strong>
+                      </li>
+                      <li>
+                        <i class="fa fa-odnoklassniki"></i>&nbsp Realizó:
+                        <strong> <%= @cash_out.user.first_name %> </strong>
+                      </li>
+                      <li>
+                        <i class="fa fa-odnoklassniki"></i>&nbsp Recibió:
+                        <strong> <%= @cash_out.received_by.first_name %> </strong>
+                      </li>
+                      <li>
+                        <i class="fa fa-odnoklassniki"></i>&nbsp Observaciones:
+                        <strong> <%= @cash_out.observations %> </strong>
+                      </li>
+                  	</ul>
 									</div>
 								</div>
 							</div>
@@ -120,106 +119,105 @@
 										<div class="">
 											<div class="row">
 												<div class="col-md-4">
-												    <div class="hidden-print" style="padding-left: 0px">
-												      <ul class="list-group">
-												        <li class="list-group-item list-group-item-default"> Total de ventas
-												        <span class="pull-right label label-warning"><%= number_to_currency(@sales_total, precision: 2) %></span>
-												        </li>
-												      </ul>
-												    </div>
+											    <div class="hidden-print" style="padding-left: 0px">
+											      <ul class="list-group">
+											        <li class="list-group-item list-group-item-default"> Total de ventas
+											        <span class="pull-right label label-warning"><%= number_to_currency(@sales_total, precision: 2) %></span>
+											        </li>
+											      </ul>
+											    </div>
 												</div>
 												<div class="col-md-4">
-												    <div class="hidden-print" style="padding-left: 0px">
-												      <ul class="list-group">
-												        <li class="list-group-item list-group-item-default"> Total de egresos
-												        <span class="pull-right label label-warning"><%= number_to_currency(@expenses_total, precision: 2) %></span>
-												        </li>
-												      </ul>
-												    </div>
+											    <div class="hidden-print" style="padding-left: 0px">
+											      <ul class="list-group">
+											        <li class="list-group-item list-group-item-default"> Total de egresos
+											        <span class="pull-right label label-warning"><%= number_to_currency(@expenses_total, precision: 2) %></span>
+											        </li>
+											      </ul>
+											    </div>
 												</div>
 
 												<div class="col-md-4">
-												    <div class="hidden-print" style="padding-left: 0px">
-												      <ul class="list-group">
-												        <li class="list-group-item list-group-item-default"> Efectivo inicial
-												        <span class="pull-right label label-warning"><%= number_to_currency(@cash_out.open_cash_register.initial_cash, precision: 2) %></span>
-												        </li>
-												      </ul>
-												    </div>
+											    <div class="hidden-print" style="padding-left: 0px">
+											      <ul class="list-group">
+											        <li class="list-group-item list-group-item-default"> Efectivo inicial
+											        <span class="pull-right label label-warning"><%= number_to_currency(@cash_out.open_cash_register.initial_cash, precision: 2) %></span>
+											        </li>
+											      </ul>
+											    </div>
 												</div>
 
 												<div class="col-md-4">
-												    <div class="hidden-print" style="padding-left: 0px">
-												      <ul class="list-group">
-												        <li class="list-group-item list-group-item-default"> Retiro
-												        <span class="pull-right label label-warning"><%= number_to_currency(@cash_out.received_cash, precision: 2) %></span>
-												        </li>
-												      </ul>
-												    </div>
+											    <div class="hidden-print" style="padding-left: 0px">
+											      <ul class="list-group">
+											        <li class="list-group-item list-group-item-default"> Retiro
+											        <span class="pull-right label label-warning"><%= number_to_currency(@cash_out.received_cash, precision: 2) %></span>
+											        </li>
+											      </ul>
+											    </div>
 												</div>
 
 												<div class="col-md-4">
-												    <div class="hidden-print" style="padding-left: 0px">
-												      <ul class="list-group">
-												        <li class="list-group-item list-group-item-default"> Fondo
-												        <span class="pull-right label label-warning"><%= number_to_currency(@cash_out.cash_fund, precision: 2) %></span>
-												        </li>
-												      </ul>
-												    </div>
+											    <div class="hidden-print" style="padding-left: 0px">
+											      <ul class="list-group">
+											        <li class="list-group-item list-group-item-default"> Fondo
+											        <span class="pull-right label label-warning"><%= number_to_currency(@cash_out.cash_fund, precision: 2) %></span>
+											        </li>
+											      </ul>
+											    </div>
 												</div>
 											</div>
 											<!-- saldo inicial de la caja para el view-->
 
 											<!-- saldo inicial de la caja para el print view -->
 											<ul class="list-unstyled visible-print">
-	                                            <li>
-	                                                <i class="fa fa-money"></i>&nbsp Total de ventas:
-	                                                <strong><%= number_to_currency(@sales_total, precision: 2) %> </strong>
-	                                            </li>
-	                                            <li>
-	                                                <i class="fa fa-money"></i>&nbsp Total de egresos:
-	                                                <strong><%= number_to_currency(@expenses_total, precision: 2) %> </strong>
-	                                            </li>
-	                                            <li>
-	                                                <i class="fa fa-money"></i>&nbsp Efectivo inicial:
-	                                                <strong><%= number_to_currency(@cash_out.open_cash_register.initial_cash, precision: 2) %> </strong>
-	                                            </li>
-	                                            <li>
-	                                                <i class="fa fa-money"></i>&nbsp Retiro de efectivo:
-	                                                <strong><%= number_to_currency(@cash_out.received_cash, precision: 2) %> </strong>
-	                                            </li>
-	                                            <li>
-	                                                <i class="fa fa-money"></i>&nbsp Fondo de caja:
-	                                                <strong><%= number_to_currency(@cash_out.cash_fund, precision: 2) %> </strong>
-	                                            </li>
-
+                        <li>
+                          <i class="fa fa-money"></i>&nbsp Total de ventas:
+                          <strong><%= number_to_currency(@sales_total, precision: 2) %> </strong>
+                        </li>
+                        <li>
+                          <i class="fa fa-money"></i>&nbsp Total de egresos:
+                          <strong><%= number_to_currency(@expenses_total, precision: 2) %> </strong>
+                        </li>
+                        <li>
+                          <i class="fa fa-money"></i>&nbsp Efectivo inicial:
+                          <strong><%= number_to_currency(@cash_out.open_cash_register.initial_cash, precision: 2) %> </strong>
+                        </li>
+                        <li>
+                          <i class="fa fa-money"></i>&nbsp Retiro de efectivo:
+                          <strong><%= number_to_currency(@cash_out.received_cash, precision: 2) %> </strong>
+                        </li>
+                        <li>
+                          <i class="fa fa-money"></i>&nbsp Fondo de caja:
+                          <strong><%= number_to_currency(@cash_out.cash_fund, precision: 2) %> </strong>
+                        </li>
 											</ul>
-									        <table class="table table-striped table-hover">
-									            <thead>
-									                <tr class="uppercase">
-									                    <th> # </th>
-									                    <th> Método de pago </th>
-									                    <th> total de ingresos </th>
-									                    <th> total de egresos </th>
-									                    <th> Total </th>
-									                </tr>
-									            </thead>
-									            <tbody>
-									              <% @cash_out.cash_out_details.each_with_index do |detail, key| %>
-									                <tr>
-									                  <td> <%= key +1 %> </td>
-									                  <td> <%= detail.payment_method.method %> </td>
-									                  <td> <%= number_to_currency(detail.incoming, precision: 2) %> </td>
-									                  <td> <%= number_to_currency(detail.outgoing, precision: 2) %> </td>
-									                  <td>
-									                    <%= number_to_currency(detail.total, precision: 2) %>
-									                  </td>
-									                </tr>
-									              <% end %>
-									            </tbody>
-					                    	</table>
+							        <table class="table table-striped table-hover">
+						            <thead>
+					                <tr class="uppercase">
+				                    <th> # </th>
+				                    <th> Método de pago </th>
+				                    <th> total de ingresos </th>
+				                    <th> total de egresos </th>
+				                    <th> Total </th>
+					                </tr>
+						            </thead>
+						            <tbody>
+						              <% @cash_out.cash_out_details.each_with_index do |detail, key| %>
+						                <tr>
+						                  <td> <%= key +1 %> </td>
+						                  <td> <%= detail.payment_method.method %> </td>
+						                  <td> <%= number_to_currency(detail.incoming, precision: 2) %> </td>
+						                  <td> <%= number_to_currency(detail.outgoing, precision: 2) %> </td>
+						                  <td>
+						                    <%= number_to_currency(detail.total, precision: 2) %>
+						                  </td>
+						                </tr>
+						              <% end %>
+						            </tbody>
+                    	</table>
 										</div>
-			                    	</div>
+                	</div>
 								</div>
 							</div>
 							<div class="col-md-12 col-sm-12">
@@ -230,41 +228,41 @@
 									<div class="portlet-body">
 										<table class="table table-striped table-hover">
 											<thead>
-										        <tr>
-										          <th>#</th>
-										          <th>Folio</th>
-										          <th>Caja registradora</th>
-										          <th>Método de pago</th>
-										          <th>Cantidad</th>
-										          <th>Concepto</th>
-										          <th>Hora</th>
-										        </tr>
+								        <tr>
+								          <th>#</th>
+								          <th>Folio</th>
+								          <th>Caja registradora</th>
+								          <th>Método de pago</th>
+								          <th>Cantidad</th>
+								          <th>Concepto</th>
+								          <th>Hora</th>
+								        </tr>
 											</thead>
 											<tbody>
-										        <% @incomings.each_with_index do |move, key| %>
-										        <tr>
-										          <td><%= key + 1 %></td>
-										          <td>
-										            <% case move.concept %>
-          												<% when "sale",  "reserved_payment", "reserved_first_payment", "reserved_last_payment", "products_return" %>
-										                <%= move.sale.sale_code %>
-										              <% when "purchase"%>
-										                <%= move.purchase.purchase_code %>
-										              <% when "expense"%>
-										                <%= move.expense.expense_code %>
-										              <% when "credit_payment"%>
-										                <%= move.credit_payment.id %>
-										            <% end %>
-										          </td>
-										          <td><%= move.open_cash_register.cash_register.name%></td>
-										          <td><%= move.payment_method.method %></td>
-										          <td><%= number_to_currency(move.quantity, precision: 2) %></td>
-										          <td>
-                                  <%= cash_move_type(move) %>
-								           		 </td>
-										          <td><%= l(move.created_at, :format => '%I:%M %p') %> </td>
-										        </tr>
-										        <% end %>
+								        <% @incomings.each_with_index do |move, key| %>
+									        <tr>
+									          <td><%= key + 1 %></td>
+									          <td>
+									            <% case move.concept %>
+        												<% when "sale",  "reserved_payment", "reserved_first_payment", "reserved_last_payment", "products_return" %>
+									                <%= move.sale.sale_code %>
+									              <% when "purchase"%>
+									                <%= move.purchase.purchase_code %>
+									              <% when "expense"%>
+									                <%= move.expense.expense_code %>
+									              <% when "credit_payment"%>
+									                <%= move.credit_payment.id %>
+									            <% end %>
+									          </td>
+									          <td><%= move.open_cash_register.cash_register.name%></td>
+									          <td><%= move.payment_method.method %></td>
+									          <td><%= number_to_currency(move.quantity, precision: 2) %></td>
+									          <td>
+                              <%= cash_move_type(move) %>
+							           		</td>
+									          <td><%= l(move.created_at, :format => '%I:%M %p') %> </td>
+									        </tr>
+								        <% end %>
 											</tbody>
 										</table>
 									</div>
@@ -278,47 +276,47 @@
 									<div class="portlet-body">
 										<table class="table table-striped table-hover">
 											<thead>
-										        <tr>
-										          <th>#</th>
-										          <th>Folio</th>
-										          <th>Caja registradora</th>
-										          <th>Método de pago</th>
-										          <th>Cantidad</th>
-										          <th>Concepto</th>
-										          <th>Hora</th>
-										        </tr>
+								        <tr>
+								          <th>#</th>
+								          <th>Folio</th>
+								          <th>Caja registradora</th>
+								          <th>Método de pago</th>
+								          <th>Cantidad</th>
+								          <th>Concepto</th>
+								          <th>Hora</th>
+								        </tr>
 											</thead>
 											<tbody>
-										        <% @outgoings.each_with_index do |move, key| %>
-										        <tr>
-										          <td><%= key + 1 %></td>
-										          <td>
-										            <% case move.concept %>
-										              <% when "sale",  "reserved_payment",  "credit_payment" %>
-										                <%= move.sale.sale_code %>
-										              <% when "purchase"%>
-										                <%= move.purchase.purchase_code %>
-										              <% when "expense"%>
-										                <%= move.expense.expense_code %>
-										            <% end %>
-										          </td>
-										          <td><%= move.open_cash_register.cash_register.name%></td>
-										          <td><%= move.payment_method.method %></td>
-										          <td><%= number_to_currency(move.quantity, precision: 2) %></td>
-										          <td>
-						                          	<% case move.concept %>
-						                          	<% when "sale"%>
-						                            	Venta cancelada
-						                          	<% when "purchase"%>
-						                            	Compra
-						                          	<% when "expense"%>
-										                <strong> <%= move.expense.expensesconcept.name %></strong> <br>
-										                <%= move.expense.observations %>
-							                          <% end %>
-								           		 </td>
-										          <td><%= l(move.created_at, :format => '%I:%M %p') %> </td>
-										        </tr>
-										        <% end %>
+								        <% @outgoings.each_with_index do |move, key| %>
+									        <tr>
+									          <td><%= key + 1 %></td>
+									          <td>
+									            <% case move.concept %>
+									              <% when "sale",  "reserved_payment",  "credit_payment" %>
+									                <%= move.sale.sale_code %>
+									              <% when "purchase"%>
+									                <%= move.purchase.purchase_code %>
+									              <% when "expense"%>
+									                <%= move.expense.expense_code %>
+									            <% end %>
+									          </td>
+									          <td><%= move.open_cash_register.cash_register.name%></td>
+									          <td><%= move.payment_method.method %></td>
+									          <td><%= number_to_currency(move.quantity, precision: 2) %></td>
+									          <td>
+	                          	<% case move.concept %>
+	                          	<% when "sale" %>
+    	                        	Venta cancelada
+	                          	<% when "purchase" %>
+	                            	Compra
+	                          	<% when "expense" %>
+								                <strong> <%= move.expense.expensesconcept.name %></strong> <br>
+								                <%= move.expense.observations %>
+		                          <% end %>
+							           		</td>
+									          <td><%= l(move.created_at, :format => '%I:%M %p') %> </td>
+									        </tr>
+								        <% end %>
 											</tbody>
 										</table>
 									</div>

+ 128 - 131
app/views/commissions/_sellers_for_commissions.html.erb

@@ -1,148 +1,145 @@
 <div class="form-horizontal">
-    <div class="portlet-body form">
-        <div class="form-body">
-            <div class="row">
-                <div class="col-md-12">
-                    <div class="form-group">
-                       <%= label_tag :pointsale_id,  {:class=>"col-md-3 control-label"} do %>Punto de venta <span class="required">*</span> <% end %>
-                        <div class="col-md-8" style="padding-right:0px">
-                            <% if current_user.usertype == 'A' %>
-                              <%= select_tag :pointsale_id, options_from_collection_for_select(Pointsale.activos, :id, :name), :include_blank => "Seleccione punto de venta",  class: "form-control select2" %>
-                            <% else %>
-                                <%= text_field_tag 'pointsale', current_user.pointsale.name, :class => 'form-control', :disabled => true %>
-                                <%= hidden_field_tag 'pointsale_id', current_user.pointsale_id %>
-                            <% end %>
-                        </div>
-                    </div>
-                    <div class="form-group">
-                      <%= label_tag :initial_date, "Fecha", {:class=>"col-md-2 control-label"} do %>Desde <span class="required">*</span> <% end %>
-                      <div class="col-md-3" style="padding-left:0px;padding-right:0px;margin-left:15px">
-                          <div class='input-group date' id='initial_date'>
-                              <input id="start" type='text' class="form-control"/>
-                              <span class="input-group-addon">
-                                  <span class="glyphicon glyphicon-calendar"></span>
-                              </span>
-                          </div>
-                      </div>
-                      <%= label_tag :final_date, "Fecha", {:class=>"col-md-2 control-label"} do %>Hasta <span class="required">*</span> <% end %>
-                      <div class="col-md-3" style="padding-left:0px;padding-right:0px;">
-                          <div class='input-group date' id='final_date'>
-                              <input id="end" type='text' class="form-control"/>
-                              <span class="input-group-addon">
-                                  <span class="glyphicon glyphicon-calendar"></span>
-                              </span>
-                          </div>
-                      </div>
-                      <button class="btn btn-icon-only blue" style="margin-left:25px" onclick="getSellersByDates()">
-                        <i class="fa fa-search"></i>
-                      </button>
-                    </div>
-                    <div class="form-group">
-                        <div class="form-group" id="sellers_div">
-                            <%= label_tag :sellers_ids, "Vendores", {:class=>"col-md-3 control-label"} do %>Vendedores <span class="required">*</span> <% end %>
-                            <div class="col-md-9" style="padding-left:20px">
-                                <div class="row" style="margin-bottom:10px">
-                                    <div class="col-md-12">
-                                        <button type="button" class="btn btn-default" id='select-all'><i class="fa fa fa-square-o"></i> Seleccionar todo</button>
-                                        <button style="margin-left:55px" type="button" class="btn btn-default" id='deselect-all'><i class="fa fa-square-o"></i> Deseleccionar todo</button>
-                                    </div>
-                                </div>
-                                <%= select_tag :sellers_ids, nil, multiple: true, class: 'multi-select' %>
-                            </div>
-                        </div>
-                    </div>
+  <div class="portlet-body form">
+    <div class="form-body">
+      <div class="row">
+        <div class="col-md-12">
+          <div class="form-group">
+            <%= label_tag :pointsale_id,  {:class=>"col-md-3 control-label"} do %>Punto de venta <span class="required">*</span> <% end %>
+            <div class="col-md-8" style="padding-right:0px">
+              <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+                <%= select_tag :pointsale_id, options_from_collection_for_select(Pointsale.activos, :id, :name), :include_blank => "Seleccione punto de venta",  class: "form-control select2" %>
+              <% else %>
+                <%= text_field_tag 'pointsale', current_user.pointsale.name, :class => 'form-control', :disabled => true %>
+                <%= hidden_field_tag 'pointsale_id', current_user.pointsale_id %>
+              <% end %>
+            </div>
+          </div>
+          <div class="form-group">
+            <%= label_tag :initial_date, "Fecha", {:class=>"col-md-2 control-label"} do %>Desde <span class="required">*</span> <% end %>
+            <div class="col-md-3" style="padding-left:0px;padding-right:0px;margin-left:15px">
+              <div class='input-group date' id='initial_date'>
+                <input id="start" type='text' class="form-control"/>
+                <span class="input-group-addon">
+                  <span class="glyphicon glyphicon-calendar"></span>
+                </span>
+              </div>
+            </div>
+            <%= label_tag :final_date, "Fecha", {:class=>"col-md-2 control-label"} do %>Hasta <span class="required">*</span> <% end %>
+            <div class="col-md-3" style="padding-left:0px;padding-right:0px;">
+              <div class='input-group date' id='final_date'>
+                <input id="end" type='text' class="form-control"/>
+                <span class="input-group-addon">
+                  <span class="glyphicon glyphicon-calendar"></span>
+                </span>
+              </div>
+            </div>
+            <button class="btn btn-icon-only blue" style="margin-left:25px" onclick="getSellersByDates()">
+              <i class="fa fa-search"></i>
+            </button>
+          </div>
+          <div class="form-group">
+            <div class="form-group" id="sellers_div">
+              <%= label_tag :sellers_ids, "Vendores", {:class=>"col-md-3 control-label"} do %>Vendedores <span class="required">*</span> <% end %>
+              <div class="col-md-9" style="padding-left:20px">
+                <div class="row" style="margin-bottom:10px">
+                  <div class="col-md-12">
+                    <button type="button" class="btn btn-default" id='select-all'><i class="fa fa fa-square-o"></i> Seleccionar todo</button>
+                    <button style="margin-left:55px" type="button" class="btn btn-default" id='deselect-all'><i class="fa fa-square-o"></i> Deseleccionar todo</button>
+                  </div>
                 </div>
+                <%= select_tag :sellers_ids, nil, multiple: true, class: 'multi-select' %>
+              </div>
             </div>
+          </div>
         </div>
+      </div>
     </div>
-    <div class="form-actions">
-        <h4 class="form-section"> </h4>
-        <div class="row">
-            <div class="col-md-12">
-                <button type="button" class="btn green" disabled=​"disabled" onclick="generateCommissions()" id="generate_button">Generar comisiones</button>
-                <button type="button" class="btn default" onclick="cerrarDialog()">Cerrar</button>
-            </div>
-        </div>
+  </div>
+  <div class="form-actions">
+    <h4 class="form-section"> </h4>
+    <div class="row">
+      <div class="col-md-12">
+        <button type="button" class="btn green" disabled=​"disabled" onclick="generateCommissions()" id="generate_button">Generar comisiones</button>
+        <button type="button" class="btn default" onclick="cerrarDialog()">Cerrar</button>
+      </div>
     </div>
+  </div>
 </div>
 <script>
-    function cerrarDialog() {
-        $('#dialog').modal('toggle');
-    }
+  function cerrarDialog() {
+    $('#dialog').modal('toggle');
+  }
 
-    $('#initial_date').datetimepicker({
-        icons: {
-            date: "fa fa-calendar"
-        },
-        format: "DD/MM/YYYY"
-    });
+  $('#initial_date').datetimepicker({
+    icons: {
+      date: "fa fa-calendar"
+    },
+    format: "DD/MM/YYYY"
+  });
 
-    $('#final_date').datetimepicker({
-        icons: {
-            date: "fa fa-calendar"
-        },
-        format: "DD/MM/YYYY"
-    });
+  $('#final_date').datetimepicker({
+    icons: {
+      date: "fa fa-calendar"
+    },
+    format: "DD/MM/YYYY"
+  });
 
-    function getSellersByDates() {
-        if ($("#initial_date").data("date") && $("#final_date").data("date") && $('#pointsale_id').val()) {
+  function getSellersByDates() {
+    if ($("#initial_date").data("date") && $("#final_date").data("date") && $('#pointsale_id').val()) {
+      var initial_date = moment($("#initial_date").data("date"), "DD-MM-YYYY").startOf('day').format('YYYY-MM-DD HH:mm:ss');
+      var final_date = moment($("#final_date").data("date"), "DD-MM-YYYY").endOf('day').format('YYYY-MM-DD HH:mm:ss');
+      var pointsale_id = $('#pointsale_id').val();
+      App.blockUI({
+        target: $("#sellers_div"),
+        animate: true
+      });
 
-            var initial_date = moment($("#initial_date").data("date"), "DD-MM-YYYY").startOf('day').format('YYYY-MM-DD HH:mm:ss');
-            var final_date = moment($("#final_date").data("date"), "DD-MM-YYYY").endOf('day').format('YYYY-MM-DD HH:mm:ss');
-            var pointsale_id = $('#pointsale_id').val();
-
-            App.blockUI({
-                 target: $("#sellers_div"),
-                 animate: true
-            });
-
-            $.ajax({
-              type: "get",
-              url:  '/find_sellers_by_date/' + pointsale_id+ '/' + initial_date + '/' + final_date,
-              dataType: 'json',
-              success: function(data) {
-                  console.log(data);
-                  $('#sellers_ids').html('');
-                  for (var i = 0; i < data.length; i++) {
-                    $('#sellers_ids').append($('<option>', {
-                        value: data[i].seller_id,
-                        text : data[i].name
-                    }));
-                  }
-                  $('#sellers_ids').multiselect('refresh');
-                  App.unblockUI($("#sellers_div"));
-                  $('#generate_button').prop('disabled', false);
-              },
-                error: function (err) {
-                    App.unblockUI($("#sellers_div"));
-                    toastr["error"]('Ya se generaron comisiones para el periodo seleccionado');
-                }
-            });
-
-        } else {
-            toastr["error"]('Seleccione punto de venta y rango de fechas');
+      $.ajax({
+        type: "get",
+        url: '/find_sellers_by_date/' + pointsale_id + '/' + initial_date + '/' + final_date,
+        dataType: 'json',
+        success: function(data) {
+          $('#sellers_ids').html('');
+          for (var i = 0; i < data.length; i++) {
+            $('#sellers_ids').append($('<option>', {
+              value: data[i].seller_id,
+              text : data[i].name
+            }));
+          }
+          $('#sellers_ids').multiselect('refresh');
+          App.unblockUI($("#sellers_div"));
+          $('#generate_button').prop('disabled', false);
+        },
+        error: function (err) {
+          App.unblockUI($("#sellers_div"));
+          toastr["error"]('Ya se generaron comisiones para el periodo seleccionado');
         }
+      });
+
+    } else {
+        toastr["error"]('Seleccione punto de venta y rango de fechas');
     }
+  }
 
-    function generateCommissions() {
-       if($('#sellers_ids').val()) {
-            var initial_date = moment($("#initial_date").data("date"), "DD-MM-YYYY").startOf('day').format('YYYY-MM-DD HH:mm:ss');
-            var final_date = moment($("#final_date").data("date"), "DD-MM-YYYY").endOf('day').format('YYYY-MM-DD HH:mm:ss');
-            $.ajax({
-              type: "get",
-              url:  '/generate_commissions/',
-              dataType: 'script',
-              data: {
-                sellers_ids: $('#sellers_ids').val(),
-                pointsale_id: $('#pointsale_id').val(),
-                initial_date: initial_date,
-                final_date: final_date
-              },
-              success: function(data) {
-              }
-            });
-       } else {
-            toastr["error"]('Seleccione vendedores para generar comisiones');
-       }
+  function generateCommissions() {
+    if($('#sellers_ids').val()) {
+      var initial_date = moment($("#initial_date").data("date"), "DD-MM-YYYY").startOf('day').format('YYYY-MM-DD HH:mm:ss');
+      var final_date = moment($("#final_date").data("date"), "DD-MM-YYYY").endOf('day').format('YYYY-MM-DD HH:mm:ss');
+      $.ajax({
+        type: "get",
+        url: '/generate_commissions/',
+        dataType: 'script',
+        data: {
+          sellers_ids: $('#sellers_ids').val(),
+          pointsale_id: $('#pointsale_id').val(),
+          initial_date: initial_date,
+          final_date: final_date
+        },
+        success: function(data) {
+        }
+      });
+    } else {
+      toastr["error"]('Seleccione vendedores para generar comisiones');
     }
+  }
 </script>

+ 58 - 72
app/views/customers/customer_sales.html.erb

@@ -85,9 +85,9 @@
 																		</span>
 																	</div>
 																</div>
-															<button class="btn btn-icon-only blue" style="margin-left:25px" onclick="salesByDate()">
-																<i class="fa fa-search"></i>
-															</button>
+																<button class="btn btn-icon-only blue" style="margin-left:25px" onclick="salesByDate()">
+																	<i class="fa fa-search"></i>
+																</button>
 															</div>
 														</div>
 													</div>
@@ -99,7 +99,7 @@
 														<tr>
 															<th>#</th>
 															<th>Código de venta</th>
-															<% if current_user.usertype == 'A' %>
+															<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 																<th>Punto de venta</th>
 															<% end %>
 															<th>Vendedor</th>
@@ -113,67 +113,54 @@
 															<th width="15%">Acciones</th>
 														</tr>
 													</thead>
-													<tbody id="customer_sales" >
-													<% @sales.each_with_index do |sale, key| %>
-														<tr class=<%= (sale.cancelled? ? 'danger' : (sale.paid? ? 'success' : '')) %>>
-															<td><%= sale.id %></td>
-															<td><%= sale.sale_code %> </td>
-															<% if current_user.usertype == 'A' %>
-																<td> <%= sale.get_pointsale.name %> </td>
-															<% end %>
-															<td><%= sale.user.first_name %> </td>
-															<td><%= l(sale.date_sale, :format => '%d/%m/%Y') %></td>
-															<td>
-															<% if sale.saletype == "credit" && sale.credit_note.blank? %>
-																Crédito
-															<% elsif sale.saletype == "credit" && sale.credit_note.present? %>
-																Crédito/vale
-															<% else %>
-																Contado
-															<% end %>
-															</td>
-															<td><%= sale.products.count %></td>
-															<td>
-															<% case sale.status %>
-																<% when "paid"%>
-																	<span class="label label-success"> PAGADA </span>
-																<% when "cancelled"%>
-																	<span class="label label-danger"> CANCELADO </span>
-																<% when "parcial"%>
-																	<span class="label label-warning"> ABONADA </span>
-																<% when "notpaid"%>
-																	<span class="label label-default"> PENDIENTE PAGO </span>
-															<% end %>
-															</td>
-															<td><%= number_to_currency(sale.total, precision: 2) %></td>
-
-															<% credito = Credit.where(:sale_id => sale.id).first %>
-
-															<% if credito.present? %>
-																<% abonos = CreditPayment.where(:credit_id => credito.id, :status => 0).sum(:quantity) %>
-																<% if abonos.present? %>
-																	<td><%= number_to_currency(abonos, precision: 2) %></td>
+													<tbody id="customer_sales">
+														<% @sales.each_with_index do |sale, key| %>
+															<tr class=<%= (sale.cancelled? ? 'danger' : (sale.paid? ? 'success' : '')) %>>
+																<td><%= sale.id %></td>
+																<td><%= sale.sale_code %> </td>
+																<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+																	<td> <%= sale.get_pointsale.name %> </td>
 																<% end %>
-																<td><%= number_to_currency(credito.rest, precision: 2) %></td>
-															<% else %>
-																<td></td>
-																<td></td>
-															<% end %>
-
-															<td class="text-center">
-																<%= link_to sale, {:class=>"btn btn-icon-only default", :title=>"Ver venta"} do %>
-																	<i class="fa fa-search"></i>
+																<td><%= sale.user.first_name %> </td>
+																<td><%= l(sale.date_sale, :format => '%d/%m/%Y') %></td>
+																<td>
+																	<% if sale.saletype == "credit" && sale.credit_note.blank? %>
+																		Crédito
+																	<% elsif sale.saletype == "credit" && sale.credit_note.present? %>
+																		Crédito/vale
+																	<% else %>
+																		Contado
+																	<% end %>
+																</td>
+																<td><%= sale.products.count %></td>
+																<td><%= sale_status(sale) %></td>
+																<td><%= number_to_currency(sale.total, precision: 2) %></td>
+																<% credito = Credit.where(:sale_id => sale.id).first %>
+																<% if credito.present? %>
+																	<% abonos = CreditPayment.where(:credit_id => credito.id, :status => 0).sum(:quantity) %>
+																	<% if abonos.present? %>
+																		<td><%= number_to_currency(abonos, precision: 2) %></td>
+																	<% end %>
+																	<td><%= number_to_currency(credito.rest, precision: 2) %></td>
+																<% else %>
+																	<td></td>
+																	<td></td>
 																<% end %>
-															<% if can? :destroy, Sale %>
-																<% daysToCancel = @pos_config.days_cancel_sale %>
-																	<% if (sale.date_sale + daysToCancel.days >= Date.today) && !sale.cancelled? %>
-																		<%= link_to sale , method: :delete, :class => "btn btn-icon-only btn-danger", :title=>"Cancelar venta", data: { confirm: '¿Esta seguro que desea cancelar la venta?'}   do %> <i class="fa fa-ban"></i>
+
+																<td class="text-center">
+																	<%= link_to sale, {:class=>"btn btn-icon-only default", :title=>"Ver venta"} do %>
+																		<i class="fa fa-search"></i>
+																	<% end %>
+																	<% if can? :destroy, Sale %>
+																		<% daysToCancel = @pos_config.days_cancel_sale %>
+																		<% if (sale.date_sale + daysToCancel.days >= Date.today) && !sale.cancelled? %>
+																			<%= link_to sale , method: :delete, :class => "btn btn-icon-only btn-danger", :title=>"Cancelar venta", data: { confirm: '¿Está seguro que desea cancelar la venta?' } do %> <i class="fa fa-ban"></i>
+																			<% end %>
 																		<% end %>
 																	<% end %>
-															<% end %>
-															</td>
-														</tr>
-													<% end %>
+																</td>
+															</tr>
+														<% end %>
 													</tbody>
 												</table>
 												</div>
@@ -212,11 +199,10 @@
 																		<span class="label label-success"> ACTIVO </span>
 																	<% end %>
 																</td>
-
 																<td class="text-center">
 																<% if !abono.cancelled? && abono.cash_registers_move.present? && abono.cash_registers_move.open_cash_register.open?%>
-																		<%= link_to cash_move_delete_payment_path(:credit_payment_id => abono.id, :credit => credit.id) , method: :delete_credit_payment, :class => "btn btn-icon-only btn-danger", :title=>"Cancelar abono", data: { confirm: '¿Esta seguro que desea cancelar el abono?'}   do %> <i class="fa fa-ban"></i>
-																		<% end %>
+																	<%= link_to cash_move_delete_payment_path(:credit_payment_id => abono.id, :credit => credit.id) , method: :delete_credit_payment, :class => "btn btn-icon-only btn-danger", :title=>"Cancelar abono", data: { confirm: '¿Está seguro que desea cancelar el abono?' } do %> <i class="fa fa-ban"></i>
+																	<% end %>
 																<% end %>
 																</td>
 															</tr>
@@ -269,20 +255,20 @@
 		var end = moment($("#end_date").data("date"), "DD-MM-YYYY").format('YYYY-MM-DD HH:mm:ss');
 		var cliente = '<%= @custom.id %>'
 		App.blockUI({
-				 target: $("#sales_table"),
-				 animate: true
+			target: $("#sales_table"),
+			animate: true
 		});
 		$.ajax({
 			type: "get",
 			url:  '/find_customer_sales_by_date/' + start + '/' + end + '/' + cliente,
 			dataType: 'script',
 			success: function(data) {
-					window.setTimeout(function() {
-						App.unblockUI($("#sales_table"));
-						var startDate = moment($("#begin_date").data("date"), "DD-MM-YYYY").format('DD/MM/YYYY')
-						var endDate = moment($("#end_date").data("date"), "DD-MM-YYYY").format('DD/MM/YYYY');
-						$('#title_for_print').val('Ventas del ' + startDate + ' al ' + endDate);
-					}, 100);
+				window.setTimeout(function() {
+					App.unblockUI($("#sales_table"));
+					var startDate = moment($("#begin_date").data("date"), "DD-MM-YYYY").format('DD/MM/YYYY')
+					var endDate = moment($("#end_date").data("date"), "DD-MM-YYYY").format('DD/MM/YYYY');
+					$('#title_for_print').val('Ventas del ' + startDate + ' al ' + endDate);
+				}, 100);
 			}
 		});
 	}

+ 78 - 78
app/views/dashboard/_dashboard_for_admin.html.erb

@@ -1,104 +1,104 @@
 <div class="row">
-    <div class="col-md-12">
-        <div class="col-md-6">
-            <div class="portlet light">
-                <div class="portlet-title">
-                    <div class="caption caption-md">
-                        <i class="icon-bar-chart font-red"></i>
-                        <span class="caption-subject font-red uppercase bold">Ingresos por punto de venta</span>
-                    </div>
-                    <div class="actions">
-                        <div class="btn-group btn-group-devided" data-toggle="buttons">
-                            <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm active">
-                                <input type="radio" name="optionsIncomings" class="toggle" value="day">Día
-                            </label>                        
-                            <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm">
-                                <input type="radio" name="optionsIncomings" class="toggle" value="week">Semana
-                            </label>
-                            <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm">
-                                <input type="radio" name="optionsIncomings" class="toggle" value="month">Mes
-                            </label>
-                        </div>
-                    </div>
-                </div>
-                    <div id="incomingsByPointsaleChart" class="chart" style="width:100%;height:400px;font-size:11px;"></div>
+  <div class="col-md-12">
+    <div class="col-md-6">
+      <div class="portlet light">
+        <div class="portlet-title">
+          <div class="caption caption-md">
+            <i class="icon-bar-chart font-red"></i>
+            <span class="caption-subject font-red uppercase bold">Ingresos por punto de venta</span>
+          </div>
+          <div class="actions">
+            <div class="btn-group btn-group-devided" data-toggle="buttons">
+              <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm active">
+                <input type="radio" name="optionsIncomings" class="toggle" value="day">Día
+              </label>
+              <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm">
+                <input type="radio" name="optionsIncomings" class="toggle" value="week">Semana
+              </label>
+              <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm">
+                <input type="radio" name="optionsIncomings" class="toggle" value="month">Mes
+              </label>
             </div>
+          </div>
         </div>
+          <div id="incomingsByPointsaleChart" class="chart" style="width:100%;height:400px;font-size:11px;"></div>
+      </div>
+    </div>
 
-        <div class="col-md-6">
-            <div class="portlet light">
-                <div class="portlet-title">
-                    <div class="caption caption-md">
-                        <i class="icon-bar-chart font-red"></i>
-                        <span class="caption-subject font-red uppercase bold">10 productos mas vendidos</span>
-                    </div>
-                    <div class="actions">
-                        <div class="btn-group btn-group-devided" data-toggle="buttons">
-                            <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm active">
-                                <input type="radio" name="optionsRanking" class="toggle" value="week">Semana
-                            </label>
-                            <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm">
-                                <input type="radio" name="optionsRanking" class="toggle" value="month">Mes
-                            </label>
-                        </div>
-                    </div>
-                </div>
-                 <div id="productRankingChart" class="chart" style="width:100%;height:400px;font-size:11px;"></div>
+    <div class="col-md-6">
+      <div class="portlet light">
+        <div class="portlet-title">
+          <div class="caption caption-md">
+            <i class="icon-bar-chart font-red"></i>
+            <span class="caption-subject font-red uppercase bold">10 productos mas vendidos</span>
+          </div>
+          <div class="actions">
+            <div class="btn-group btn-group-devided" data-toggle="buttons">
+              <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm active">
+                <input type="radio" name="optionsRanking" class="toggle" value="week">Semana
+              </label>
+              <label class="btn btn-transparent grey-salsa btn-outline btn-circle btn-sm">
+                <input type="radio" name="optionsRanking" class="toggle" value="month">Mes
+              </label>
             </div>
+          </div>
         </div>
+         <div id="productRankingChart" class="chart" style="width:100%;height:400px;font-size:11px;"></div>
+      </div>
     </div>
+  </div>
 </div>
 
 <script type="text/javascript">
 $(document).on("page:change", function() {
-    // ingresos por punto de venta
-    MakeChart('serial', <%= @incomings %>, 'incomingsByPointsaleChart', 'pointsale', 'total');
-    // ranking de productos
-    MakeChart('pie', <%= @product_ranking %>, 'productRankingChart', 'product', 'quantity');    
+  // ingresos por punto de venta
+  MakeChart('serial', <%= @incomings %>, 'incomingsByPointsaleChart', 'pointsale', 'total');
+  // ranking de productos
+  MakeChart('pie', <%= @product_ranking %>, 'productRankingChart', 'product', 'quantity');
 });
 
 
 $('input:radio[name=optionsIncomings]').change(function() {
-    var period = $('input:radio[name=optionsIncomings]:checked').val();
-    getChart('incomings', period);
+  var period = $('input:radio[name=optionsIncomings]:checked').val();
+  getChart('incomings', period);
 });
 
 $('input:radio[name=optionsRanking]').change(function() {
-    var period = $('input:radio[name=optionsRanking]:checked').val();
-    getChart('products', period);
+  var period = $('input:radio[name=optionsRanking]:checked').val();
+  getChart('products', period);
 });
 
 setTimeout(function() {
-    $('.chart a').remove();
+  $('.chart a').remove();
 }, 1000);
 
 
 function getChart(chart, period) {
-    App.blockUI({
-         target: $((chart == "incomings" ? "#incomingsByPointsaleChart" : "#productRankingChart")),
-         animate: true
-    });
-    $.ajax({
-      type: "get",
-      url:  '/get_chart_data_for_dashboard/',
-      data: {
-        period: period,
-        chart: chart
-      },
-      dataType: 'text',
-      success: function(data) {
-          var data = JSON.parse(data);
-          window.setTimeout(function() {
-            App.unblockUI($((chart == "incomings" ? "#incomingsByPointsaleChart" : "#productRankingChart")));
-            
-            if (chart == 'incomings') {
-                MakeChart('serial', data, 'incomingsByPointsaleChart', 'pointsale', 'total');
-            } else {
-                MakeChart('pie', data, 'productRankingChart', 'product', 'quantity');
-            }
-            $('.chart a').remove();
-          }, 100);
-      }
-    });    
+  App.blockUI({
+    target: $((chart == "incomings" ? "#incomingsByPointsaleChart" : "#productRankingChart")),
+    animate: true
+  });
+  $.ajax({
+    type: "get",
+    url:  '/get_chart_data_for_dashboard/',
+    data: {
+    period: period,
+    chart: chart
+    },
+    dataType: 'text',
+    success: function(data) {
+      var data = JSON.parse(data);
+      window.setTimeout(function() {
+        App.unblockUI($((chart == "incomings" ? "#incomingsByPointsaleChart" : "#productRankingChart")));
+
+        if (chart == 'incomings') {
+          MakeChart('serial', data, 'incomingsByPointsaleChart', 'pointsale', 'total');
+        } else {
+          MakeChart('pie', data, 'productRankingChart', 'product', 'quantity');
+        }
+        $('.chart a').remove();
+      }, 100);
+    }
+  });
 }
-</script>
+</script>

+ 1 - 1
app/views/dashboard/index.html.erb

@@ -40,7 +40,7 @@
 							</div>
 						<% end %>
 					</div>
-					<% if current_user.usertype == 'A' %>
+					<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 						<%= render 'dashboard/dashboard_for_admin' %>
 					<% elsif current_user.usertype == 'G' %>
 						<%= render 'dashboard/dashboard_for_manager' %>

+ 68 - 80
app/views/expenses/_form.html.erb

@@ -1,97 +1,86 @@
-<!-- BEGIN FORM-->
-<%= form_for(@expense, :html => {:class=>"form-horizontal"}) do |f| %>
-<div class="portlet-body form">
-  <% if @expense.errors.any? %>
-    <div class="alert alert-danger">
-      <strong>Tiene <%= pluralize(@expense.errors.count, "error") %> no se puede guardar el gasto</strong><br>
-    </div>
-  <% end %>
-  <div class="form-body">
-    <div class="row">
-      <div class="col-md-8">
-        <%= hidden_field_tag :concept_purchase_payment, @concept_purchase_payment.id %>
-        <div class="form-group">
-          <%= f.label :expense_code, {:class=>"col-md-3 control-label"} do %> Código de egreso
-          <span class="required">*</span>
-          <% end %>
-          <div class="col-md-4 input-group">
-            <span class="input-group-addon"><i class="fa fa-barcode"></i></span>
-            <%= f.text_field :expense_code, { :class=>"form-control", :readonly => true} %>
-          </div>
-        </div>
-        <% if current_user.usertype == "A" %>
+<%= form_for(@expense, html: { class: "form-horizontal" }) do |f| %>
+  <div class="portlet-body form">
+    <% if @expense.errors.any? %>
+      <div class="alert alert-danger">
+        <strong>Tiene <%= pluralize(@expense.errors.count, "error") %> no se puede guardar el gasto</strong><br>
+      </div>
+    <% end %>
+    <div class="form-body">
+      <div class="row">
+        <div class="col-md-8">
+          <%= hidden_field_tag :concept_purchase_payment, @concept_purchase_payment.id %>
           <div class="form-group">
-            <%= f.label :expense_date, "Fecha", {:class=>"col-md-3 control-label"} do %> Fecha
-            <span class="required">*</span>
-            <% end %>
-                <div class="col-sm-4" style="padding-left:0px;padding-right:0px;">
-                    <div class='input-group date' id='datetimepicker1'>
-                        <span class="input-group-addon">
-                            <span class="glyphicon glyphicon-calendar"></span>
-                        </span>
-                        <%= f.text_field :expense_date, class: 'form-control'%>
-                    </div>
-                </div>
+            <%= f.label :expense_code, { class: "col-md-3 control-label" } do %> Código de egreso <span class="required">*</span> <% end %>
+            <div class="col-md-4 input-group">
+              <span class="input-group-addon"><i class="fa fa-barcode"></i></span>
+              <%= f.text_field :expense_code, { class: "form-control", readonly: true } %>
+            </div>
           </div>
-        <% end %>
-        <% if current_user.usertype != "A" %>
+          <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+            <div class="form-group">
+              <%= f.label :expense_date, "Fecha", { class: "col-md-3 control-label" } do %> Fecha <span class="required">*</span> <% end %>
+              <div class="col-sm-4" style="padding-left:0px;padding-right:0px;">
+                <div class='input-group date' id='datetimepicker1'>
+                  <span class="input-group-addon">
+                    <span class="glyphicon glyphicon-calendar"></span>
+                  </span>
+                  <%= f.text_field :expense_date, class: 'form-control' %>
+                </div>
+              </div>
+            </div>
+          <% else %>
+            <div class="form-group">
+              <%= f.label :open_cash_register_id, "Caja registradora", { class: "col-md-3 control-label" } do %> Caja registradora <span class="required">*</span> <% end %>
+              <div class="input-group col-md-4 select2-bootstrap-prepend">
+                <%= f.select :open_cash_register_id, @current_user.pointsale.open_cash_registers.abiertas.map{ |o| [o.cash_register.name, o.id] }, { prompt: "Seleccione" }, { class: 'form-control select2', disabled: @is_cashier } %>
+                <% if current_user.usertype == 'C' %>
+                  <%= f.hidden_field :open_cash_register_id %>
+                <% end %>
+              </div>
+            </div>
+          <% end %>
           <div class="form-group">
-            <%= f.label :open_cash_register_id, "Caja registradora", {:class=>"col-md-3 control-label"} do %> Caja registradora
+            <%= f.label :expensesconcept_id, "Concepto", { class: "col-md-3 control-label" } do %>Concepto de egreso <span class="required">*</span> <% end %>
+            <div class="input-group col-md-4 select2-bootstrap-prepend">
+              <%= f.collection_select :expensesconcept_id, @expenses_concepts, :id, :name, { prompt: "Seleccione" }, { class: "form-control select2", style: "width: 100%" } %>
+            </div>
+          </div>
+          <div class="form-group hidden" id="purchases_div">
+            <%= f.label :purchases, "Concepto", { class: "col-md-3 control-label" } do %>Compras
             <span class="required">*</span>
             <% end %>
             <div class="input-group col-md-4 select2-bootstrap-prepend">
-              <%= f.select :open_cash_register_id, @current_user.pointsale.open_cash_registers.abiertas.map{|o| [o.cash_register.name, o.id]}, {:prompt => "Seleccione"}, { :class => 'form-control select2', :disabled => @is_cashier} %>
-              <% if current_user.usertype == 'C' %>
-                <%= f.hidden_field :open_cash_register_id %>
+              <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+                <%= select_tag "purchases", options_from_collection_for_select(Purchase.notpaid, :id, :code_with_price), include_blank: "Seleccione", class: "form-control select2" %>
+              <% else %>
+                <%= select_tag "purchases", options_from_collection_for_select(Purchase.notpaid.where(pointsale_id: current_user.pointsale_id), :id, :code_with_price), include_blank: "Seleccione", class: "form-control select2" %>
               <% end %>
             </div>
           </div>
-        <% end %>
-        <div class="form-group">
-          <%= f.label :expensesconcept_id, "Concepto", {:class=>"col-md-3 control-label"} do %>Concepto de egreso
-          <span class="required">*</span>
-          <% end %>
-          <div class="input-group col-md-4 select2-bootstrap-prepend">
-            <%= f.collection_select :expensesconcept_id, @expenses_concepts, :id, :name, {:prompt => "Seleccione"}, {:class => "form-control select2", :style => "width: 100%"} %>
-          </div>
-        </div>
-
-        <div class="form-group hidden" id="purchases_div">
-          <%= f.label :purchases, "Concepto", {:class=>"col-md-3 control-label"} do %>Compras
-          <span class="required">*</span>
-          <% end %>
-          <div class="input-group col-md-4 select2-bootstrap-prepend">
-            <% if current_user.usertype == 'A' %>
-              <%= select_tag "purchases", options_from_collection_for_select(Purchase.notpaid, :id, :code_with_price), :include_blank => "Seleccione",  class: "form-control select2" %>
-            <% else %>
-              <%= select_tag "purchases", options_from_collection_for_select(Purchase.notpaid.where(:pointsale_id => current_user.pointsale_id), :id, :code_with_price), :include_blank => "Seleccione",  class: "form-control select2" %>
+          <div class="form-group">
+            <%= f.label :quantity, { class: "col-md-3 control-label" } do %>Cantidad <span class="required">*</span>
             <% end %>
+            <div class="col-md-4" style="padding-left:0px;padding-right:0px">
+              <%= f.number_field :quantity, { class: "form-control" } %>
+            </div>
           </div>
-        </div>
-        <div class="form-group">
-          <%= f.label :quantity,  {:class=>"col-md-3 control-label"} do %>Cantidad <span class="required">*</span>
-          <% end %>
-          <div class="col-md-4" style="padding-left:0px;padding-right:0px">
-            <%= f.number_field :quantity, {:class=>"form-control" }  %>
-          </div>
-        </div>
-        <div class="form-group">
-          <%= f.label :observations, "Observaciones", {:class=>"col-md-3 control-label"} %>
-          <div class="col-md-9" style="padding-left:0px">
-            <%= f.text_area :observations, {:class=>"form-control", :rows=>5} %>
+          <div class="form-group">
+            <%= f.label :observations, "Observaciones", { class: "col-md-3 control-label" } %>
+            <div class="col-md-9" style="padding-left:0px">
+              <%= f.text_area :observations, { class: "form-control", rows: 5 } %>
+            </div>
           </div>
-        </div>
+      </div>
     </div>
-  </div>
-  <div class="form-actions">
-    <div class="row">
-      <div class="col-md-9">
-        <%= f.submit 'Guardar', {:class=>"btn green"} %>
-        <%= link_to 'Cancelar', expenses_path, {:class=>"btn default"} %>
+    <div class="form-actions">
+      <div class="row">
+        <div class="col-md-9">
+          <%= f.submit 'Guardar', { class: "btn green" } %>
+          <%= link_to 'Cancelar', expenses_path, { class: "btn default" } %>
+        </div>
       </div>
     </div>
   </div>
-</div>
 <% end %>
 <script type="text/javascript">
   $(document).on('page:change', function() {
@@ -126,7 +115,7 @@
     });
 
   function generateExpenseCode() {
-    <% if current_user.usertype == 'A' %>
+    <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
       $.ajax({
         type: "get",
         url:  '/get_next_expense_code/0',
@@ -149,4 +138,3 @@
     <% end %>
   }
 </script>
-

+ 3 - 3
app/views/expenses/index.html.erb

@@ -44,13 +44,13 @@
                   </div>
                   <div class="actions">
                     <% if can? :create, Expense %>
-                    <%= link_to new_expense_path, {:class=>"btn bold green pull-right"} do %> Nuevo egreso <i class="fa fa-plus"></i>
-                    <% end %>
+                      <%= link_to new_expense_path, {:class=>"btn bold green pull-right"} do %> Nuevo egreso <i class="fa fa-plus"></i>
+                      <% end %>
                     <% end %>
                   </div>
                 </div>
                 <div class="portlet-body">
-                  <% if current_user.usertype == "A" %>
+                  <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                     <%= render partial: 'expenses/expenses_for_admin' %>
                   <% else %>
                     <%= render partial: 'expenses/expenses_for_manager' %>

+ 102 - 103
app/views/expensesconcepts/index.html.erb

@@ -1,123 +1,122 @@
-		<!-- BEGIN CONTAINER -->
-		<div class="page-container">
-			<!-- BEGIN CONTENT -->
-			<div class="page-content-wrapper">
-				<!-- BEGIN CONTENT BODY -->
-				<!-- BEGIN PAGE HEAD-->
-				<div class="page-head">
-					<div class="container-fluid">
-						<!-- BEGIN PAGE TITLE -->
-						<div class="page-title">
-							<h1>Conceptos de Egresos </h1>
-						</div>
-						<!-- END PAGE TITLE -->
-					</div>
+<!-- BEGIN CONTAINER -->
+<div class="page-container">
+	<!-- BEGIN CONTENT -->
+	<div class="page-content-wrapper">
+		<!-- BEGIN CONTENT BODY -->
+		<!-- BEGIN PAGE HEAD-->
+		<div class="page-head">
+			<div class="container-fluid">
+				<!-- BEGIN PAGE TITLE -->
+				<div class="page-title">
+					<h1>Conceptos de Egresos </h1>
 				</div>
-				<!-- END PAGE HEAD-->
-				<!-- BEGIN PAGE CONTENT BODY -->
-				<div class="page-content">
-					<div class="container-fluid">
-						<!-- BEGIN PAGE BREADCRUMBS -->
-						<ul class="page-breadcrumb breadcrumb">
-							<%= render_breadcrumbs :tag => :li, :separator => ' <i class="fa fa-circle"></i> ' %>
-						</ul>
-						<!-- END PAGE BREADCRUMBS -->
-						<!-- BEGIN PAGE CONTENT INNER -->
-						<div class="page-content-inner">
-							<div id="notice">
-							<% if success %>
-							<div class="alert alert-success">
-								<p><%= success %></p>
-							</div>
-							<% elsif warning %>
-							<div class="alert alert-warning">
-								<p><%= warning %></p>
-							</div>
-							<% end %>
-							</div>
-							<div class="row">
-								<div class="col-md-12">
-									<div class="portlet light ">
-										<div class="portlet-title">
-											<div class="caption">
-												<i class="fa fa-list "></i>
-												<span class="caption-subject bold uppercase">Lista de conceptos de egresos</span>
-											</div>
-											<div class="actions">
-												<% if can? :create, Expensesconcept %>
-												<%= link_to new_expensesconcept_path, {:class=>"btn bold green pull-right filtros"} do %> Nuevo Concepto de egreso <i class="fa fa-plus"></i>
+				<!-- END PAGE TITLE -->
+			</div>
+		</div>
+		<!-- END PAGE HEAD-->
+		<!-- BEGIN PAGE CONTENT BODY -->
+		<div class="page-content">
+			<div class="container-fluid">
+				<!-- BEGIN PAGE BREADCRUMBS -->
+				<ul class="page-breadcrumb breadcrumb">
+					<%= render_breadcrumbs :tag => :li, :separator => ' <i class="fa fa-circle"></i> ' %>
+				</ul>
+				<!-- END PAGE BREADCRUMBS -->
+				<!-- BEGIN PAGE CONTENT INNER -->
+				<div class="page-content-inner">
+					<div id="notice">
+					<% if success %>
+					<div class="alert alert-success">
+						<p><%= success %></p>
+					</div>
+					<% elsif warning %>
+					<div class="alert alert-warning">
+						<p><%= warning %></p>
+					</div>
+					<% end %>
+					</div>
+					<div class="row">
+						<div class="col-md-12">
+							<div class="portlet light ">
+								<div class="portlet-title">
+									<div class="caption">
+										<i class="fa fa-list "></i>
+										<span class="caption-subject bold uppercase">Lista de conceptos de egresos</span>
+									</div>
+									<div class="actions">
+										<% if can? :create, Expensesconcept %>
+										<%= link_to new_expensesconcept_path, {:class=>"btn bold green pull-right filtros"} do %> Nuevo Concepto de egreso <i class="fa fa-plus"></i>
+										<% end %>
+										<% end %>
+									</div>
+								</div>
+								<div class="portlet-body">
+									<input type='hidden' name='filter' id='filter' value='<%= @filter %>' >
+									<input type='hidden' name='current_page' id='current_page' value='<%= @current_page %>' >
+									<table class="table table-striped table-bordered table-hover tableadvanced">
+										<thead>
+											<tr>
+												<th>#</th>
+												<th>Nombre</th>
+												<th>Descripción</th>
+												<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+													<th>Puntos de venta</th>
 												<% end %>
+												<th>Status</th>
+												<% if can? :manage, Expensesconcept %>
+													<th>Acciones</th>
 												<% end %>
-											</div>
-										</div>
-										<div class="portlet-body">
-											<input type='hidden' name='filter' id='filter' value='<%= @filter %>' >
-											<input type='hidden' name='current_page' id='current_page' value='<%= @current_page %>' >
-											<table class="table table-striped table-bordered table-hover tableadvanced">
-												<thead>
-													<tr>
-														<th>#</th>
-														<th>Nombre</th>
-														<th>Descripción</th>
-														<% if current_user.usertype == 'A' %>
-															<th>Puntos de venta</th>
-														<% end %>
-														<th>Status</th>
-														<% if can? :manage, Expensesconcept %>
-														<th>Acciones</th>
-														<% end %>
-													</tr>
-												</thead>
-												<tbody>
-													<% @expensesconcepts.each_with_index do |expensesconcept, key| %>
-													<tr>
-														<td><%= key + 1 %></td>
-														<td><%= expensesconcept.name %></td>
-                                                        <td><%= expensesconcept.description %></td>
-                                                        <% if current_user.usertype == 'A' %>
-	                                                        <td>
-	                                                        	<% if expensesconcept.allpoints %>
-	                                                        	Todos
-	                                                        	<% else %>
-	                                                        	<%= expensesconcept.pointsales.map { |pv| pv.name }.join(", ")  %>
-	                                                        	<% end %>
-	                                                        </td>
-                                                        <% end %>
-
-														<td class="text-center"><% if expensesconcept.status == "active" %>
+											</tr>
+										</thead>
+										<tbody>
+											<% @expensesconcepts.each_with_index do |expensesconcept, key| %>
+												<tr>
+													<td><%= key + 1 %></td>
+													<td><%= expensesconcept.name %></td>
+                          <td><%= expensesconcept.description %></td>
+                          <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+                            <td>
+                            	<% if expensesconcept.allpoints %>
+                            	Todos
+                            	<% else %>
+                            	<%= expensesconcept.pointsales.map { |pv| pv.name }.join(", ") %>
+                            	<% end %>
+                            </td>
+                          <% end %>
+													<td class="text-center">
+														<% if expensesconcept.active? %>
 															<i class="fa fa-check font-green"></i>
-															<% else %>
+														<% else %>
 															<i class="fa fa-times font-red"></i>
-															<% end %>
-														</td>
-														<% if can? :manage, Expensesconcept %>
+														<% end %>
+													</td>
+													<% if can? :manage, Expensesconcept %>
 														<td class="text-center">
-															<%= link_to edit_expensesconcept_path(expensesconcept), {:class=>"btn btn-icon-only btn-primary filtros", :title=>"Editar concepto de egreso"} do %>
+															<%= link_to edit_expensesconcept_path(expensesconcept), {:class=>"btn btn-icon-only btn-primary filtros", :title=>"Editar concepto de egreso" } do %>
 																<i class="fa fa-edit"></i>
 															<% end %>
 															<% unless @concept_purchase_payment.id == expensesconcept.id %>
-																<%= link_to expensesconcept_path(expensesconcept), method: :delete, :class => "btn btn-icon-only btn-danger", :title=>"Eliminar concepto de egreso", data: { confirm: '¿Esta seguro de eliminar el concepto de egreso?'}   do %>
+																<%= link_to expensesconcept_path(expensesconcept), method: :delete, :class => "btn btn-icon-only btn-danger", :title=>"Eliminar concepto de egreso", data: { confirm: '¿Está seguro de eliminar el concepto de egreso?' } do %>
 																	<i class="fa fa-trash-o"></i>
 																<% end %>
 															<% end %>
-
 														</td>
-														<% end %>
-													</tr>
-												<% end %>
-												</tbody>
-											</table>
-										</div>
-									</div>
+													<% end %>
+												</tr>
+											<% end %>
+										</tbody>
+									</table>
 								</div>
 							</div>
 						</div>
-						<!-- END PAGE CONTENT INNER -->
 					</div>
 				</div>
-				<!-- END PAGE CONTENT BODY -->
-				<!-- END CONTENT BODY -->
+				<!-- END PAGE CONTENT INNER -->
 			</div>
-			<!-- END CONTENT -->
 		</div>
-		<!-- END CONTAINER -->
+		<!-- END PAGE CONTENT BODY -->
+		<!-- END CONTENT BODY -->
+	</div>
+	<!-- END CONTENT -->
+</div>
+<!-- END CONTAINER -->

+ 8 - 10
app/views/product_wastes/index.html.erb

@@ -43,9 +43,8 @@
 										<span class="caption-subject bold uppercase">Lista de mermas</span>
 									</div>
 									<div class="actions">
-										<% if current_user.usertype != 'A' %>
-										<%= link_to new_product_waste_path, {:class=>"btn bold green pull-right"} do %> Nueva Merma de producto <i class="fa fa-plus"></i>
-										<% end %>
+										<% if can? :create, ProductWaste %>
+											<%= link_to new_product_waste_path, {:class=>"btn bold green pull-right"} do %> Nueva Merma de producto <i class="fa fa-plus"></i><% end %>
 										<% end %>
 									</div>
 								</div>
@@ -60,7 +59,7 @@
 												<th>Motivo</th>
 												<th>Registró</th>
 												<th>Fecha</th>
-												<% if current_user.usertype == 'A'%>
+												<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 													<th>Localización</th>
 												<% end %>
 												<th>Status</th>
@@ -70,7 +69,7 @@
 										<tbody>
 											<% @product_wastes.each_with_index do |product_waste, key| %>
 											<tr>
-												<td><%= key +1 %></td>
+												<td><%= key + 1 %></td>
 												<td><%= product_waste.product.sku %> </td>
 												<td>
 													<%= product_waste.product.name %><br>
@@ -80,19 +79,19 @@
 												<td><%= product_waste.reason %> </td>
 												<td><%= product_waste.user.first_name %> </td>
 												<td><%= l(product_waste.created_at, :format => '%d/%B/%Y') %></td>
-												<% if current_user.usertype == 'A'%>
-													<td> <%= product_waste.pointsale.present? ?  product_waste.pointsale.name : product_waste.warehouse.name %> </td>
+												<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+													<td> <%= product_waste.pointsale.present? ? product_waste.pointsale.name : product_waste.warehouse.name %> </td>
 												<% end %>
 												<td class="text-center">
 													<% case product_waste.status %>
 													<% when "active"%>
 														<i class="fa fa-check font-green"></i>
 													<% when "inactive"%>
-														<i class="fa fa-close font-red"></i>                         
+														<i class="fa fa-close font-red"></i>
 													<% end %>
 												</td>
 												<td class="text-center">
-													<%= link_to product_waste, method: :delete, :class => "btn btn-icon-only btn-danger", :title => "Eliminar merma", data: { confirm: '¿Esta seguro de eliminar la merma del producto?'}   do %> 
+													<%= link_to product_waste, method: :delete, :class => "btn btn-icon-only btn-danger", :title => "Eliminar merma", data: { confirm: '¿Está seguro de eliminar la merma del producto?' } do %>
 														<i class="fa fa-trash-o"></i>
 													<% end %>
 												</td>
@@ -113,4 +112,3 @@
 	</div>
 	<!-- END CONTENT -->
 </div>
-<!-- END CONTAINER

+ 192 - 195
app/views/products/edit_variants.html.erb

@@ -1,251 +1,248 @@
 	<!-- BEGIN CONTAINER -->
-	<div class="page-container">
+<div class="page-container">
 		<!-- BEGIN CONTENT -->
-		<div class="page-content-wrapper">
+	<div class="page-content-wrapper">
 			<!-- BEGIN CONTENT BODY -->
 			<!-- BEGIN PAGE HEAD-->
-			<div class="page-head">
-				<div class="container-fluid">
+		<div class="page-head">
+			<div class="container-fluid">
 					<!-- BEGIN PAGE TITLE -->
-					<div class="page-title">
-						<h1> Producto </h1>
-					</div>
-					<!-- END PAGE TITLE -->
+				<div class="page-title">
+					<h1> Producto </h1>
 				</div>
+					<!-- END PAGE TITLE -->
 			</div>
+		</div>
 			<!-- END PAGE HEAD-->
 			<!-- BEGIN PAGE CONTENT BODY -->
-			<div class="page-content">
-				<div class="container-fluid">
-					<%= link_to  products_path(:filter => @filter, :current_page => @current_page), {:class=>"fr-space btn blue-hoki "} do %>
-						<i class="fa fa-angle-left "></i>
-						Regresar
-					<% end %>
-					<!-- BEGIN PAGE BREADCRUMBS -->
-					<ul class="page-breadcrumb breadcrumb">
-						<%= render_breadcrumbs :tag => :li, :separator => ' <i class="fa fa-circle"></i> ' %>
-					</ul>
-					<!-- END PAGE BREADCRUMBS -->
-					<!-- BEGIN PAGE CONTENT INNER -->
-					<div class="page-content-inner">
-						<div id="notice"><%= notice %></div>
-						<div class="row">
-							<div class="col-md-12">
-								<%= form_tag(product_update_variants_path(@product.id), :multipart => true, :class => "form-horizontal", :id => "form") do |f| %>
-								<div class="portlet light  ">
-									<div class="portlet-title">
-										<div class="caption">
-											<i class="fa fa-edit font-blue-sharp"></i>
-											<span class="caption-subject font-blue-sharp bold uppercase">Modificar variantes del producto</span>
-											<span class="caption-helper"></span>
-										</div>
+		<div class="page-content">
+			<div class="container-fluid">
+				<%= link_to products_path(:filter => @filter, :current_page => @current_page), { class: "fr-space btn blue-hoki pull-right margin-bottom-10" } do %>
+					<i class="fa fa-angle-left "></i>
+					Regresar
+				<% end %>
+				<!-- BEGIN PAGE BREADCRUMBS -->
+				<ul class="page-breadcrumb breadcrumb">
+					<%= render_breadcrumbs :tag => :li, :separator => ' <i class="fa fa-circle"></i> ' %>
+				</ul>
+				<!-- END PAGE BREADCRUMBS -->
+				<!-- BEGIN PAGE CONTENT INNER -->
+				<div class="page-content-inner">
+					<div id="notice"><%= notice %></div>
+					<div class="row">
+						<div class="col-md-12">
+							<%= form_tag(product_update_variants_path(@product.id), :multipart => true, :class => "form-horizontal", :id => "form") do |f| %>
+							<div class="portlet light">
+								<div class="portlet-title">
+									<div class="caption">
+										<i class="fa fa-edit font-blue-sharp"></i>
+										<span class="caption-subject font-blue-sharp bold uppercase">Modificar variantes del producto</span>
+										<span class="caption-helper"></span>
 									</div>
-
-									<div class="portlet-body">
-										<div class="row">
-											<div class="col-md-6">
-												<div class="row static-info">
-													<div class="col-md-4 name"> SKU: </div>
-													<div class="col-md-8 value"> <%= @product.sku %></div>
-												</div>
-												<div class="row static-info">
-													<div class="col-md-4 name"> Producto: </div>
-													<div class="col-md-8 value"> <%= @product.name %> </div>
-												</div>
-												<% unless @product.parent_id.nil? %>
+								</div>
+								<div class="portlet-body">
+									<div class="row">
+										<div class="col-md-6">
+											<div class="row static-info">
+												<div class="col-md-4 name"> SKU: </div>
+												<div class="col-md-8 value"> <%= @product.sku %></div>
+											</div>
+											<div class="row static-info">
+												<div class="col-md-4 name"> Producto: </div>
+												<div class="col-md-8 value"> <%= @product.name %> </div>
+											</div>
+											<% unless @product.parent_id.nil? %>
 												<div class="row static-info">
-													<div class="col-md-4 name"> Presentacion: </div>
+													<div class="col-md-4 name"> Presentación: </div>
 													<div class="col-md-8 value"> <%= @product.display_attributes %> </div>
 												</div>
-												<% end %>
-												<div class="row static-info">
-													<div class="col-md-4 name"> Descripcion: </div>
-													<div class="col-md-8 value"> <%= @product.description %> </div>
-												</div>
-												<div class="row static-info">
-													<div class="col-md-4 name"> Unidad de medida: </div>
-													<div class="col-md-8 value"> <%= @product.unit.unit %> </div>
-												</div>
-												<div class="row static-info">
-													<div class="col-md-4 name"> Status: </div>
-													<div class="col-md-8 value"> <% if @product.status == "active" %> <span class="badge badge-success"> Activo</span>  <% else %> <span class="badge badge-danger"> Inactivo</span> <% end %></div>
-												</div>
+											<% end %>
+											<div class="row static-info">
+												<div class="col-md-4 name"> Descripción: </div>
+												<div class="col-md-8 value"> <%= @product.description %> </div>
 											</div>
-											<div class="col-md-6">
-												<div class="row static-info">
-													<div class="col-md-4 name"> Inventariado: </div>
-													<div class="col-md-8 value"> <% if @product.inventory %> <span class="label label-success"> Si</span>  <% else %> <span class="label label-danger"> No</span> <% end %> </div>
-												</div>
-												<div class="row static-info">
-													<div class="col-md-4 name"> Categorías: </div>
-													<div class="col-md-8 value">
-														<%  @product.categories.each_with_index do | cat, index | %>
-															<% if index > 0 %>  <br> <% end %>
-															<span class="badge badge-default badge-roundless" > <%= cat.category %> </span>
-														<% end %>
-													</div>
+											<div class="row static-info">
+												<div class="col-md-4 name"> Unidad de medida: </div>
+												<div class="col-md-8 value"> <%= @product.unit.unit %> </div>
+											</div>
+											<div class="row static-info">
+												<div class="col-md-4 name"> Status: </div>
+												<div class="col-md-8 value"> <% if @product.status == "active" %> <span class="badge badge-success"> Activo</span>  <% else %> <span class="badge badge-danger"> Inactivo</span> <% end %></div>
+											</div>
+										</div>
+										<div class="col-md-6">
+											<div class="row static-info">
+												<div class="col-md-4 name"> Inventariado: </div>
+												<div class="col-md-8 value"> <% if @product.inventory %> <span class="label label-success"> Si</span>  <% else %> <span class="label label-danger"> No</span> <% end %> </div>
+											</div>
+											<div class="row static-info">
+												<div class="col-md-4 name"> Categorías: </div>
+												<div class="col-md-8 value">
+													<% @product.categories.each_with_index do |cat, index| %>
+														<% if index > 0 %>  <br> <% end %>
+														<span class="badge badge-default badge-roundless" > <%= cat.category %> </span>
+													<% end %>
 												</div>
-												<% if current_user.usertype == "A" %>
+											</div>
+											<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 												<div class="row static-info">
 													<div class="col-md-4 name"> Precio compra: </div>
 													<div class="col-md-8 value"><%= (@product.is_in_dollars? ? "#{number_to_currency(@product.price_base_dollars, precision: 2)} USD" : "#{number_to_currency(@product.price_base, precision: 2)} MXN") %> </div>
 												</div>
-												<% end %>
-												<div class="row static-info">
-													<div class="col-md-4 name"> Precio venta base: </div>
-													<div class="col-md-8 value"> $ <%= @product.price_sale %> </div>
-												</div>
-
-											</div>
-										</div><br>
-										<h4 class="form-section presentaciones">Variantes</h4><hr>
-										<div class="col-md-9 col-md-offset-3">
-											<div class="alert alert-warning hidden">
-												Son <strong id="variantes"></strong> variantes del producto.
+											<% end %>
+											<div class="row static-info">
+												<div class="col-md-4 name"> Precio venta base: </div>
+												<div class="col-md-8 value"> $ <%= @product.price_sale %> </div>
 											</div>
 										</div>
+									</div><br>
+									<h4 class="form-section presentaciones">Variantes</h4><hr>
+									<div class="col-md-9 col-md-offset-3">
+										<div class="alert alert-warning hidden">
+											Son <strong id="variantes"></strong> variantes del producto.
+										</div>
+									</div>
 
-										<div class="form-group ">
-											<%= label_tag :size_list, "Tallas", {:class=>"col-md-3 control-label"} %>
-											<div class="col-md-9 div_sizes">
-												<button class="btn btn-primary btn-sm margin-bottom-10 add_size">Agregar talla</button>
-												<% @product.sizes.each_with_index do |s, i| %>
-													<%= text_field_tag "#{s.id}", s.name, :class => "form-control input-medium margin-bottom-10 sizes"  %>
-													<!-- < %= hidden_field_tag "size_#{s.id}", s.name %> -->
-												<% end %>
-												<%= hidden_field_tag "new_size_list", @product.sizes.to_json.to_s %>
-											</div>
+									<div class="form-group ">
+										<%= label_tag :size_list, "Tallas", {:class=>"col-md-3 control-label"} %>
+										<div class="col-md-9 div_sizes">
+											<button class="btn btn-primary btn-sm margin-bottom-10 add_size">Agregar talla</button>
+											<% @product.sizes.each_with_index do |s, i| %>
+												<%= text_field_tag "#{s.id}", s.name, :class => "form-control input-medium margin-bottom-10 sizes"  %>
+												<!-- < %= hidden_field_tag "size_#{s.id}", s.name %> -->
+											<% end %>
+											<%= hidden_field_tag "new_size_list", @product.sizes.to_json.to_s %>
 										</div>
+									</div>
 
-										<div class="form-group ">
-											<%= label_tag :color_list, "Colores", {:class=>"col-md-3 control-label"} %>
-											<div class="col-md-9 div_colors">
-												<button class="btn btn-primary btn-sm margin-bottom-10 add_color">Agregar color</button>
-												<% @product.colors.each_with_index do |s, i| %>
-													<%= text_field_tag "#{s.id}", s.name, :class => "form-control input-medium margin-bottom-10 colors"  %>
-													<!-- < %= hidden_field_tag "color_#{s.id}", s.name %> -->
-												<% end %>
-												<%= hidden_field_tag "new_color_list", @product.colors.to_json %>
-											</div>
+									<div class="form-group ">
+										<%= label_tag :color_list, "Colores", {:class=>"col-md-3 control-label"} %>
+										<div class="col-md-9 div_colors">
+											<button class="btn btn-primary btn-sm margin-bottom-10 add_color">Agregar color</button>
+											<% @product.colors.each_with_index do |s, i| %>
+												<%= text_field_tag "#{s.id}", s.name, :class => "form-control input-medium margin-bottom-10 colors"  %>
+												<!-- < %= hidden_field_tag "color_#{s.id}", s.name %> -->
+											<% end %>
+											<%= hidden_field_tag "new_color_list", @product.colors.to_json %>
 										</div>
+									</div>
 
-										<div class="form-group ">
-											<%= label_tag :style_list, "Estilos", {:class=>"col-md-3 control-label"} %>
-											<div class="col-md-9 div_styles">
-												<button class="btn btn-primary btn-sm margin-bottom-10 add_style">Agregar estilo</button>
-												<% @product.styles.each_with_index do |s, i| %>
-													<%= text_field_tag "#{s.id}", s.name, :class => "form-control input-medium margin-bottom-10 styles"  %>
-													<!-- < %= hidden_field_tag "style_#{s.id}", s.name %> -->
-												<% end %>
-												<%= hidden_field_tag "new_style_list", @product.styles.to_json %>
-											</div>
+									<div class="form-group ">
+										<%= label_tag :style_list, "Estilos", {:class=>"col-md-3 control-label"} %>
+										<div class="col-md-9 div_styles">
+											<button class="btn btn-primary btn-sm margin-bottom-10 add_style">Agregar estilo</button>
+											<% @product.styles.each_with_index do |s, i| %>
+												<%= text_field_tag "#{s.id}", s.name, :class => "form-control input-medium margin-bottom-10 styles"  %>
+												<!-- < %= hidden_field_tag "style_#{s.id}", s.name %> -->
+											<% end %>
+											<%= hidden_field_tag "new_style_list", @product.styles.to_json %>
 										</div>
-										<hr>
-										<div class="form-actions">
-											<div class="row">
-												<div class="col-md-9">
-													<%= submit_tag 'Guardar', {:class=>"btn green"} %>
-													<%= link_to 'Cancelar', products_path(:filter => @filter, :current_page => @current_page), {:class=>"btn default"} %>
-												</div>
+									</div>
+									<hr>
+									<div class="form-actions">
+										<div class="row">
+											<div class="col-md-9">
+												<%= submit_tag 'Guardar', {:class=>"btn green"} %>
+												<%= link_to 'Cancelar', products_path(:filter => @filter, :current_page => @current_page), {:class=>"btn default"} %>
 											</div>
 										</div>
-										<%= hidden_field_tag :variants %>
 									</div>
-
+									<%= hidden_field_tag :variants %>
 								</div>
-								<% end %>
 							</div>
+							<% end %>
 						</div>
 					</div>
-					<!-- END PAGE CONTENT INNER -->
 				</div>
+				<!-- END PAGE CONTENT INNER -->
 			</div>
+		</div>
 			<!-- END PAGE CONTENT BODY -->
 			<!-- END CONTENT BODY -->
-		</div>
-		<!-- END CONTENT -->
 	</div>
+		<!-- END CONTENT -->
+</div>
 	<!-- END CONTAINER -->
-	<script>
+<script>
 	$("#form").submit(function(e) {
 		var self = this;
 		e.preventDefault();
 
 		<% if @product.sizes.count > 0 %>
-		var sizes = JSON.parse($('#new_size_list').val());
-		$('.sizes').each(function () {
-			// console.log(this);
-			for (var i = 0; i < sizes.length ; i++) {
-				if(sizes[i].id == this.name){
-					sizes[i].name = this.value;
-				}
-			};
-		});
-		$('#new_size_list').val(JSON.stringify(sizes));
+			var sizes = JSON.parse($('#new_size_list').val());
+			$('.sizes').each(function () {
+				// console.log(this);
+				for (var i = 0; i < sizes.length ; i++) {
+					if(sizes[i].id == this.name){
+						sizes[i].name = this.value;
+					}
+				};
+			});
+			$('#new_size_list').val(JSON.stringify(sizes));
 		<% end %>
+
 		<% if @product.colors.count > 0 %>
-		var colors = JSON.parse($('#new_color_list').val());
-		$('.colors').each(function () {
-			// console.log(this);
-			for (var i = 0; i < colors.length ; i++) {
-				if(colors[i].id == this.name){
-					colors[i].name = this.value;
-				}
-			};
-		});
-		$('#new_color_list').val(JSON.stringify(colors));
+			var colors = JSON.parse($('#new_color_list').val());
+			$('.colors').each(function () {
+				// console.log(this);
+				for (var i = 0; i < colors.length ; i++) {
+					if(colors[i].id == this.name){
+						colors[i].name = this.value;
+					}
+				};
+			});
+			$('#new_color_list').val(JSON.stringify(colors));
 		<% end %>
+
 		<% if @product.styles.count > 0 %>
-		var styles = JSON.parse($('#new_style_list').val());
-		$('.styles').each(function () {
-			// console.log(this);
-			for (var i = 0; i < styles.length ; i++) {
-				if(styles[i].id == this.name){
-					styles[i].name = this.value;
-				}
-			};
-		});
-		$('#new_style_list').val(JSON.stringify(styles));
+			var styles = JSON.parse($('#new_style_list').val());
+			$('.styles').each(function () {
+				// console.log(this);
+				for (var i = 0; i < styles.length ; i++) {
+					if(styles[i].id == this.name){
+						styles[i].name = this.value;
+					}
+				};
+			});
+			$('#new_style_list').val(JSON.stringify(styles));
 		<% end %>
+
 		self.submit();
 		return false; //is superfluous, but I put it here as a fallback
 	});
 
 	$(document).ready(function() {
-	    var x = 1; //initlal text box count
-	    $('.add_size').click(function(e){ //on add input button click
-	        e.preventDefault();
-	        x++; //text box increment
-	        $('.div_sizes').append('<div class="margin-bottom-10"><div class="input-group"><input type="text" name="mynewsizes[]" class="form-control input-medium "/><a href="#" class="remove_field btn btn-icon-only red"><i class="fa fa-times"></i></a></div></div>'); //add input box
-
-	    });
-
-	    $('.div_sizes').on("click",".remove_field", function(e){ //user click on remove text
-	        e.preventDefault(); $(this).parent('div').remove(); x--;
-	    });
-
-	    var y = 1;
-	    $('.add_color').click(function(e){ //on add input button click
-	        e.preventDefault();
-	        y++; //text box increment
-	        $('.div_colors').append('<div class="margin-bottom-10"><div class="input-group"><input type="text" name="mynewcolors[]" class="form-control input-medium "/><a href="#" class="remove_field btn btn-icon-only red"><i class="fa fa-times"></i></a></div></div>'); //add input box
-
-	    });
-
-	    $('.div_colors').on("click",".remove_field", function(e){ //user click on remove text
-	        e.preventDefault(); $(this).parent('div').remove(); y--;
-	    });
-
-	    var z = 1;
-	    $('.add_style').click(function(e){ //on add input button click
-	        e.preventDefault();
-	        z++; //text box increment
-	        $('.div_styles').append('<div class="margin-bottom-10"><div class="input-group"><input type="text" name="mynewstyles[]" class="form-control input-medium "/><a href="#" class="remove_field btn btn-icon-only red"><i class="fa fa-times"></i></a></div></div>'); //add input box
-
-	    });
-
-	    $('.div_styles').on("click",".remove_field", function(e){ //user click on remove text
-	        e.preventDefault(); $(this).parent('div').remove(); z--;
-	    });
+    var x = 1; //initlal text box count
+    $('.add_size').click(function(e){ //on add input button click
+      e.preventDefault();
+      x++; //text box increment
+      $('.div_sizes').append('<div class="margin-bottom-10"><div class="input-group"><input type="text" name="mynewsizes[]" class="form-control input-medium "/><a href="#" class="remove_field btn btn-icon-only red"><i class="fa fa-times"></i></a></div></div>'); //add input box
+    });
+
+    $('.div_sizes').on("click",".remove_field", function(e){ //user click on remove text
+      e.preventDefault(); $(this).parent('div').remove(); x--;
+    });
+
+    var y = 1;
+    $('.add_color').click(function(e){ //on add input button click
+      e.preventDefault();
+      y++; //text box increment
+      $('.div_colors').append('<div class="margin-bottom-10"><div class="input-group"><input type="text" name="mynewcolors[]" class="form-control input-medium "/><a href="#" class="remove_field btn btn-icon-only red"><i class="fa fa-times"></i></a></div></div>'); //add input box
+    });
+
+    $('.div_colors').on("click",".remove_field", function(e){ //user click on remove text
+	    e.preventDefault(); $(this).parent('div').remove(); y--;
+    });
+
+    var z = 1;
+    $('.add_style').click(function(e){ //on add input button click
+      e.preventDefault();
+      z++; //text box increment
+      $('.div_styles').append('<div class="margin-bottom-10"><div class="input-group"><input type="text" name="mynewstyles[]" class="form-control input-medium "/><a href="#" class="remove_field btn btn-icon-only red"><i class="fa fa-times"></i></a></div></div>'); //add input box
+    });
+
+    $('.div_styles').on("click",".remove_field", function(e){ //user click on remove text
+      e.preventDefault(); $(this).parent('div').remove(); z--;
+	  });
 	});
-	</script>
+</script>

+ 2 - 2
app/views/products/index.html.erb

@@ -44,7 +44,7 @@
 												<span class="caption-subject bold uppercase">Lista de productos</span>
 											</div>
 											<div class="actions">
-												<% if current_user.usertype == 'A' || current_user.usertype == 'G' %>
+												<% if can? :create, Product %>
 													<%= link_to new_product_path(:filter => @filter, :current_page => @current_page), {:class=>"btn bold green pull-right filtros"} do %>
 														Nuevo Producto <i class="fa fa-plus"></i>
 													<% end %>
@@ -61,7 +61,7 @@
 														<th>#</th>
 														<th>Imagen</th>
 														<th>Producto</th>
-														<% if current_user.usertype == "A" %>
+														<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 														<th>Precio compra</th>
 														<% end %>
 														<th>Precio venta</th>

+ 24 - 61
app/views/products/show.html.erb

@@ -22,7 +22,7 @@
 							<i class="fa fa-angle-left "></i>
 							Regresar
 						<% end %>
-						<% if @current_user.usertype == 'A' %>
+						<% if @current_user.usertype == "A" || @current_user.usertype == "SS" %>
 							<%= link_to  edit_product_path(@product), {:class=>"btn btn-primary "} do %>
 								<i class="fa fa-edit"></i> Modificar
 							<% end %>
@@ -58,25 +58,6 @@
 												<!-- <button type="button" class="btn btn-circle green btn-sm">Follow</button>
 												<button type="button" class="btn btn-circle red btn-sm">Message</button>-->
 										</div>
-										<!-- END SIDEBAR BUTTONS -->
-										<!-- SIDEBAR MENU -->
-										<!-- <div class="profile-usermenu">
-												<ul class="nav">
-														<li class="active">
-																<a href="page_user_profile_1.html">
-																		<i class="icon-home"></i> Overview </a>
-														</li>
-														<li>
-																<a href="page_user_profile_1_account.html">
-																		<i class="icon-settings"></i> Account Settings </a>
-														</li>
-														<li>
-																<a href="page_user_profile_1_help.html">
-																		<i class="icon-info"></i> Help </a>
-														</li>
-												</ul>
-										</div> -->
-										<!-- END MENU -->
 									</div>
 									<!-- END PORTLET MAIN -->
 
@@ -143,13 +124,13 @@
 													<div class="row static-info">
 														<div class="col-md-4 name"> Categorías: </div>
 														<div class="col-md-8 value">
-															<%  @product.categories.each_with_index do | cat, index | %>
+															<%  @product.categories.each_with_index do |cat, index| %>
 																<% if index > 0 %>  <br> <% end %>
 																<span class="badge badge-default badge-roundless" > <%= cat.category %> </span>
 															<% end %>
 														</div>
 													</div>
-													<% if current_user.usertype == "A" %>
+													<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 													<div class="row static-info">
 														<div class="col-md-4 name"> Precio compra: </div>
 														<div class="col-md-8 value"><%= (@product.is_in_dollars? ? "#{number_to_currency(@product.price_base_dollars, precision: 2)} USD" : "#{number_to_currency(@product.price_base, precision: 2)} MXN") %> </div>
@@ -175,7 +156,7 @@
 											</div>
 										</div>
 									</div>
-									<% if current_user.usertype == "A" %>
+									<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 									<div class="row">
 										<div class="col-md-6">
 											<!-- BEGIN PORTLET -->
@@ -189,48 +170,30 @@
 												</div>
 												<div class="portlet-body">
 													<table class="table table-hover table-light">
-                                                    <thead>
-                                                        <tr class="uppercase">
-                                                            <th> punto de<br>venta </th>
-                                                            <th> existencia<br>de producto </th>
-                                                            <th> Ultima<br>venta </th>
-
-                                                        </tr>
-                                                    </thead>
-                                                    <tbody>
-                                                    	<% @product.pointsales.each_with_index do |pointsale, key|  %>
-                                                    	<tr>
-	                                                        <td>
-	                                                        	<%= pointsale.name %>
-	                                                        </td>
-	                                                        <td class="text-center">
-	                                                        	<%= @product.stock_in_pointsale(pointsale.id).round %>
-	                                                        </td>
-	                                                        <td>
-	                                                        	<% last_sale =  @product.last_sale(pointsale.id) %>
-	                                                        	<%= l(last_sale.created_at, :format => '%d/%m/%Y') unless last_sale.blank? %>
-	                                                        </td>
-	                                                    </tr>
-	                                                    <% end %>
-                                                    </tbody>
-                                                	</table>
+                            <thead>
+                              <tr class="uppercase">
+                                <th> punto de<br>venta </th>
+                                <th> existencia<br>de producto </th>
+                                <th> Ultima<br>venta </th>
+                              </tr>
+                            </thead>
+                            <tbody>
+	                          	<% @product.pointsales.each_with_index do |pointsale, key| %>
+                              	<tr>
+      	                          <td> <%= pointsale.name %> </td>
+                                  <td class="text-center"> <%= @product.stock_in_pointsale(pointsale.id).round %> </td>
+                                  <td>
+                                  	<% last_sale = @product.last_sale(pointsale.id) %>
+                                  	<%= l(last_sale.created_at, :format => '%d/%m/%Y') unless last_sale.blank? %>
+                                  </td>
+                                </tr>
+                              <% end %>
+                            </tbody>
+                        	</table>
 												</div>
 											</div>
 										</div>
 										<div class="col-md-6">
-											<!-- BEGIN PORTLET -->
-											<!-- <div class="portlet light ">
-												<div class="portlet-title">
-													<div class="caption caption-md">
-														<i class="fa fa-bar-chart theme-font hide"></i>
-														<span class="caption-subject font-green bold uppercase">Ventas del mes</span>
-														<span class="caption-helper hide"></span>
-													</div>
-												</div>
-												<div class="portlet-body">
-
-												</div>
-											</div> -->
 										</div>
 
 									</div>

+ 1 - 2
app/views/products_returns/_form.html.erb

@@ -128,7 +128,7 @@
                       <tr>
                         <th>#</th>
                         <th>Folio</th>
-                        <% if current_user.usertype == 'A' %>
+                        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                           <th>Pto. de venta</th>
                         <% end %>
                         <th>Cliente</th>
@@ -198,7 +198,6 @@
             </div>
             <div class="tab-pane" id="tab4">
               <h3 class="block">Finalizar devolución</h3>
-
               <div class="col-md-12 margin-top-10">
                 <table class="pull-right">
                   <thead>

+ 2 - 2
app/views/products_returns/index.html.erb

@@ -58,7 +58,7 @@
                     <thead>
                       <tr>
                         <th>Folio</th>
-                        <% if current_user.usertype == "A" %>
+                        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                           <th>Punto de venta</th>
                         <% end %>
                         <th>Fecha</th>
@@ -75,7 +75,7 @@
                     <% @products_returns.each_with_index do |product_return, key| %>
                         <tr>
                           <td> <%= product_return.return_code %></td>
-                          <% if current_user.usertype == "A" %>
+                          <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                             <td><%= product_return.pointsale.name %></td>
                           <% end %>
                           <td><%= l(product_return.created_at, :format => '%d/%m/%Y') %></td>

+ 379 - 383
app/views/purchases/_form.html.erb

@@ -1,30 +1,30 @@
-<%= form_for(@purchase, :html => {:class=>"form-horizontal", :id=> "purchase_form"}) do |f| %>
+<%= form_for(@purchase, html: { class: "form-horizontal", id: "purchase_form" }) do |f| %>
 	<div class="portlet-body form">
 	<%= hidden_field_tag :tax_percent, @pos_config.tax_percent %>
 	<div id="error_explanation"></div>
 		<!-- purchase code -->
 		<div class="form-group">
-			<%= f.label :purchase_code, {:class=>"col-md-2 control-label"} do %> Codigo de compra
+			<%= f.label :purchase_code, { class: "col-md-2 control-label" } do %> Código de compra
 			<span class="required">*</span>
 			<% end %>
 			<div class="col-md-3 input-group">
 				<span class="input-group-addon"><i class="fa fa-barcode"></i></span>
-				<%= f.text_field :purchase_code, {:class=>"form-control", :readonly => true} %>
+				<%= f.text_field :purchase_code, { class: "form-control", readonly: true } %>
 			</div>
 		</div>
 		<!-- fecha -->
 		<div class="form-group">
-			<%= f.label :purchase_date, {:class=>"col-md-2 control-label"} do %> Fecha
+			<%= f.label :purchase_date, { class: "col-md-2 control-label" } do %> Fecha
 			<span class="required">*</span>
 			<% end %>
 			<div class="col-md-3 input-group date date-picker">
 				<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
-				<%= f.date_field :purchase_date, {:value=>Date.today, :class=>"form-control", :readonly => true} %>
+				<%= f.date_field :purchase_date, { value: Date.today, class: "form-control", readonly: true } %>
 			</div>
 		</div>
 		<!-- tipo de destino -->
 		<div class="form-group">
-			<%= label_tag 'destiny', {:class=>"col-md-2 control-label"} do %> Destino del producto
+			<%= label_tag 'destiny', { class: "col-md-2 control-label" } do %> Destino del producto
 			<span class="required">*</span>
 			<% end %>
 			<div class="col-md-3" style="padding-left:0px;padding-right:0px">
@@ -42,40 +42,40 @@
 			</div>
 		</div>
 		<!-- punto de venta -->
-		<div class= "form-group <%=(@destiny == 'pointsale' ? '' : 'hidden')%>"  id='pointsale_div'>
-			<%= f.label :pointsale_id, "Punto de venta", {:class=>"col-md-2 control-label"} do %> Punto de venta
+		<div class= "form-group <%=(@destiny == 'pointsale' ? '' : 'hidden')%>" id='pointsale_div'>
+			<%= f.label :pointsale_id, "Punto de venta", { class: "col-md-2 control-label" } do %> Punto de venta
 			<span class="required">*</span>
 			<% end %>
 			<div class="input-group col-md-3 select2-bootstrap-prepend">
-				<%= f.collection_select :pointsale_id, Pointsale.activos, :id, :name, {:prompt => "Seleccione"}, {:class => "form-control select2", :disabled => @disable_pointsale} %>
-				<%= f.hidden_field :pointsale_id, {:id => 'pointsale'} %>
+				<%= f.collection_select :pointsale_id, Pointsale.activos, :id, :name, { prompt: "Seleccione" }, { class: "form-control select2", disabled: @disable_pointsale } %>
+				<%= f.hidden_field :pointsale_id, { id: 'pointsale' } %>
 			</div>
 		</div>
 		<!-- almacen -->
-		<div class= "form-group <%=(@destiny == 'warehouse' ? '' : 'hidden')%>"  id='warehouse_div'>
-			<%= f.label :warehouse_id, "Almacén", {:class=>"col-md-2 control-label"} do %> Almacén
+		<div class= "form-group <%=(@destiny == 'warehouse' ? '' : 'hidden')%>" id='warehouse_div'>
+			<%= f.label :warehouse_id, "Almacén", { class: "col-md-2 control-label" } do %> Almacén
 			<span class="required">*</span>
 			<% end %>
 			<div class="input-group col-md-3 select2-bootstrap-prepend">
-				<%= f.collection_select :warehouse_id, Warehouse.activos, :id, :name, {:prompt => "Seleccione"}, {:class => "form-control select2", :disabled => @disable_warehouse} %>
-				<%= f.hidden_field :warehouse_id, {:id => 'warehouse'} %>
+				<%= f.collection_select :warehouse_id, Warehouse.activos, :id, :name, { prompt: "Seleccione" }, { class: "form-control select2", disabled: @disable_warehouse } %>
+				<%= f.hidden_field :warehouse_id, { id: 'warehouse' } %>
 			</div>
 		</div>
 		<!-- proveedor -->
 		<div class="form-group">
-			<%= f.label :supplier_id, "Proveedor", {:class=>"col-md-2 control-label"} do %> Proveedor
+			<%= f.label :supplier_id, "Proveedor", { class: "col-md-2 control-label" } do %> Proveedor
 			<span class="required">*</span>
 			<% end %>
 			<div class="input-group col-md-3 select2-bootstrap-prepend">
-				<%= f.collection_select :supplier_id, Supplier.activos, :id, :nick_name, {:prompt => "Seleccione"}, {:class => "form-control select2", :disabled => @disable_supplier} %>
-				<%= f.hidden_field :supplier_id, {:id => 'supplier'} %>
+				<%= f.collection_select :supplier_id, Supplier.activos, :id, :nick_name, { prompt: "Seleccione" }, { class: "form-control select2", disabled: @disable_supplier } %>
+				<%= f.hidden_field :supplier_id, { id: 'supplier' } %>
 			</div>
 		</div>
 		<div class="form-group">
-			<%= f.label :is_in_dollars, {:class=>"col-md-2 control-label"} do %> tipo de Moneda
+			<%= f.label :is_in_dollars, { class: "col-md-2 control-label" } do %> Tipo de Moneda
 				<span class="required">*</span>
 			<% end %>
-			<div class="col-md-3"  style="padding-left:0px;padding-right:0px">
+			<div class="col-md-3" style="padding-left:0px;padding-right:0px">
 				<%= f.check_box(:is_in_dollars,
 					{
 						class: "make-switch",
@@ -90,15 +90,15 @@
 					"true", "false"
 				) %>
 			</div>
-			<%= f.hidden_field :is_in_dollars, {:id => 'is_in_dollars'} %>
+			<%= f.hidden_field :is_in_dollars, { id: 'is_in_dollars' } %>
 		</div>
 		<div class="form-group hidden" id="exchange_div">
-			<%= f.label :exchange, {:class=>"col-md-2 control-label"} do %> Tipo de cambio
+			<%= f.label :exchange, { class: "col-md-2 control-label" } do %> Tipo de cambio
 			<span class="required">*</span>
 			<% end %>
 			<div class="col-md-3 input-group">
 				<span class="input-group-addon"><i class="fa fa-usd"></i></span>
-				<%= f.number_field :exchange, {:class=>"form-control", :step=>"any"} %>
+				<%= f.number_field :exchange, { class: "form-control", step: "any" } %>
 			</div>
 		</div>
 		<!-- boton para resetear datos -->
@@ -121,7 +121,7 @@
 					</div>
 				</div>
 				<div class="col-md-2">
-					<button id="products_add_new" class="btn btn-success" type="button" onclick="addNewProduct()">  <i class="fa fa-plus"></i> Nuevo Producto </button>
+					<button id="products_add_new" class="btn btn-success" type="button" onclick="addNewProduct()"> <i class="fa fa-plus"></i> Nuevo Producto </button>
 				</div>
 			</div>
 		</div>
@@ -143,7 +143,7 @@
 					</tr>
 				</thead>
 				<tbody>
-				<%= render @pre_purchases %>
+					<%= render @pre_purchases %>
 				</tbody>
 			</table>
 		</div>
@@ -152,67 +152,67 @@
 		<div class="row">
 			<div class="col-md-6">
 				<div class="form-group">
-					 <%= f.label :observations, "Observaciones", {:class=>"col-md-3 control-label"} %>
+					 <%= f.label :observations, "Observaciones", { class: "col-md-3 control-label" } %>
 					 <div class="col-md-8">
-						 <%= f.text_area :observations, {:class=>"form-control", :rows=>5} %>
+						 <%= f.text_area :observations, { class: "form-control", rows: 5 } %>
 					 </div>
 				 </div>
 			 </div>
 			<div class="col-md-offset-1 col-md-5">
-					<div class="well">
-							<div class="row static-info align-reverse">
-									<div class="col-md-4 name"> Sub Total: </div>
-									<div class="col-md-8 value " id="amount_div">
-											<div class="input-group">
-												<span class="input-group-addon">$ </span>
-												<%= f.text_field :amount, {:class=>"form-control sub_total", :readonly => true, :id => "amount"}  %>
-												<span class="input-group-addon"></span>
-											</div>
-									</div>
+				<div class="well">
+					<div class="row static-info align-reverse">
+						<div class="col-md-4 name"> Sub Total: </div>
+						<div class="col-md-8 value " id="amount_div">
+							<div class="input-group">
+								<span class="input-group-addon">$ </span>
+								<%= f.text_field :amount, { class: "form-control sub_total", readonly: true, id: "amount" } %>
+								<span class="input-group-addon"></span>
 							</div>
-							<div class="row static-info align-reverse">
-									<div class="col-md-4 name"> IVA: </div>
-									<div class="col-md-8 value " id="tax_div">
-											<div class="input-group">
-												<span class="input-group-addon">$ </span>
-												<%= f.text_field :tax, {:class=>"form-control descto", :readonly => true, :id => "tax"}  %>
-												<span class="input-group-addon"></span>
-											</div>
-									</div>
+						</div>
+					</div>
+					<div class="row static-info align-reverse">
+						<div class="col-md-4 name"> IVA: </div>
+						<div class="col-md-8 value " id="tax_div">
+							<div class="input-group">
+								<span class="input-group-addon">$ </span>
+								<%= f.text_field :tax, { class: "form-control descto", readonly: true, id: "tax" } %>
+								<span class="input-group-addon"></span>
 							</div>
-							<div class="row static-info align-reverse">
-									<div class="col-md-4 name"> Total: </div>
-									<div class="col-md-8 value " id="total_div">
-											<div class="input-group">
-												<span class="input-group-addon">$ </span>
-												<%= f.text_field :total, {:class=>"form-control descto", :readonly => true, :id => "total"}  %>
-												<span class="input-group-addon"></span>
-											</div>
-									</div>
+						</div>
+					</div>
+					<div class="row static-info align-reverse">
+						<div class="col-md-4 name"> Total: </div>
+						<div class="col-md-8 value " id="total_div">
+							<div class="input-group">
+								<span class="input-group-addon">$ </span>
+								<%= f.text_field :total, { class: "form-control descto", readonly: true, id: "total" } %>
+								<span class="input-group-addon"></span>
 							</div>
+						</div>
 					</div>
+				</div>
 			</div>
 			<div class="col-md-offset-7 col-md-5 hidden" id="total_in_mxn_div">
-					<div class="well">
-						<div class="row static-info align-reverse">
-								<div class="col-md-4 name"> Total en pesos: </div>
-								<div class="col-md-8 value ">
-										<div class="input-group">
-											<span class="input-group-addon">$ </span>
-												<%= text_field_tag :total_in_mxn, '' , :class=>"form-control", :readonly => true %>
-											<span class="input-group-addon">MXN</span>
-										</div>
-								</div>
+				<div class="well">
+					<div class="row static-info align-reverse">
+						<div class="col-md-4 name"> Total en pesos: </div>
+						<div class="col-md-8 value ">
+							<div class="input-group">
+								<span class="input-group-addon">$ </span>
+								<%= text_field_tag :total_in_mxn, '' , class: "form-control", readonly: true %>
+								<span class="input-group-addon">MXN</span>
+							</div>
 						</div>
 					</div>
+				</div>
 			</div>
 		</div>
 		<!-- acciones del form -->
 		<div class="form-actions">
 			<div class="row">
 				<div class="col-md-offset-2 col-md-9">
-					<%= f.submit 'Guardar', {:class=>"btn green"} %>
-					<%= link_to 'Cancelar', purchases_path(:filter => @filter, :current_page => @current_page), {:class=>"btn default"} %>
+					<%= f.submit 'Guardar', { class: "btn green" } %>
+					<%= link_to 'Cancelar', purchases_path(filter: @filter, current_page: @current_page), { class: "btn default" } %>
 				</div>
 			</div>
 		</div>
@@ -272,354 +272,350 @@
 			generatePurchaseCode();
 		});
 
-	 });
-
-		$('body').barcodeListener().on('barcode.valid', function(e, code) {
-			findProductByBarcode(code);
-		});
-
-			var bloodhound = new Bloodhound({
-				datumTokenizer: function (d) {
-					return Bloodhound.tokenizers.whitespace(d.value);
-				},
-				queryTokenizer: Bloodhound.tokenizers.whitespace,
-				remote: {
-					url: '/find_products?query=%QUERY',
-					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;
+	});
 
-			var supplier = $('#purchase_supplier_id').val();
-			var pointsale = $('#purchase_pointsale_id').val();
-			var warehouse = $('#purchase_warehouse_id').val();
+	$('body').barcodeListener().on('barcode.valid', function(e, code) {
+		findProductByBarcode(code);
+	});
 
-			if( (supplier && pointsale) || (supplier && warehouse) ) {
-				$('#products_new').attr('disabled', false);
-			} else {
-				toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
+	var bloodhound = new Bloodhound({
+		datumTokenizer: function (d) {
+			return Bloodhound.tokenizers.whitespace(d.value);
+		},
+		queryTokenizer: Bloodhound.tokenizers.whitespace,
+		remote: {
+			url: '/find_products?query=%QUERY',
+			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 addNewProduct() {
-			var pointsale = $('#purchase_pointsale_id').val();
-			var supplier = $('#purchase_supplier_id').val();
-			var warehouse = $('#purchase_warehouse_id').val();
-			var exchange = $('#purchase_exchange').val();
-			if( (supplier && pointsale) || (supplier && warehouse) ) {
-				$.ajax({
-					type: "GET",
-					url: "/products/new",
-					dataType: "script",
-					data: {
-						remoto: true,
-						pointsale: pointsale,
-						warehouse: warehouse,
-						supplier: supplier,
-						exchange: exchange
-					},
-					success: function(xhr, status, error) {}
-				});
-			} else {
-				toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
-			}
-		}
+		var supplier = $('#purchase_supplier_id').val();
+		var pointsale = $('#purchase_pointsale_id').val();
+		var warehouse = $('#purchase_warehouse_id').val();
 
-		function addRow() {
-			if(selectedProduct) {
-				$('#pre_purchase_supplier_id').val($('#supplier').val());
-				$('#pre_purchase_pointsale_id').val($('#pointsale').val());
-				$('#pre_purchase_warehouse_id').val($('#warehouse').val());
-				$('#pre_purchase_exchange').val($('#purchase_exchange').val());
-				$('#pre_purchase_price_base').val();
-				$('#pre_purchase_product_id').val(selectedProduct.id);
-				$('#pre_purchase_quantity').val(1);
-				$('#pre_purchase_amount').val(selectedProduct.price_sale);
-				$('#pre_purchase_tax').val(0);
-				$('#pre_purchase_total').val(0);
-
-				$('#new_pre_purchase').submit();
-				$('#typeahead').typeahead('val','');
-				$('#products_new').attr('disabled', true);
-			}
+		if( (supplier && pointsale) || (supplier && warehouse) ) {
+			$('#products_new').attr('disabled', false);
+		} else {
+			toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
 		}
-
-		function deleteRow(input) {
-			var table = $('#products_table').DataTable();
-			var idText = input.closest('tr').attr('id');
-			var prePurchaseId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
+	});
+
+	function addNewProduct() {
+		var pointsale = $('#purchase_pointsale_id').val();
+		var supplier = $('#purchase_supplier_id').val();
+		var warehouse = $('#purchase_warehouse_id').val();
+		var exchange = $('#purchase_exchange').val();
+		if( (supplier && pointsale) || (supplier && warehouse) ) {
 			$.ajax({
-				type: "DELETE",
-				url: "/pre_purchases/" + prePurchaseId,
-				dataType: "json",
-				data: "",
-				success: function(xhr, status, error) {
-					table.row(input.closest('tr')).remove().draw();
-					calculateTotals();
-				}
+				type: "GET",
+				url: "/products/new",
+				dataType: "script",
+				data: {
+					remoto: true,
+					pointsale: pointsale,
+					warehouse: warehouse,
+					supplier: supplier,
+					exchange: exchange
+				},
+				success: function(xhr, status, error) {}
 			});
+		} else {
+			toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
 		}
+	}
+
+	function addRow() {
+		if(selectedProduct) {
+			$('#pre_purchase_supplier_id').val($('#supplier').val());
+			$('#pre_purchase_pointsale_id').val($('#pointsale').val());
+			$('#pre_purchase_warehouse_id').val($('#warehouse').val());
+			$('#pre_purchase_exchange').val($('#purchase_exchange').val());
+			$('#pre_purchase_price_base').val();
+			$('#pre_purchase_product_id').val(selectedProduct.id);
+			$('#pre_purchase_quantity').val(1);
+			$('#pre_purchase_amount').val(selectedProduct.price_sale);
+			$('#pre_purchase_tax').val(0);
+			$('#pre_purchase_total').val(0);
+
+			$('#new_pre_purchase').submit();
+			$('#typeahead').typeahead('val','');
+			$('#products_new').attr('disabled', true);
+		}
+	}
+
+	function deleteRow(input) {
+		var table = $('#products_table').DataTable();
+		var idText = input.closest('tr').attr('id');
+		var prePurchaseId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
+		$.ajax({
+			type: "DELETE",
+			url: "/pre_purchases/" + prePurchaseId,
+			dataType: "json",
+			data: "",
+			success: function(xhr, status, error) {
+				table.row(input.closest('tr')).remove().draw();
+				calculateTotals();
+			}
+		});
+	}
+
+	function updateQuantity(input) {
+		if(input.val()) {
+			clearTimeout(timeout);
+			timeout = setTimeout(function () {
+				tax = 0;
+				quantity = parseInt(input.val());
+				// sacar el precio del producto
+				if (input.closest('tr').find('td:eq(5) input').val()) {
+					price = parseFloat(input.closest('tr').find('td:eq(5) input').val());
+				} else {
+					price = 0;
+				}
+				amount = price * quantity;
+				if(input.closest('tr').find('td:eq(0) input').val() == '1') {
+					taxPercent = parseFloat($('#tax_percent').val()) / 100
+					tax = (taxPercent * amount) / (1 + taxPercent);
+				}
+				input.closest('tr').find('td:eq(6)').text(Math.round(tax * 100) / 100);
+				input.closest('tr').find('td:eq(7)').text(Math.round(amount * 100) / 100);
+				calculateTotals();
 
-		function updateQuantity(input) {
-			if(input.val()) {
-				clearTimeout(timeout);
-				timeout = setTimeout(function () {
-					tax = 0;
-					quantity = parseInt(input.val());
-					// sacar el precio del producto
-					if (input.closest('tr').find('td:eq(5) input').val()) {
-						price = parseFloat(input.closest('tr').find('td:eq(5) input').val());
-					} else {
-						price = 0;
-					}
-					amount = price * quantity;
-					if(input.closest('tr').find('td:eq(0) input').val() == '1') {
-						taxPercent = parseFloat($('#tax_percent').val()) / 100
-						tax =  (taxPercent  * amount) / (1 + taxPercent);
-					}
-					input.closest('tr').find('td:eq(6)').text(Math.round(tax * 100) / 100);
-					input.closest('tr').find('td:eq(7)').text(Math.round(amount * 100) / 100);
-					calculateTotals();
-
-					var idText = input.closest('tr').attr('id');
-					var prePurchaseId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
+				var idText = input.closest('tr').attr('id');
+				var prePurchaseId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
 
-					$.ajax({
+				$.ajax({
+					type: "PUT",
+					url: "/pre_purchases/" + prePurchaseId,
+					dataType: "json",
+					data: {pre_purchase: {quantity: quantity }},
+					success: function(xhr, status, error) {
+					}
+				});
+			}, 700);
+		}
+	}
+
+	function updateProductPrice(input) {
+		if(input.val()) {
+			clearTimeout(timeout);
+			timeout = setTimeout(function () {
+				price = parseFloat(input.val());
+				var is_in_dollars = $('#purchase_is_in_dollars').bootstrapSwitch('state');
+				var exchange = $('#purchase_exchange').val() ? parseFloat($('#purchase_exchange').val()) : '';
+				var productId = input.closest('td').find('span').text();
+				$.ajax({
+					type: "POST",
+					url: "/products/" + productId + "/edit_from_purchase",
+					dataType: "script",
+					data: {product: {price_base: price }, is_in_dollars: is_in_dollars, exchange: exchange},
+					success: function(xhr, status, error) {
+							//actualizar datos en la tabla
+						tax = 0;
+						hasTax = input.closest('tr').find('td:eq(0) input').val();
+						quantity = parseFloat(input.closest('tr').find('td:eq(4) input').val());
+						price = parseFloat(input.closest('tr').find('td:eq(5) input').val());
+						amount = price * quantity;
+						if(hasTax == '1') {
+							taxPercent = parseFloat($('#tax_percent').val()) / 100
+							tax = (taxPercent * amount) / (1 + taxPercent);
+						}
+						input.closest('tr').find('td:eq(6)').text(Math.round(tax * 100) / 100);
+						input.closest('tr').find('td:eq(7)').text(Math.round(amount * 100) / 100);
+						var preIdText = input.closest('tr').attr('id');
+						var prePurchaseId = preIdText.substring(preIdText.lastIndexOf('_') + 1, preIdText.length);
+						$.ajax({
 							type: "PUT",
 							url: "/pre_purchases/" + prePurchaseId,
 							dataType: "json",
 							data: {pre_purchase: {quantity: quantity }},
 							success: function(xhr, status, error) {
+								calculateTotals();
 							}
-					});
-				}, 700);
-			}
+						});
+					}
+				});
+			}, 600);
 		}
-
-		function updateProductPrice(input) {
-			if(input.val()) {
-				clearTimeout(timeout);
-				timeout = setTimeout(function () {
-					price = parseFloat(input.val());
-					var is_in_dollars = $('#purchase_is_in_dollars').bootstrapSwitch('state');
-					var exchange = $('#purchase_exchange').val() ? parseFloat($('#purchase_exchange').val()) : '';
-					var productId = input.closest('td').find('span').text();
-					$.ajax({
-							type: "POST",
-							url: "/products/" + productId + "/edit_from_purchase",
-							dataType: "script",
-							data: {product: {price_base: price }, is_in_dollars: is_in_dollars, exchange: exchange},
-							success: function(xhr, status, error) {
-									//actualizar datos en la tabla
-									tax = 0;
-									hasTax = input.closest('tr').find('td:eq(0) input').val();
-									quantity = parseFloat(input.closest('tr').find('td:eq(4) input').val());
-									price = parseFloat(input.closest('tr').find('td:eq(5) input').val());
-									amount = price * quantity;
-									if(hasTax == '1') {
-										taxPercent = parseFloat($('#tax_percent').val()) / 100
-										tax =  (taxPercent  * amount) / (1 + taxPercent);
-									}
-									input.closest('tr').find('td:eq(6)').text(Math.round(tax * 100) / 100);
-									input.closest('tr').find('td:eq(7)').text(Math.round(amount * 100) / 100);
-									var preIdText = input.closest('tr').attr('id');
-									var prePurchaseId = preIdText.substring(preIdText.lastIndexOf('_') + 1, preIdText.length);
-									$.ajax({
-											type: "PUT",
-											url: "/pre_purchases/" + prePurchaseId,
-											dataType: "json",
-											data: {pre_purchase: {quantity: quantity }},
-											success: function(xhr, status, error) {
-												calculateTotals();
-											}
-									});
-							}
-					});
-				}, 600);
-			}
+	}
+
+	function calculateTotals() {
+		var amount = 0;
+		var tax = 0;
+		var total = 0;
+		$('#products_table tbody tr td:nth-child(7)').each(function() {
+			tax += parseFloat($(this).text());
+		});
+		$('#products_table tbody tr td:nth-child(8)').each(function() {
+			amount += parseFloat($(this).text());
+		});
+		amount = amount - tax;
+		total = amount + tax;
+		$('#tax').val(Math.round(tax * 100) / 100);
+		$('#amount').val(Math.round(amount * 100) / 100);
+		$('#total').val(Math.round(total * 100) / 100);
+
+		// mostrar el total en pesos cuando es en dolares
+		var is_in_dollars = $('#purchase_is_in_dollars').bootstrapSwitch('state');
+		if (is_in_dollars) {
+			$('#total_in_mxn').val(Math.round((total * $('#purchase_exchange').val()) * 100) / 100);
 		}
-
-		function calculateTotals() {
-			var amount = 0;
-			var tax    = 0;
-			var total  = 0;
-			$('#products_table tbody tr td:nth-child(7)').each(function() {
-				 tax+= parseFloat($(this).text());
-			});
-			$('#products_table tbody tr td:nth-child(8)').each(function() {
-				 amount+= parseFloat($(this).text());
-			});
-			amount = amount - tax;
-			total = amount + tax;
-			$('#tax').val(Math.round(tax * 100) / 100);
-			$('#amount').val(Math.round(amount * 100) / 100);
-			$('#total').val(Math.round(total * 100) / 100);
-
-			// mostrar el total en pesos cuando es en dolares
-			var is_in_dollars = $('#purchase_is_in_dollars').bootstrapSwitch('state');
-			if (is_in_dollars) {
-				$('#total_in_mxn').val(Math.round((total * $('#purchase_exchange').val()) * 100) / 100);
+	}
+
+	function deletePrePurchases() {
+		$.ajax({
+			type: "get",
+			url: '/delete_pre_purchases',
+			dataType: 'json',
+			success: function(xhr, status, error){
+				$('#products_table').dataTable().fnClearTable();
+				$('#purchase_purchase_code').val('');
+				$("#purchase_supplier_id").select2().select2("val", null);
+				$("#purchase_supplier_id").attr('disabled',false);
+				$("#purchase_pointsale_id").select2().select2("val", null);
+				$("#purchase_pointsale_id").attr('disabled',false);
+				$("#purchase_warehouse_id").select2().select2("val", null);
+				$("#purchase_warehouse_id").attr('disabled',false);
+				$("#reset_pre_purchases").attr('disabled',true);
+				$('#destiny').bootstrapSwitch('disabled',false);
+				$('#purchase_is_in_dollars').bootstrapSwitch('disabled', false);
+				$('#purchase_is_in_dollars').bootstrapSwitch('state', false);
+				calculateTotals();
 			}
-		}
+		});
+	}
+
+	function addPurchase() {
+		$('#purchase_form').submit();
+	}
 
-		function deletePrePurchases() {
+	function generatePurchaseCode() {
+		if($('#purchase_pointsale_id').val()) {
 			$.ajax({
 				type: "get",
-				url:  '/delete_pre_purchases',
-				dataType: 'json',
-				success: function(xhr, status, error){
-					$('#products_table').dataTable().fnClearTable();
-					$('#purchase_purchase_code').val('');
-					$("#purchase_supplier_id").select2().select2("val", null);
-					$("#purchase_supplier_id").attr('disabled',false);
-					$("#purchase_pointsale_id").select2().select2("val", null);
-					$("#purchase_pointsale_id").attr('disabled',false);
-					$("#purchase_warehouse_id").select2().select2("val", null);
-					$("#purchase_warehouse_id").attr('disabled',false);
-					$("#reset_pre_purchases").attr('disabled',true);
-					$('#destiny').bootstrapSwitch('disabled',false);
-					$('#purchase_is_in_dollars').bootstrapSwitch('disabled', false);
-					$('#purchase_is_in_dollars').bootstrapSwitch('state', false);
-					calculateTotals();
-				}
+				url: '/get_max_purchaseid_by_pointsale/' + $('#purchase_pointsale_id').val(),
+				dataType: 'text',
+				success: function(data) {
+					$('#purchase_purchase_code').val(data);
+				},
+			});
+		} else if($('#purchase_warehouse_id').val()) {
+			$.ajax({
+				type: "get",
+				url: '/get_max_purchaseid_by_warehouse/' + $('#purchase_warehouse_id').val(),
+				dataType: 'text',
+				success: function(data) {
+					$('#purchase_purchase_code').val(data);
+				},
 			});
 		}
+	}
 
-		function addPurchase() {
-			$('#purchase_form').submit();
-		}
+	function findProductByBarcode(barcode) {
+		var supplier = $('#purchase_supplier_id').val();
+		var pointsale = $('#purchase_pointsale_id').val();
+		var warehouse = $('#purchase_warehouse_id').val();
 
-		function generatePurchaseCode() {
-			if($('#purchase_pointsale_id').val()) {
-				$.ajax({
-					type: "get",
-					url:  '/get_max_purchaseid_by_pointsale/' + $('#purchase_pointsale_id').val(),
-					dataType: 'text',
-					success: function(data) {
-						$('#purchase_purchase_code').val(data);
-					},
-				});
-			} else if($('#purchase_warehouse_id').val()) {
-				$.ajax({
-					type: "get",
-					url:  '/get_max_purchaseid_by_warehouse/' + $('#purchase_warehouse_id').val(),
-					dataType: 'text',
-					success: function(data) {
-						$('#purchase_purchase_code').val(data);
-					},
-				});
-			}
+		if (pointsale) {
+			url = '/add_pre_purchase_by_barcode_pointsale/' + barcode + "/" + supplier + "/" + pointsale;
+		} else {
+			url = '/add_pre_purchase_by_barcode_warehouse/' + barcode + "/" + supplier + "/" + warehouse;
 		}
-
-		function findProductByBarcode(barcode) {
-			var supplier = $('#purchase_supplier_id').val();
-			var pointsale = $('#purchase_pointsale_id').val();
-			var warehouse = $('#purchase_warehouse_id').val();
-
-			if (pointsale) {
-				url = '/add_pre_purchase_by_barcode_pointsale/' + barcode + "/" + supplier + "/" + pointsale;
-			} else {
-				url = '/add_pre_purchase_by_barcode_warehouse/' + barcode + "/" + supplier + "/" + warehouse;
-			}
-			if((supplier && pointsale) || (supplier && warehouse)) {
-				$.ajax({
-					type: "get",
-					url:  url,
-					dataType: 'script',
-					success: function(data) {
-						calculateTotals();
-					},
-				});
-			} else {
-				toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
-			}
+		if((supplier && pointsale) || (supplier && warehouse)) {
+			$.ajax({
+				type: "get",
+				url: url,
+				dataType: 'script',
+				success: function(data) {
+					calculateTotals();
+				},
+			});
+		} else {
+			toastr["error"]("Se debe seleccionar proveedor y destino de la compra.");
 		}
-
-		function enumeratePrePurchases() {
-			if($('#reset_pre_purchases').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 enumeratePrePurchases() {
+		if($('#reset_pre_purchases').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 setDestiny(state) {
-			// true es almacen| false es punto de venta
-			$('#purchase_purchase_code').val('');
-			if (state) {
-				$('#warehouse_div').removeClass('hidden');
-				$("#purchase_warehouse_id").select2();
-				$('#pointsale_div').addClass('hidden');
-				<% if current_user.usertype == 'A' %>
-					$('#purchase_pointsale_id').select2('val', null);
-				<% end %>
-			} else {
-				$('#pointsale_div').removeClass('hidden');
-				$("#purchase_pointsale_id").select2();
-				$('#warehouse_div').addClass('hidden');
-				<% if current_user.usertype == 'A' %>
-					$('#purchase_warehouse_id').select2('val', null);
-				<% end %>
-			}
+	}
+
+	function setDestiny(state) {
+		// true es almacen| false es punto de venta
+		$('#purchase_purchase_code').val('');
+		if (state) {
+			$('#warehouse_div').removeClass('hidden');
+			$("#purchase_warehouse_id").select2();
+			$('#pointsale_div').addClass('hidden');
+			<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+				$('#purchase_pointsale_id').select2('val', null);
+			<% end %>
+		} else {
+			$('#pointsale_div').removeClass('hidden');
+			$("#purchase_pointsale_id").select2();
+			$('#warehouse_div').addClass('hidden');
+			<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
+				$('#purchase_warehouse_id').select2('val', null);
+			<% end %>
 		}
-
-		function showExchangeField(state) {
-			// true es dolares | false es pesos
-			if (state) {
-				$('#exchange_div').removeClass('hidden');
-				$('#amount_div div span:last-child').html('USD');
-				$('#tax_div div span:last-child').html('USD');
-				$('#total_div div span:last-child').html('USD');
-				$("#total_in_mxn_div").removeClass('hidden');
-			} else {
-				$('#exchange_div').addClass('hidden');
-				$('#purchase_exchange').val('');
-				$('#amount_div div span:last-child').html('MXN');
-				$('#tax_div div span:last-child').html('MXN');
-				$('#total_div div span:last-child').html('MXN');
-				$("#total_in_mxn_div").addClass('hidden');
-			}
+	}
+
+	function showExchangeField(state) {
+		// true es dolares | false es pesos
+		if (state) {
+			$('#exchange_div').removeClass('hidden');
+			$('#amount_div div span:last-child').html('USD');
+			$('#tax_div div span:last-child').html('USD');
+			$('#total_div div span:last-child').html('USD');
+			$("#total_in_mxn_div").removeClass('hidden');
+		} else {
+			$('#exchange_div').addClass('hidden');
+			$('#purchase_exchange').val('');
+			$('#amount_div div span:last-child').html('MXN');
+			$('#tax_div div span:last-child').html('MXN');
+			$('#total_div div span:last-child').html('MXN');
+			$("#total_in_mxn_div").addClass('hidden');
 		}
+	}
 </script>
-
-
-

+ 15 - 15
app/views/purchases/_purchase.html.erb

@@ -2,31 +2,31 @@
 	<td> # </td>
 	<td><%= purchase.purchase_code %></td>
 	<td><%= purchase.user.first_name%></td>
-  <% if current_user.usertype == "A" %>
+  <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
     <td><%= purchase.pointsale.present? ? purchase.pointsale.name : '' %></td>
     <td><%= purchase.warehouse.present? ? purchase.warehouse.name : '' %></td>
   <% end %>
 	<td><%= purchase.supplier.nick_name %></td>
   <td><%= number_to_currency(purchase.total, precision: 2) %> <%= purchase.is_in_dollars ? 'USD' : 'MXN' %></td>
 
-	<td> <%= l(purchase.purchase_date, :format => '%d/%B/%Y')  %> </td>
-    <td class="text-center">
-      <% case purchase.status %>
-          <% when "paid"%>
-            <span class="label label-sm label-success"> <i class="fa fa-check"></i> Pagada </span>
-          <% when "cancelled"%>
-             <span class="label label-sm label-danger"> <i class="fa fa-close"></i> Cancelada </span>
-          <% when "parcial"%>
-            <span class="label label-sm label-warning"> <i class="fa fa-clock-o"></i> Abonada </span>
-          <% when "notpaid"%>
-            <span class="label label-sm label-default"> <i class="fa fa-clock-o"></i> Pendiente de pago </span>
-      <% end %>
-    </td>
+	<td> <%= l(purchase.purchase_date, format: '%d/%B/%Y') %> </td>
+  <td class="text-center">
+    <% case purchase.status %>
+    <% when "paid"%>
+      <span class="label label-sm label-success"> <i class="fa fa-check"></i> Pagada </span>
+    <% when "cancelled"%>
+      <span class="label label-sm label-danger"> <i class="fa fa-close"></i> Cancelada </span>
+    <% when "parcial"%>
+      <span class="label label-sm label-warning"> <i class="fa fa-clock-o"></i> Abonada </span>
+    <% when "notpaid"%>
+      <span class="label label-sm label-default"> <i class="fa fa-clock-o"></i> Pendiente de pago </span>
+    <% end %>
+  </td>
 	<td class="text-center">
       	<%= link_to purchase, {:class=>"btn btn-icon-only default", :title=>"Ver compra"} do %> <i class="fa fa-search"></i> <% end %>
       	<% daysToCancel = @pos_config.days_cancel_purchase %>
       	<% if (can? :manage, Purchase) && (purchase.purchase_date + daysToCancel.days >= Date.today) && !purchase.cancelled? %>
-			<%= link_to purchase_path(purchase), method: :delete, :class => "btn btn-icon-only btn-danger", :title=>"Cancelar compra", data: { confirm: '¿Está seguro de cancelar la compra?'}   do %> <i class="fa fa-times"></i> <% end %>
+			<%= link_to purchase_path(purchase), method: :delete, :class => "btn btn-icon-only btn-danger", :title=>"Cancelar compra", data: { confirm: '¿Está seguro de cancelar la compra?' } do %> <i class="fa fa-times"></i> <% end %>
 		<% end %>
 	</td>
 </tr>

+ 48 - 62
app/views/purchases/index.html.erb

@@ -44,44 +44,43 @@
 									</div>
 									<div class="actions">
 										<% if can? :create, Purchase %>
-										<%= link_to new_purchase_path, {:class=>"btn bold green pull-right filtros"} do %> Nueva Compra <i class="fa fa-plus"></i>
-										<% end %>
+											<%= link_to new_purchase_path, {:class=>"btn bold green pull-right filtros"} do %> Nueva Compra <i class="fa fa-plus"></i><% end %>
 										<% end %>
 									</div>
 								</div>
 								<div class="portlet-body">
-				                    <div class="form-horizontal" style="margin-bottom:35px">
-				                      <div class="row">
-				                        <div class="col-md-11">
-                          					<%= hidden_field_tag 'title_for_print' %>
-				                          <div class="form-group">
-				                            <%= label_tag :begin_date, "Fecha", {:class=>"col-md-1 control-label"} do %> Desde
-				                            <% end %>
-				                            <div class="col-sm-2" style="padding-left:0px;padding-right:0px;">
-				                                <div class='input-group date' id='begin_date'>
-				                                    <input id="start" type='text' class="form-control"/>
-				                                    <span class="input-group-addon">
-				                                        <span class="glyphicon glyphicon-calendar"></span>
-				                                    </span>
-				                                </div>
-				                            </div>
-				                            <%= label_tag :end_date, "Fecha", {:class=>"col-md-1 control-label"} do %> Hasta
-				                            <% end %>
-				                            <div class="col-sm-2" style="padding-left:0px;padding-right:0px;">
-				                                <div class='input-group date' id='end_date'>
-				                                    <input id="end" type='text' class="form-control"/>
-				                                    <span class="input-group-addon">
-				                                        <span class="glyphicon glyphicon-calendar"></span>
-				                                    </span>
-				                                </div>
-				                            </div>
-				                            <button class="btn btn-icon-only blue" style="margin-left:25px" onclick="purchasesByDate()">
-				                              <i class="fa fa-search"></i>
-				                            </button>
-				                          </div>
-				                        </div>
-				                      </div>
-				                    </div>
+                  <div class="form-horizontal" style="margin-bottom:35px">
+                    <div class="row">
+                      <div class="col-md-11">
+              					<%= hidden_field_tag 'title_for_print' %>
+                        <div class="form-group">
+                          <%= label_tag :begin_date, "Fecha", { class: "col-md-1 control-label" } do %> Desde
+                          <% end %>
+                          <div class="col-sm-2" style="padding-left:0px;padding-right:0px;">
+                            <div class='input-group date' id='begin_date'>
+                              <input id="start" type='text' class="form-control"/>
+                              <span class="input-group-addon">
+                                <span class="glyphicon glyphicon-calendar"></span>
+                              </span>
+                            </div>
+                          </div>
+                          <%= label_tag :end_date, "Fecha", { class: "col-md-1 control-label" } do %> Hasta
+                          <% end %>
+                          <div class="col-sm-2" style="padding-left:0px;padding-right:0px;">
+                            <div class='input-group date' id='end_date'>
+                              <input id="end" type='text' class="form-control"/>
+                              <span class="input-group-addon">
+                                <span class="glyphicon glyphicon-calendar"></span>
+                              </span>
+                            </div>
+                          </div>
+                          <button class="btn btn-icon-only blue" style="margin-left:25px" onclick="purchasesByDate()">
+                            <i class="fa fa-search"></i>
+                          </button>
+                        </div>
+                      </div>
+                    </div>
+                  </div>
 
 									<input type='hidden' name='filter' id='filter' value='<%= @filter %>' >
 									<input type='hidden' name='current_page' id='current_page' value='<%= @current_page %>' >
@@ -91,7 +90,7 @@
 												<th>#</th>
 												<th>Folio</th>
 												<th>Usuario</th>
-												<% if current_user.usertype == "A" %>
+												<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 													<th>Pto. de venta</th>
 													<th>Almacén</th>
 												<% end %>
@@ -106,36 +105,23 @@
 										</thead>
 										<tbody>
 											<% @purchases.each_with_index do |purchase, key| %>
-												<tr <% if purchase.status == "cancelled" %>class="danger"<% end %>>
+												<tr <% if purchase.cancelled? %>class="danger"<% end %>>
 													<td><%= key + 1 %></td>
 													<td><%= purchase.purchase_code %></td>
-													<td><%= purchase.user.first_name%></td>
-													<% if current_user.usertype == "A" %>
+													<td><%= purchase.user.first_name %></td>
+													<% if current_user.usertype == "A" || current_user.usertype == "SS" %>
 														<td><%= purchase.pointsale.present? ? purchase.pointsale.name : '' %></td>
 														<td><%= purchase.warehouse.present? ? purchase.warehouse.name : '' %></td>
 													<% end %>
 													<td><%= purchase.supplier.nick_name %></td>
 													<td><%= number_to_currency(purchase.total, precision: 2) %> <%= purchase.is_in_dollars ? 'USD' : 'MXN' %></td>
-
-													<td><%= l(purchase.purchase_date, :format => '%d/%B/%Y') %>
-													</td>
-							                        <td class="text-center">
-							                          <% case purchase.status %>
-								                          <% when "paid"%>
-								                            <span class="label label-sm label-success"> <i class="fa fa-check"></i> Pagada </span>
-								                          <% when "cancelled"%>
-								                             <span class="label label-sm label-danger"> <i class="fa fa-close"></i> Cancelada </span>
-								                          <% when "parcial"%>
-								                            <span class="label label-sm label-warning"> <i class="fa fa-clock-o"></i> Abonada </span>
-								                          <% when "notpaid"%>
-								                            <span class="label label-sm label-default"> <i class="fa fa-clock-o"></i> Pte. de pago</span>
-							                          <% end %>
-							                        </td>
+													<td><%= l(purchase.purchase_date, :format => '%d/%B/%Y') %></td>
+	                        <td class="text-center"><%= purchase_status(purchase) %></td>
 													<td class="text-center">
-							                          	<%= link_to purchase, {:class=>"btn btn-icon-only default filtros", :title=>"Ver compra"} do %> <i class="fa fa-search"></i> <% end %>
-							                          	<% daysToCancel = @pos_config.days_cancel_purchase %>
-							                          	<% if (can? :manage, Purchase) && (purchase.purchase_date + daysToCancel.days >= Date.today) && !purchase.cancelled? %>
-															<%= link_to purchase_path(purchase), method: :delete, :class => "btn btn-icon-only btn-danger", :title=>"Cancelar compra", data: { confirm: '¿Está seguro de cancelar la compra?'}   do %> <i class="fa fa-times"></i> <% end %>
+                          	<%= link_to purchase, {:class=>"btn btn-icon-only default filtros", :title=>"Ver compra"} do %> <i class="fa fa-search"></i> <% end %>
+                          	<% daysToCancel = @pos_config.days_cancel_purchase %>
+                          	<% if (can? :manage, Purchase) && (purchase.purchase_date + daysToCancel.days >= Date.today) && !purchase.cancelled? %>
+															<%= link_to purchase_path(purchase), method: :delete, :class => "btn btn-icon-only btn-danger", :title=>"Cancelar compra", data: { confirm: '¿Está seguro de cancelar la compra?' } do %> <i class="fa fa-times"></i> <% end %>
 														<% end %>
 													</td>
 												</tr>
@@ -183,17 +169,17 @@
 	var start = moment($("#begin_date").data("date"), "DD-MM-YYYY").format('YYYY-MM-DD HH:mm:ss');
     var end = moment($("#end_date").data("date"), "DD-MM-YYYY").format('YYYY-MM-DD HH:mm:ss');
     App.blockUI({
-         target: $("#purchases_table"),
-         animate: true
+      target: $("#purchases_table"),
+      animate: true
     });
     $.ajax({
       type: "get",
       url:  '/find_purchases_by_date/' + start + '/' + end,
       dataType: 'script',
       success: function(data) {
-          window.setTimeout(function() {
-            App.unblockUI($("#purchases_table"));
-          }, 100);
+        window.setTimeout(function() {
+          App.unblockUI($("#purchases_table"));
+        }, 100);
       }
     });
   }

+ 11 - 11
app/views/sales/_sale_reserved.html.erb

@@ -1,7 +1,7 @@
 <tr class=<%= (sale.cancelled? ? 'danger' : '') %>>
   <td><%= sale.id %></td>
   <td><%= sale.sale_code %> </td>
-  <% if current_user.usertype == 'A' %>
+  <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
     <td> <%= sale.get_pointsale.name %> </td>
   <% end %>
   <td> <%= sale.customer.nick_name %> </td>
@@ -10,15 +10,15 @@
   <td> <%= l(sale.expiration_date, :format => '%d/%B/%Y') %> </td>
   <td> <%= sale.sales_details.sum(:quantity) %> </td>
   <td>
-      <% if sale.reserve_is_expired? && !sale.paid? && !sale.cancelled? %>
-        <span class="label label-warning"> VENCIDO </span>
-      <% elsif sale.cancelled? %>
-        <span class="label label-danger"> CANCELADO </span>
-      <% elsif sale.parcial? %>
-        <span class="label label-success"> VIGENTE </span>
-      <% elsif sale.paid? %>
-        <span class="label label-success"> PAGADO </span>
-      <% end %>
+    <% if sale.reserve_is_expired? && !sale.paid? && !sale.cancelled? %>
+      <span class="label label-warning"> VENCIDO </span>
+    <% elsif sale.cancelled? %>
+      <span class="label label-danger"> CANCELADO </span>
+    <% elsif sale.parcial? %>
+      <span class="label label-success"> VIGENTE </span>
+    <% elsif sale.paid? %>
+      <span class="label label-success"> PAGADO </span>
+    <% end %>
   </td>
   <td><%= number_to_currency(sale.total, precision: 2) %></td>
   <td><%= number_to_currency(sale.reserve_debt, precision: 2) %></td>
@@ -33,7 +33,7 @@
     <% end %>
     <!-- regresar productos a inventario cuando vencio el apartado -->
     <% if sale.reserve_is_expired? && !sale.cancelled_by_expiration? && !sale.paid? && !sale.cancelled? %>
-      <%= link_to sale_return_expired_path(sale), :class=>"btn btn-icon-only btn-info", :title=>"Regresar producto(s) a inventario", data: { confirm: '¿Esta seguro que desea reingresar los productos a inventario?', method: 'post'}  do %>
+      <%= link_to sale_return_expired_path(sale), :class=>"btn btn-icon-only btn-info", :title=>"Regresar producto(s) a inventario", data: { confirm: '¿Está seguro que desea reingresar los productos a inventario?', method: 'post' } do %>
           <i class="fa fa-reply"></i>
       <% end %>
     <% end %>

+ 2 - 2
app/views/sales/index.html.erb

@@ -87,7 +87,7 @@
                       <tr>
                         <th>#</th>
                         <th>Folio</th>
-                        <% if current_user.usertype == 'A' %>
+                        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                           <th>Pto. de venta</th>
                         <% end %>
                         <th>Cliente</th>
@@ -105,7 +105,7 @@
                       <tr class=<%= (sale.cancelled? ? 'danger' : '') %>>
                         <td><%= sale.id %></td>
                         <td><%= sale.sale_code %> </td>
-                        <% if current_user.usertype == 'A' %>
+                        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                           <td> <%= sale.get_pointsale.name %> </td>
                         <% end %>
                         <td><%= sale.customer.nick_name %> </td>

+ 11 - 11
app/views/sales/sales_reserved.html.erb

@@ -81,7 +81,7 @@
                       <tr>
                         <th>#</th>
                         <th>Folio</th>
-                        <% if current_user.usertype == 'A' %>
+                        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                           <th>Punto de venta</th>
                         <% end %>
                         <th>Cliente</th>
@@ -100,7 +100,7 @@
                       <tr class=<%= (sale.cancelled? ? 'danger' : '') %>>
                         <td><%= sale.id %></td>
                         <td><%= sale.sale_code %> </td>
-                        <% if current_user.usertype == 'A' %>
+                        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                           <td> <%= sale.get_pointsale.name %> </td>
                         <% end %>
                         <td> <%= sale.customer.nick_name %> </td>
@@ -109,15 +109,15 @@
                         <td> <%= l(sale.expiration_date, :format => '%d/%B/%Y') %> </td>
                         <td> <%= sale.sales_details.sum(:quantity) %> </td>
                         <td>
-                            <% if sale.reserve_is_expired? && !sale.paid? && !sale.cancelled? %>
-                              <span class="label label-warning"> VENCIDO </span>
-                            <% elsif sale.cancelled? %>
-                              <span class="label label-danger"> CANCELADO </span>
-                            <% elsif sale.parcial? %>
-                              <span class="label label-success"> VIGENTE </span>
-                            <% elsif sale.paid? %>
-                              <span class="label label-success"> PAGADO </span>
-                            <% end %>
+                          <% if sale.reserve_is_expired? && !sale.paid? && !sale.cancelled? %>
+                            <span class="label label-warning"> VENCIDO </span>
+                          <% elsif sale.cancelled? %>
+                            <span class="label label-danger"> CANCELADO </span>
+                          <% elsif sale.parcial? %>
+                            <span class="label label-success"> VIGENTE </span>
+                          <% elsif sale.paid? %>
+                            <span class="label label-success"> PAGADO </span>
+                          <% end %>
                         </td>
                         <td><%= number_to_currency(sale.total, precision: 2) %></td>
                         <td><%= number_to_currency(sale.reserve_debt, precision: 2) %></td>

+ 27 - 27
app/views/transfers/_form.html.erb

@@ -19,17 +19,17 @@
         <!-- fecha -->
         <div class="form-group">
           <%= f.label :transfer_date, "Fecha", {:class=>"col-md-3 control-label"} do %> Fecha
-          <span class="required">*</span>
+            <span class="required">*</span>
           <% end %>
-            <%= f.hidden_field :transfer_date, {:value=>Date.today} %>
-              <div class="col-sm-6" style="padding-left:0px;padding-right:0px;">
-                  <div class='input-group date' id='datetimepicker1'>
-                      <input type='text' class="form-control" disabled/>
-                      <span class="input-group-addon">
-                          <span class="glyphicon glyphicon-calendar"></span>
-                      </span>
-                  </div>
-              </div>
+          <%= f.hidden_field :transfer_date, { value: Date.today } %>
+          <div class="col-sm-6" style="padding-left:0px;padding-right:0px;">
+            <div class='input-group date' id='datetimepicker1'>
+              <input type='text' class="form-control" disabled/>
+              <span class="input-group-addon">
+                <span class="glyphicon glyphicon-calendar"></span>
+              </span>
+            </div>
+          </div>
         </div>
         <!-- origen -->
         <div class="form-group">
@@ -144,8 +144,8 @@
       url: "/find_from_stock_by_pointsale?pointsale_id=ID&query=%QUERY",
       wildcard: '%QUERY',
       replace: function(url, uriEncodedQuery) {
-          origin = $('#origin_id').val();
-          return url.replace('ID', origin).replace('%QUERY', uriEncodedQuery)
+        origin = $('#origin_id').val();
+        return url.replace('ID', origin).replace('%QUERY', uriEncodedQuery)
       }
     }
   });
@@ -240,12 +240,12 @@
   function deletePreTransfers() {
     $.ajax({
       type: "get",
-      url:  '/delete_pre_transfers',
+      url: '/delete_pre_transfers',
       dataType: 'json',
       success: function(xhr, status, error){
         $('#products_table').dataTable().fnClearTable();
         $("#transfer_destiny_id").select2().select2("val", null);
-        <% if current_user.usertype == 'A' %>
+        <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
           $("#transfer_origin_id").attr('disabled', false);
           $("#transfer_origin_id").select2().select2("val", null);
         <% end %>
@@ -262,19 +262,19 @@
         var idText = input.closest('tr').attr('id');
         var preTransferId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
         $.ajax({
-            type: "PUT",
-            url: "/pre_transfers/" + preTransferId,
-            dataType: "json",
-            data: {pre_transfer: {quantity: input.val()}},
-            success: function(xhr, status, error) {
-              $("#save_transfer").attr("disabled", false);
-            },
-            statusCode: {
-              422: function() {
-                $("#save_transfer").attr("disabled", true);
-                toastr["error"]("Error, El stock es insuficiente.");
-              }
+          type: "PUT",
+          url: "/pre_transfers/" + preTransferId,
+          dataType: "json",
+          data: {pre_transfer: {quantity: input.val()}},
+          success: function(xhr, status, error) {
+            $("#save_transfer").attr("disabled", false);
+          },
+          statusCode: {
+            422: function() {
+              $("#save_transfer").attr("disabled", true);
+              toastr["error"]("Error, El stock es insuficiente.");
             }
+          }
         });
       }, 700);
     } else {
@@ -289,7 +289,7 @@
     if((origin && destiny) && (origin != destiny)) {
       $.ajax({
         type: "get",
-        url:  '/add_pre_transfer_by_barcode/' + barcode + "/" + origin + "/" + destiny,
+        url: '/add_pre_transfer_by_barcode/' + barcode + "/" + origin + "/" + destiny,
         dataType: 'script',
         success: function(data) {
         },

+ 1 - 1
app/views/transfers/index.html.erb

@@ -48,7 +48,7 @@
                   </div>
                 </div>
                 <div class="portlet-body">
-                    <% if current_user.usertype == "A" %>
+                    <% if current_user.usertype == "A" || current_user.usertype == "SS" %>
                       <%= render partial: 'transfers/index_for_admin' %>
                     <% elsif current_user.usertype == "C" %>
                       <%= render partial: 'transfers/index_for_cashier' %>

+ 1 - 1
app/views/transfers/new.html.erb

@@ -17,7 +17,7 @@
 		<!-- BEGIN PAGE CONTENT BODY -->
 		<div class="page-content">
 			<div class="container-fluid">
-                <%= link_to transfers_path(:filter => @filter, :current_page => @current_page), {:class=>"btn blue-hoki pull-right margin-bottom-10"} do %> <i class="fa fa-angle-left "></i> Regresar
+        <%= link_to transfers_path(:filter => @filter, :current_page => @current_page), {:class=>"btn blue-hoki pull-right margin-bottom-10"} do %> <i class="fa fa-angle-left "></i> Regresar
 				<% end %>
 				<!-- BEGIN PAGE BREADCRUMBS -->
 				<ul class="page-breadcrumb breadcrumb">