Explorar o código

new commissions based on incomings, not sales. and bugfix in dashboard charts

Jose Miguel Ledon Nieblas %!s(int64=8) %!d(string=hai) anos
pai
achega
76421a4015

+ 20 - 8
app/controllers/commissions_controller.rb

@@ -28,7 +28,8 @@ class CommissionsController < ApplicationController
     @final_date = params[:final_date]
     commission_total = 0
     @sellers.each do |seller|
-      commission_total += seller.get_sales_by_period(@initial_date, @final_date, 'commission').sum(:total)
+      total = seller.get_sales_by_period(@initial_date, @final_date, 'commission').sum(:total)
+      commission_total += total
     end
     @commission = Commission.new
     @commission.sellerscommissions.new
@@ -99,13 +100,24 @@ class CommissionsController < ApplicationController
     initial_date = DateTime.parse(params[:initial_date])
     final_date = DateTime.parse(params[:final_date])
 
-    sales = Pointsale.find(params[:pointsale_id]).sales.activas.where(date_sale: initial_date..final_date).pluck(:id)
-    commissions_paid = SalesSellercommission.where('sale_id IN (?)', sales).pluck(:sale_id)
-
-    to_pay = sales - commissions_paid
-
-    sellers = Sale.where('sales.id IN (?)', to_pay).joins(:seller).distinct(:seller_id).select(:seller_id, :name)
+    # exists_any = Commission.where(initial_date: initial_date..final_date, final_date: initial_date..final_date, pointsale: params[:pointsale_id]).any?
+    # exists_any = Commission.where("pointsale_id = ? AND ((initial_date BETWEEN ? AND ?) OR (final_date BETWEEN ? AND ?))", params[:pointsale_id], initial_date, final_date, initial_date, final_date).any?
+
+    # unless (exists_any)
+    ids_w_moves_in_period = Pointsale.find(params[:pointsale_id]).cash_registers_moves.where(move_type: '1', created_at: initial_date..final_date).pluck(:sale_id)
+    news_sales_in_period = Pointsale.find(params[:pointsale_id]).sales.activas.where(date_sale: initial_date..final_date).pluck(:id)
+    all_ids = (ids_w_moves_in_period + news_sales_in_period).uniq
+    if all_ids.present?
+      commissions_paid = SalesSellercommission.includes(:sale).where('sale_id IN (?) and sales.saletype = ?', all_ids, 1).pluck(:sale_id)
+      to_pay = all_ids - commissions_paid
+      sellers = Sale.where('sales.id IN (?)', to_pay).joins(:seller).distinct(:seller_id).select(:seller_id, :name)
+    else
+      sellers = Array.new
+    end
     render json: sellers
+    # else
+    #   render json: 'no funka'
+    # end
   end
 
   private
@@ -122,6 +134,6 @@ class CommissionsController < ApplicationController
 
   # Never trust parameters from the scary internet, only allow the white list through.
   def commission_params
-    params.require(:commission).permit(:initial_date, :final_date, :commission_total, :pointsale_id, :user_id, sellerscommissions_attributes: [:seller_id, :num_sales, :num_products, :sales_total, :commission_calculated, :commission_paid, :commission_percent])
+    params.require(:commission).permit(:initial_date, :final_date, :commission_total, :pointsale_id, :user_id, sellerscommissions_attributes: [:total_sold_cash, :total_sold_credits_apartments, :income_by_cash, :income_by_reserved_and_credits, :seller_id, :num_sales, :sales_total, :commission_calculated, :commission_paid, :commission_percent])
   end
 end

+ 1 - 1
app/controllers/sales_controller.rb

@@ -414,7 +414,7 @@ class SalesController < ApplicationController
         @sales = Sale.activas.where(date_sale: start_date..end_date).includes(:sales_details).order("id DESC")
       end
 
-      @sales_total = CashRegistersMove.activos.where("sale_id IN (?)", @sales.pluck(:id)).sum(:quantity)
+      @sales_total = CashRegistersMove.activos.where("sale_id IN (?)", @sales.pluck(:id)).where(created_at: start_date..end_date).sum(:quantity)
       @sales_quantity = @sales.size
       @prods_total = SalesDetail.where("sale_id IN (?)", @sales.pluck(:id)).sum(:quantity).round
       @cash_sales_total = CashRegistersMove.activos.where("sale_id IN (?)", @sales.where(saletype: 1).pluck(:id)).sum(:quantity)

