Jelajahi Sumber

Merge branch 'chemi_branch' of SML/pos-boutique into master

Jose Miguel Ledon 6 tahun lalu
induk
melakukan
749325ab80

+ 2 - 1
app/controllers/products_controller.rb

@@ -103,9 +103,9 @@ class ProductsController < ApplicationController
           @product.generate_barcode
           @product.save
         end
-        @product.save_variants(current_user)
         ##--- Para cuando se agrega un producto desde purchase
         if params[:remoto] == "true"
+          @product.save_variants_no_thread(current_user)
           ##--- Guardar pre_purchase
           @pre_purchases = Array.new
           if @product.presentation && @product.is_parent
@@ -122,6 +122,7 @@ class ProductsController < ApplicationController
           format.json { head :no_content }
           format.js
         else
+          @product.save_variants(current_user)
           # crear available product para el p.v, cuando es sin variantes
           if current_user.usertype == 'G' && !@product.presentation && !@product.is_parent
             AvailableProduct.create(product_id: @product.id, pointsale_id: current_user.pointsale_id, stock: 0)

+ 2 - 2
app/models/pre_purchase.rb

@@ -21,9 +21,9 @@ class PrePurchase < ActiveRecord::Base
 
     self.amount = quantity * price_base
     self.tax = 0.0
-    if product.include_purchase_tax? && exchange.blank?
+    if product.include_purchase_tax == 1 && exchange.blank?
       tax_percent = PosConfig.first.tax_percent
-      self.tax = (((tax_percent / 100)  * amount) / ((100 + tax_percent) / 100)).round(2)
+      self.tax = (((tax_percent / 100) * amount)).round(2)
     end
     self.total = tax + amount
     true

+ 39 - 0
app/models/product.rb

@@ -237,6 +237,45 @@ class Product < ActiveRecord::Base
   end
   # rubocop:enable Metrics/BlockLength
 
+  # rubocop:disable Metrics/BlockLength
+  def save_variants_no_thread(current_user)
+      combinations = Array.new
+      attributes = Array.new
+      combinations = get_combinations(combinations, attributes)
+
+      ##--- recorrer combinaciones para crear las variantes de productos
+      unless combinations.nil?
+        combinations.each_with_index do |combination, index|
+          @products_variant = Product.new
+          @products_variant = dup
+          @products_variant.parent_id = id
+          @products_variant.is_parent = false
+          @products_variant.sku = sku + (index + 1).to_s + "A"
+          attributes_json = {}
+
+          if combination.is_a?(Array)
+            combination.each do |attrib|
+              attributes_json = @products_variant.assign_attributes_to_variant(attrib, id, attributes_json)
+            end
+          else
+            attributes_json = @products_variant.assign_attributes_to_variant(combination, id, attributes_json)
+          end
+
+          @products_variant.attributes_json = attributes_json.to_json
+          @products_variant.save
+
+          @products_variant.generate_barcode
+
+          @products_variant.save
+
+          if current_user.usertype == 'G'
+            AvailableProduct.create(product_id: @products_variant.id, pointsale_id: current_user.pointsale_id, stock: 0)
+          end
+        end
+      end
+  end
+  # rubocop:enable Metrics/BlockLength
+
   def assign_attributes_to_variant(attri, parent_id, attributes_json)
     attri_id = ActsAsTaggableOn::Tag.where("lower(name) = lower(?)", attri).select(:id).first
     get_context = ActsAsTaggableOn::Tagging.where(tag_id: attri_id, taggable_id: parent_id, taggable_type: 'Product').select(:context).first

+ 68 - 51
app/views/products/_form_remote.html.erb

@@ -110,40 +110,37 @@
 					) %>
 				</div>
 			</div>
-
+			<%
+				@category = nil
+				@subcategory = nil
+				@prompt = 'Seleccione'
+				@disabled = true
+				if @product.category.present? && @product.category.parent_id == 0
+				@category = @product.category
+				@disabled = false
+				elsif @product.category.present? && @product.category.parent_id != 0
+				@category = Category.find(@product.category.parent_id)
+				@subcategory = @product.category
+				@disabled = false
+				end
+			%>
 			<div class="form-group">