+ 3 - 1
app/models/cash_registers_move.rb

@@ -92,7 +92,9 @@ class CashRegistersMove < ActiveRecord::Base
     Pointsale.activos.each do |pointsale|
       obj = {}
       obj[:pointsale] = pointsale.name.tr(" ", "\n")
-      obj[:total] = pointsale.open_cash_registers.where(created_at: beg_period..end_period).joins(:cash_registers_moves).where("cash_registers_moves.move_type = '1' and cash_registers_moves.status = '1'").sum(:quantity)
+      # obj[:total] = pointsale.cash_registers_moves.where(created_at: beg_period..end_period, move_type: '1', status: '1').sum(:quantity)
+      sales = pointsale.sales.activas.where(date_sale: beg_period..end_period)
+      obj[:total] = CashRegistersMove.activos.where("sale_id IN (?)", sales.pluck(:id)).where(created_at: beg_period..end_period).sum(:quantity)
       all_incomings << obj
     end
     all_incomings.to_json

+ 1 - 0
app/models/pointsale.rb

@@ -11,6 +11,7 @@ class Pointsale < ActiveRecord::Base
   has_many :credit_payments
   has_many :cash_registers
   has_many :open_cash_registers, through: :cash_registers
+  has_many :cash_registers_moves, through: :open_cash_registers
   has_many :cash_outs, through: :open_cash_registers
   has_many :sales, through: :open_cash_registers
   has_many :expenses, through: :open_cash_registers

+ 79 - 49
app/models/seller.rb

@@ -1,52 +1,82 @@
 class Seller < ActiveRecord::Base
-	belongs_to :pointsale
-	has_many :sales
-	has_many :sellerscommissions
-
-  	##--- Llevar registro de Actividad del usuario
-	audited
-
-	enum status: [:erased, :active, :inactive]
-
-	attr_accessor :skip_pointsale
-
-		##--- Validaciones previas de guardar
-	validates :pointsale_id, presence: { message: "Debe seleccionar punto de venta para el vendedor." }, :on => [:create, :update], unless: :skip_pointsale
-	validates :name, presence: { message: "Debe indicar nombre para el vendedor." }, :on => [:create, :update]
-	validates :last_name, presence: { message: "Debe indicar apellido para el vendedor." }, :on => [:create, :update]
-
-	scope :vigentes, -> { where( "status != 0") }
-
-	##--- Funciones personalizadas
-	def full_name
-		"#{self.name} #{last_name}"
-	end
-
-	def self.get_ranking(period, pointsale)
-		all_serllers = Array.new
-		if period == 'week'
-	      	beg_period = Date.current.beginning_of_week
-	      	end_period = Date.current.end_of_week
-		elsif period == 'month'
-		    beg_period = Date.current.beginning_of_month
-		    end_period = Date.current.end_of_month
-		end
-
-		quantities_top_products = pointsale.sellers.joins(:sales).where("sales.date_sale between ? and ? and sales.status > 1", beg_period, end_period).group('sellers.name').order('sum_sales_total desc').limit(10).sum('sales.total')
-		return quantities_top_products
-	end
-
-	def get_sales_by_period(initial_date, final_date, type)
-		if type == 'commission'
-			sales_ids = Sale.where(:date_sale => initial_date..final_date, :seller_id => self.id).activas.pluck(:id)
-          	commissions_paid = SalesSellercommission.where("sale_id IN (?)", sales_ids).pluck(:sale_id)
-          	news_to_pay = sales_ids - commissions_paid
-          	sales_by_period = Sale.where("sales.id IN (?)", news_to_pay)
-		else
-			sales_by_period = Sale.where(:date_sale => initial_date..final_date, :seller_id => self.id).activas
-
-		end
-		return sales_by_period
-	end
+  belongs_to :pointsale
+  has_many :sales
+  has_many :sellerscommissions
 
+  ##--- Llevar registro de Actividad del usuario
+  audited
+
+  enum status: [:erased, :active, :inactive]
+
+  attr_accessor :skip_pointsale
+
+  ##--- Validaciones previas de guardar
+  validates :pointsale_id, presence: { message: "Debe seleccionar punto de venta para el vendedor." }, on: [:create, :update], unless: :skip_pointsale
+  validates :name, presence: { message: "Debe indicar nombre para el vendedor." }, on: [:create, :update]
+  validates :last_name, presence: { message: "Debe indicar apellido para el vendedor." }, on: [:create, :update]
+
+  scope :vigentes, -> { where("status != 0") }
+
+  ##--- Funciones personalizadas
+  def full_name
+    "#{name} #{last_name}"
+  end
+
+  def self.get_ranking(period, pointsale)
+    all_serllers = Array.new
+    if period == 'week'
+      beg_period = Date.current.beginning_of_week
+      end_period = Date.current.end_of_week
+    elsif period == 'month'
+      beg_period = Date.current.beginning_of_month
+      end_period = Date.current.end_of_month
+    end
+    quantities_top_products = pointsale.sellers.joins(:sales).where("sales.date_sale between ? and ? and sales.status > 1", beg_period, end_period).group('sellers.name').order('sum_sales_total desc').limit(10).sum('sales.total')
+    quantities_top_products
+  end
+
+  def get_sales_by_period(initial_date, final_date, type)
+    if type == 'commission'
+      sales_ids = Sale.where(date_sale: initial_date..final_date, seller_id: id).activas.pluck(:id)
+      commissions_paid = SalesSellercommission.where("sale_id IN (?)", sales_ids).pluck(:sale_id)
+      news_to_pay = sales_ids - commissions_paid
+      sales_by_period = Sale.where("sales.id IN (?)", news_to_pay)
+    else
+      sales_by_period = Sale.where(date_sale: initial_date..final_date, seller_id: id).activas
+    end
+    sales_by_period
+  end
+
+  def get_data_for_commissions(initial_date, final_date)
+    income_by_reserved_and_credits = CashRegistersMove.joins(:sale).where(move_type: '1', created_at: initial_date..final_date).where("sales.seller_id = ? and sales.saletype != 1", id).sum(:quantity)
+    income_by_cash = CashRegistersMove.joins(:sale).where(move_type: '1', created_at: initial_date..final_date).where("sales.seller_id = ? and sales.saletype = 1", id).sum(:quantity)
+
+    sales_by_period = Sale.where(date_sale: initial_date..final_date, seller_id: id).activas
+    already_generated_sales_comm_ids = sales_by_period.present? ? SalesSellercommission.where('sale_id IN (?)', sales_by_period.pluck(:id)).pluck(:id) : Array.new
+    sales_ids = sales_by_period.pluck(:id) - already_generated_sales_comm_ids
+    total_sold_cash = Sale.where('id in (?)', sales_ids).where(saletype: '1').sum(:total)
+    total_sold_credits_apartments = Sale.where('id in (?)', sales_ids).where('saletype != 1').sum(:total)
+
+    obj = Hash.new
+    obj['total_sold_cash'] = total_sold_cash
+    obj['total_sold_credits_apartments'] = total_sold_credits_apartments
+    obj['sales_count'] = sales_ids.count
+    obj['income_by_reserved_and_credits'] = income_by_reserved_and_credits
+    obj['income_by_cash'] = income_by_cash
+    obj
+    # moves = CashRegistersMove.joins(:sale).where(move_type: '1', created_at: initial_date..final_date).where("sales.seller_id = ?", id)
+    # all_sales_ids = moves.pluck(:id)
+    # already_paid_ids = SalesSellercommission.includes(:sale).where('sale_id IN (?) and sales.saletype = ?', all_sales_ids, 1).pluck(:sale_id)
+    # sales_with_moves_to_pay = all_sales_ids - already_paid_ids
+    # received_money = moves.sum(:quantity)
+    # obj = Hash.new
+    # obj['moves'] = moves
+    # obj['sales_with_movs'] = Sale.where('id IN (?)', sales_with_moves_to_pay)
+    # obj
+
+    # sales_ids = Sale.where(date_sale: initial_date..final_date, seller_id: id).activas.pluck(:id)
+    # commissions_paid = SalesSellercommission.where("sale_id IN (?)", sales_ids).pluck(:sale_id)
+    # news_to_pay = sales_ids - commissions_paid
+    # sales_by_period = Sale.where("sales.id IN (?)", news_to_pay)
+  end
 end

+ 45 - 29
app/views/commissions/_form.html.erb

@@ -1,11 +1,8 @@
 <%= form_for(@commission, :html => {:class=>"form-horizontal"}) do |f| %>
 <div class="portlet-body form">