-				<%
-					@category = nil
-					@subcategory = nil;
-					@prompt = 'Seleccione'
-					@disabled = true
-					if @product.categories[0].present? && @product.categories[0].parent_id == 0
-						@category = @product.categories[0]
-						@prompt = ''
-					elsif @product.categories[0].present?
-						@category = Category.find(@product.categories[0].parent_id)
-						@subcategory = @product.categories[0]
-						@disabled = false
-					end
-				%>
-				<%= label_tag :categorias, "Líneas de producto", {:class=>"col-md-3 control-label"} do %>Líneas de producto
-					<span class="required">*</span>
+				<%= f.label :category_id, "Líneas de producto", { class: "col-md-3 control-label" } do %>Líneas de producto
+				<span class="required">*</span>
 				<% end %>
 				<div class="col-md-4">
-						<%= select_tag 'categorias',
-						    options_from_collection_for_select(Category.activos_padre, 'id', 'category',
-				    			:selected => (@category.id unless @category.nil?)),
-						    	{:include_blank => "Seleccione", :class => 'form-control'} %>
+					<%= f.collection_select(:category_id, Category.activos_padre, :id, :category, options = { include_blank: "Seleccione", selected: (@category.present? ? @category.id : @prompt ) }, class: "form-control select2", onchange: "getSubCategories($(this).val())") %>
 				</div>
 			</div>
 			<div class="form-group">
-				<%= f.label :category_ids, "Sublinea del producto", {:class=>"col-md-3 control-label"}   %>
+				<%= f.label :sub_category_id, "Sublíneas de producto", { class: "col-md-3 control-label" } do %>Sublínea de producto
+				<span class="required">*</span>
+				<% end %>
 				<div class="col-md-4">
-					<%= f.collection_select(:category_ids, @category.nil? ? {} : Category.where(:parent_id => @category.id), :id, :category , options ={:include_blank => @prompt, :selected => (@subcategory.id unless @subcategory.nil?) }, :class => "form-control", :disabled => @disabled) %>
-					<%= f.hidden_field :category_ids, {:id => 'subcategory_hidden'}%>
+					<%= collection_select("", :sub_category_id, (@category.present? ? Category.activos.where(parent_id: @category.id) : {}), :id, :category, options = { prompt: "Seleccione", selected: (@subcategory.id if @subcategory.present?) }, html_options = { class: 'form-control select2 select2-allow-clear-todas' }) %>
+					<%= hidden_field_tag :subcategory_hidden, (@subcategory.id if @subcategory.present?) %>
 				</div>
 			</div>
-
 			<div class="form-group">
 				<%= f.label :include_purchase_tax, "¿Incluir IVA en compra?", {:class=>"col-md-3 control-label"} do %> ¿Incluir IVA en compra?
 					<span class="required">*</span>
@@ -165,7 +162,7 @@
 
 
 			<div class="form-group">
-				<%= f.label :include_sale_tax, "¿Incluir IVA en venta?", {:class=>"col-md-3 control-label"} do %> ¿Incluir IVA en compra?
+				<%= f.label :include_sale_tax, "¿Incluir IVA en venta?", {:class=>"col-md-3 control-label"} do %> ¿Incluir IVA en venta?
 					<span class="required">*</span>
 				<% end %>
 				<div class="col-md-9">
@@ -366,7 +363,6 @@
 	$('#product_style_list').on('change', function(event) { getVariants(); });
 
 	function presentaciones(){
-		console.log($('#product_presentation').is(':checked'));
 		if ($('#product_presentation').is(':checked')){
 			$('.presentaciones').removeClass('hidden');
 		}
@@ -416,7 +412,34 @@
 		}
 	});
 