-
     <div class="form-body">
       <div class="row">
         <%= f.hidden_field :pointsale_id %>
-        <%= f.hidden_field :initial_date %>
-        <%= f.hidden_field :final_date %>
         <div class="form-group">
           <%= f.label :pointsale, "Punto de venta", {:class=>"col-md-2 control-label"} do %> Punto de venta <span class="required">*</span>
           <% end %>
@@ -26,6 +23,24 @@
           </div>
         </div>
 
+        <div class="form-group">
+          <%= f.label :initial_date, "Inicio", {:class=>"col-md-2 control-label"} do %>Inicio del periodo<span class="required">*</span>
+          <% end %>
+          <div class="col-md-3" style="padding-left: 0px;padding-right: 0px">
+            <%= text_field_tag :initial_date_display, l(@commission.initial_date, :format => '%d/%m/%Y'), class: "form-control", disabled: true %>
+            <%= f.hidden_field :initial_date %>
+          </div>
+        </div>
+
+        <div class="form-group">
+          <%= f.label :final_date, "Fin", {:class=>"col-md-2 control-label"} do %> Fin del periodo<span class="required">*</span>
+          <% end %>
+          <div class="col-md-3" style="padding-left: 0px;padding-right: 0px">
+            <%= text_field_tag :final_date_display, l(@commission.final_date, :format => '%d/%m/%Y'), class: "form-control", disabled: true %>
+            <%= f.hidden_field :final_date %>
+          </div>
+        </div>
+
         <div class="form-group">
           <%= f.label :commission_total, "Total", {:class=>"col-md-2 control-label"} do %> Total vendido<span class="required">*</span>
           <% end %>
@@ -38,47 +53,48 @@
       </div>
 
       <h4 class="form-section">Lista de comisiones a pagar</h4>
-      <h6>Nota: si el campo de Pago actual se deja en blanco, se le dará por valor el Pago recomendado.</h6>
                         <table class="table table-striped table-bordered table-hover tableadvanced" id="products_table">
                           <thead>
                               <tr>
-                                <th width="5%">#</th>
-                                <th width="10%">Vendedor</th>
-                                <th width="15%">Número de ventas</th>
-                                <th width="15%">Última venta</th>
-                                <th width="20%">Productos totales</th>
-                                <th width="20%">Monto total</th>
-                                <th width="15%">Pago recomendado</th>
-                                <th width="15%">A pagar</th>
+                                <th>Vendedor</th>
+                                <th>Ventas en <br>el periodo</th>
+                                <th>Total vendido <br>contado</th>
+                                <th>Total vendido <br>créditos <br>y apartados</th>
+                                <th>Total <br>vendido</th>
+                                <th>$ ingresado<br>contado</th>
+                                <th>$ ingresado<br>créditos <br>y apartados</th>
+                                <th>Total <br>ingresado</th>
+                                <th>Pago <br>recomendado</th>
+                                <th>A pagar</th>
                               </tr>
                           </thead>
 
                           <tbody id="sellers_table">
-                            <% @sellers.each_with_index do |seller, key| %>
+                            <% @sellers.each_with_index do |seller| %>
                               <tr>
-                                <% sales_by_period = seller.get_sales_by_period(@initial_date, @final_date, 'commission') %>
-                                <% commission_calculated = ((@pos_config.commission_percent / 100.0) *sales_by_period.sum(:total)).round(2) %>
-                                <td> <%= key +1 %> </td>
+                                <% data = seller.get_data_for_commissions(@initial_date, @final_date) %>
+                                <% commission_calculated = ((@pos_config.commission_percent / 100.0) * (data['income_by_cash'] + data['income_by_reserved_and_credits'])).round(2) %>
                                 <td> <%= seller.name %> </td>
-                                <td> <%= sales_by_period.count %> </td>
-                                <td> <%= l(sales_by_period.last.date_sale, :format => '%d/%m/%Y') %> </td>
-                                <td> <%= sales_by_period.joins(:sales_details).sum('sales_details.quantity').round %> </td>
-                                <td>
-                                  <%= number_to_currency(sales_by_period.sum(:total), precision: 2) %>
-                                </td>
-                                <td>
-
-                                  <%= number_to_currency(commission_calculated, precision: 2) %>
-                                </td>
+                                <td> <%= data['sales_count'] %> </td>
+                                <td> <%= number_to_currency(data['total_sold_cash'], precision: 2) %> </td>
+                                <td> <%= number_to_currency(data['total_sold_credits_apartments'], precision: 2) %> </td>
+                                <td> <%= number_to_currency(data['total_sold_cash'] + data['total_sold_credits_apartments'], precision: 2) %> </td>
+                                <td> <%= number_to_currency(data['income_by_cash'], precision: 2) %> </td>
+                                <td><%= number_to_currency(data['income_by_reserved_and_credits'], precision: 2) %></td>
+                                <td><%= number_to_currency(data['income_by_cash'] + data['income_by_reserved_and_credits'], precision: 2) %></td>
+                                <td><%= number_to_currency(commission_calculated, precision: 2) %></td>
                                 <td>
                                   <%= f.fields_for :sellerscommissions do |b| %>
                                     <%= b.number_field :commission_paid, {:class =>"form-control", :value => commission_calculated, input_html: {min: 0}, :step =>"any", :pattern =>"^[0-9]*[1-9][0-9]*$"} %>
                                     <%= b.hidden_field :seller_id, :value => seller.id %>
-                                    <%= b.hidden_field :num_sales, :value => sales_by_period.count %>
-                                    <%= b.hidden_field :num_products, :value => sales_by_period.joins(:sales_details).sum('sales_details.quantity').round  %>
-                                    <%= b.hidden_field :sales_total, :value => sales_by_period.sum(:total) %>
+                                    <%= b.hidden_field :num_sales, :value => data['sales_count'] %>
+                                    <%= b.hidden_field :sales_total, :value => (data['total_sold_cash'] + data['total_sold_credits_apartments']) %>
                                     <%= b.hidden_field :commission_calculated, :value => commission_calculated %>
                                     <%= b.hidden_field :commission_percent, :value => @pos_config.commission_percent %>
+                                    <%= b.hidden_field :total_sold_cash, :value => data['total_sold_cash'] %>
+                                    <%= b.hidden_field :total_sold_credits_apartments, :value => data['total_sold_credits_apartments'] %>
+                                    <%= b.hidden_field :income_by_cash, :value => data['income_by_cash'] %>
+                                    <%= b.hidden_field :income_by_reserved_and_credits, :value => data['income_by_reserved_and_credits'] %>
                                   <% end %>
                                 </td>
                               </tr>

+ 15 - 16
app/views/commissions/_sellers_for_commissions.html.erb

@@ -1,10 +1,10 @@
 <div class="form-horizontal">
     <div class="portlet-body form">
         <div class="form-body">
-            <div class="row">     
+            <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 %> 
+                       <%= 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" %>
@@ -12,10 +12,10 @@
                                 <%= 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>
                     <div class="form-group">
-                      <%= label_tag :initial_date, "Fecha", {:class=>"col-md-2 control-label"} do %>Desde <span class="required">*</span> <% end %> 
+                      <%= 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"/>
@@ -24,7 +24,7 @@
                               </span>
                           </div>
                       </div>
-                      <%= label_tag :final_date, "Fecha", {:class=>"col-md-2 control-label"} do %>Hasta <span class="required">*</span> <% end %> 
+                      <%= 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"/>
@@ -35,17 +35,17 @@
                       </div>
                       <button class="btn btn-icon-only blue" style="margin-left:25px" onclick="getSellersByDates()">
                         <i class="fa fa-search"></i>
-                      </button>                      
-                    </div> 
+                      </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 %> 
+                            <%= 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>
                                 </div>
                                 <%= select_tag :sellers_ids, nil, multiple: true, class: 'multi-select' %>
                             </div>
@@ -58,12 +58,12 @@
     <div class="form-actions">
         <h4 class="form-section"> </h4>
         <div class="row">
-            <div class="col-md-12">                     
+            <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>
 </div>
 <script>
     function cerrarDialog() {
@@ -88,7 +88,7 @@
         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 final_date = moment($("#final_date").data("date"), "DD-MM-YYYY").startOf('day').format('YYYY-MM-DD HH:mm:ss');
             var pointsale_id = $('#pointsale_id').val();
 
             App.blockUI({
@@ -106,7 +106,7 @@
                     $('#sellers_ids').append($('<option>', {
                         value: data[i].seller_id,
                         text : data[i].name
-                    }));          
+                    }));
                   }
                   $('#sellers_ids').multiselect('refresh');
                   App.unblockUI($("#sellers_div"));