-	$('#product_category_ids').on('change', function() {
+	function getSubCategories(value) {
+		$('#_sub_category_id').html('');
+		$('#_sub_category_id').select2("destroy").select2({ placeholder: 'Seleccione'});
+		$('#_sub_category_id').select2('val', null);
+		if($('#product_category_id').val()) {
+			$.ajax({
+				type: "get",
+				url: '/getcategories/' + value,
+				dataType: 'json',
+				success: function(data) {
+					if(data.length > 0) {
+						$('#_sub_category_id').append('<option></option>')
+						for(i in data) {
+						$('#_sub_category_id').append("<option value='" + data[i].id + "'>" + data[i].category + "</option>")
+						}
+						$('#_sub_category_id').select2({ placeholder: 'Seleccione'});
+						$('#_sub_category_id').attr('disabled', false);
+					} else {
+						$('#_sub_category_id').attr('disabled', true);
+						$('#subcategory_hidden').val($('#product_category_id').val());
+					}
+					fillSKU();
+				}
+			});
+		}
+	}
+
+	$('#_sub_category_id').on('change', function() {
 		$('#subcategory_hidden').val($(this).val());
 		fillSKU();
 	});
@@ -441,39 +464,33 @@
 
 
 	function getProductId() {
-		$('#categorias').attr('disabled', true);
+		$('#product_category_id').attr('disabled', true);
+		var category_id = $('#_sub_category_id').val() ? $('#_sub_category_id').val() : $('#product_category_id').val();
 		$.ajax({
 			type: "get",
 			url:  '/get_max_product_id',
 			dataType: 'json',
+			data: {
+				category_id: category_id
+			},
 			success: function(data) {
-				$('#categorias').attr('disabled', false);
+				$('#product_category_id').attr('disabled', false);
 				var sku = $('#product_sku').val();
-				if(sku.length && !$('#idproduct').val()) {
-					$('#product_sku').val(sku + "-" + data);
-				} else {
-					$('#product_sku').val(sku + "-" + $('#idproduct').val());
-				}
-			},
+				$('#product_sku').val(sku + "-" + data);
+			}
 		});
-	}
+  	}
 
 	function fillSKU() {
-		var sku = $('#product_sku').val();
-		if(sku.length <= 3) {
-			$('#product_sku').val($('#categorias option:selected').text().substring(0,3).toUpperCase());
-			getProductId();
-		}
-
-		sku = $('#product_sku').val();
-		if(sku.length >= 3 && $('#product_category_ids').val() != "0") {
-			var subcategory = $('#product_category_ids option:selected').text();
-			if(subcategory){
-				$('#product_sku').val(sku.substring(0,3) + '-' + subcategory.replace(regex, '')
-					.substring(0,3).toUpperCase());
-				getProductId();
+		var category = $('#product_category_id option:selected').text().substring(0,3).toUpperCase();
+		$('#product_sku').val(category);
+		if($('#_sub_category_id').val()) {
+				var subcategory = $('#_sub_category_id option:selected').text();
+				if(subcategory) {
+					$('#product_sku').val(category + '-' + subcategory.replace(regex, '').substring(0,3).toUpperCase());
+				}
 			}
-		}
+		getProductId();
 	}
 
 	function validateBarcode(barcode) {

+ 1 - 1
app/views/products/create.js.erb

@@ -1,6 +1,6 @@
 var table = $('#products_table').DataTable();
 <% @pre_purchases.each do |pre_purchase| %>
-	var newRow = $('<%= j render (@pre_purchase) %>');
+	var newRow = $('<%= j render (pre_purchase) %>');
 	x = $('#products_table').dataTable();
 	newRow.find('td:eq(0)').html(newRow.find('td:eq(0)').html().replace('#', x.fnGetData().length + 1));
 	table.row.add($(newRow)).draw();

+ 1 - 1
app/views/products/new.js.erb

@@ -9,5 +9,5 @@ $('#dialog').modal("show");
 
 // Set focus to the first element
 $('#dialog').on('shown.bs.modal', function () {
-  	$('.first_input').focus()
+	$('.modal-body .select2').select2();
  })