@@ -116,7 +116,7 @@
 
         } else {
             toastr["error"]('Seleccione punto de venta y rango de fechas');
-        }        
+        }
     }
 
     function generateCommissions() {
@@ -135,10 +135,9 @@
               },
               success: function(data) {
               }
-            });        
+            });
        } else {
             toastr["error"]('Seleccione vendedores para generar comisiones');
        }
     }
 </script>
-	

+ 16 - 18
app/views/commissions/show.html.erb

@@ -72,31 +72,29 @@
                                     <table class="table table-striped table-bordered table-hover tableadvanced">
                                       <thead>
                                         <tr>
-                                          <th>#</th>
                                           <th>Vendedor</th>
-                                          <th>Ventas</th>
-                                          <th>Productos vendidos</th>
-                                          <th>Total de ventas</th>
-                                          <th>Comisión sugerida</th>
-                                          <th>Comision pagada</th>
+                                          <th>Ventas en <br>el periodo</th>
+                                          <th>Total <br>contado</th>
+                                          <th>Total créditos y <br>apartados</th>
+                                          <th>Total <br>vendido</th>
+                                          <th>$ ingresado<br>contado</th>
+                                          <th>$ ingresado<br>créditos <br>y apartados</th>
+                                          <th>Total <br>ingresado</th>
+                                          <th>Comisión <br>pagada</th>
                                         </tr>
                                       </thead>
                                       <tbody>
-                                      <% @commission.sellerscommissions.each_with_index do |seller_commission, key| %>
+                                      <% @commission.sellerscommissions.each_with_index do |seller_commission| %>
                                           <tr>
-                                            <td> <%= key +1%> </td>
                                             <td><%= seller_commission.seller.name %></td>
                                             <td><%= seller_commission.num_sales.round %></td>
-                                            <td><%= seller_commission.num_products.round %></td>
-                                            <td>
-                                              <%= number_to_currency(seller_commission.sales_total, precision: 2)  %>
-                                            </td>
-                                            <td>
-                                              <%= number_to_currency(seller_commission.commission_calculated, precision: 2) %>
-                                            </td>
-                                            <td>
-                                              <%= number_to_currency(seller_commission.commission_paid, precision: 2) %>
-                                            </td>
+                                            <td><%= number_to_currency(seller_commission.total_sold_cash, precision: 2) %></td>
+                                            <td><%= number_to_currency(seller_commission.total_sold_credits_apartments, precision: 2) %></td>
+                                            <td><%= number_to_currency(seller_commission.sales_total, precision: 2)  %></td>
+                                            <td><%= number_to_currency(seller_commission.income_by_cash, precision: 2) %></td>
+                                            <td><%= number_to_currency(seller_commission.income_by_reserved_and_credits, precision: 2) %></td>
+                                            <td><%= number_to_currency(seller_commission.income_by_cash + seller_commission.income_by_reserved_and_credits, precision: 2) %></td>
+                                            <td><%= number_to_currency(seller_commission.commission_paid, precision: 2) %></td>
                                           </tr>
                                       <% end %>
                                       </tbody>

+ 11 - 0
db/migrate/20171211222709_change_columns_in_sellers_commissions.rb

@@ -0,0 +1,11 @@
+class ChangeColumnsInSellersCommissions < ActiveRecord::Migration
+  def change
+  	if table_exists? :sellerscommissions
+	  	remove_column :sellerscommissions, :num_products
+	  	add_column :sellerscommissions, :total_sold_cash, :decimal, precision: 10, scale: 2, default: 0.0
+	  	add_column :sellerscommissions, :total_sold_credits_apartments, :decimal, precision: 10, scale: 2, default: 0.0
+			add_column :sellerscommissions, :income_by_cash, :decimal, precision: 10, scale: 2, default: 0.0
+			add_column :sellerscommissions, :income_by_reserved_and_credits, :decimal, precision: 10, scale: 2, default: 0.0
+  	end
+  end
+end

+ 24 - 19
db/schema.rb

@@ -11,7 +11,7 @@
 #
 # It's strongly recommended that you check this file into your version control system.
 
-ActiveRecord::Schema.define(version: 20170529183330) do
+ActiveRecord::Schema.define(version: 20171211222709) do
 
   # These are extensions that must be enabled in order to support this database
   enable_extension "plpgsql"
@@ -386,17 +386,18 @@ ActiveRecord::Schema.define(version: 20170529183330) do
     t.integer  "user_id"
     t.integer  "open_cash_register_id"
     t.integer  "product_id"
-    t.datetime "created_at",                                                             null: false
-    t.datetime "updated_at",                                                             null: false
+    t.datetime "created_at",                                                               null: false
+    t.datetime "updated_at",                                                               null: false
     t.integer  "sale_type",             limit: 2
-    t.decimal  "amount",                                                   default: 0.0, null: false
-    t.decimal  "tax",                                                      default: 0.0, null: false
-    t.decimal  "discount",                                                 default: 0.0, null: false
-    t.decimal  "total",                                                    default: 0.0, null: false
+    t.decimal  "amount",                                                   default: 0.0,   null: false
+    t.decimal  "tax",                                                      default: 0.0,   null: false
+    t.decimal  "discount",                                                 default: 0.0,   null: false
+    t.decimal  "total",                                                    default: 0.0,   null: false
     t.integer  "special_price_id"
     t.decimal  "unit_price",                      precision: 10, scale: 2
     t.decimal  "haggle",                          precision: 10, scale: 2, default: 0.0
-    t.decimal  "quantity",                        precision: 10, scale: 2,               null: false
+    t.decimal  "quantity",                        precision: 10, scale: 2,                 null: false
+    t.boolean  "is_adjustment",                                            default: false
   end
 
   create_table "pre_transfers", force: :cascade do |t|
@@ -554,19 +555,20 @@ ActiveRecord::Schema.define(version: 20170529183330) do
     t.integer  "customer_id"
     t.integer  "user_id"
     t.integer  "open_cash_register_id"
-    t.decimal  "amount",                          precision: 10, scale: 2, default: 0.0, null: false
-    t.decimal  "tax",                             precision: 10, scale: 2, default: 0.0, null: false
-    t.decimal  "discount",                        precision: 10, scale: 2, default: 0.0, null: false
-    t.decimal  "total",                           precision: 10, scale: 2, default: 0.0, null: false
-    t.integer  "status",                                                   default: 1,   null: false
-    t.date     "date_sale",                                                              null: false
-    t.datetime "created_at",                                                             null: false
-    t.datetime "updated_at",                                                             null: false
+    t.decimal  "amount",                          precision: 10, scale: 2, default: 0.0,   null: false
+    t.decimal  "tax",                             precision: 10, scale: 2, default: 0.0,   null: false
+    t.decimal  "discount",                        precision: 10, scale: 2, default: 0.0,   null: false
+    t.decimal  "total",                           precision: 10, scale: 2, default: 0.0,   null: false
+    t.integer  "status",                                                   default: 1,     null: false
+    t.date     "date_sale",                                                                null: false
+    t.datetime "created_at",                                                               null: false
+    t.datetime "updated_at",                                                               null: false
     t.integer  "saletype",              limit: 2
     t.integer  "seller_id"
     t.string   "sale_code"
     t.date     "expiration_date"
     t.string   "credit_note"
+    t.boolean  "is_adjustment_sale",                                       default: false
   end
 
   add_index "sales", ["customer_id"], name: "index_sales_on_customer_id", using: :btree
@@ -617,13 +619,16 @@ ActiveRecord::Schema.define(version: 20170529183330) do
     t.integer  "commission_id"
     t.integer  "seller_id"
     t.integer  "num_sales"
-    t.integer  "num_products"
     t.decimal  "sales_total"
     t.decimal  "commission_calculated"
     t.decimal  "commission_paid"
-    t.datetime "created_at",            null: false
-    t.datetime "updated_at",            null: false
+    t.datetime "created_at",                                                            null: false
+    t.datetime "updated_at",                                                            null: false
     t.integer  "commission_percent"
+    t.decimal  "total_sold_cash",                precision: 10, scale: 2, default: 0.0
+    t.decimal  "total_sold_credits_apartments",  precision: 10, scale: 2, default: 0.0
+    t.decimal  "income_by_cash",                 precision: 10, scale: 2, default: 0.0
+    t.decimal  "income_by_reserved_and_credits", precision: 10, scale: 2, default: 0.0
   end
 
   add_index "sellerscommissions", ["commission_id"], name: "index_sellerscommissions_on_commission_id", using: :btree

BIN=BIN
erd.pdf