<commit_before>class Spree::Importers::DataFactory

    attr_reader :log, :taxonomy, :taxon, :attrs

    def initialize(taxonomy_id, taxon_id, attrs={})
        @log = Logger.new(STDOUT)
        @taxonomy = Spree::Taxonomy.find(taxonomy_id)
        @taxon = Spree::Taxon.find(taxon_id)
        @attrs = attrs
        prepare_attrs
    end

    def solve
        raise ArgumentError.new("Option :name is required") unless attrs['name']
        products = Spree::Product.find_by_synonim(attrs['name'])
        if products.present?
            update_product(products.first)
        else
            handle_missing_product
        end
    end

    protected

    def prepare_attrs
        if attrs['name'][0] == "\""
            @attrs['name'][0]=''
        end
        if attrs['name'][-1] == "\""
            @attrs['name'][-1]=''
        end
        unless attrs['sku'].present?
            @attrs['sku'] = "%06d" % rand(999999)
        end
    end

    def update_product(product)
        log.info("Товар #{attrs['name']} найден в таблице! Обновляем атрибуты: Cебестоимость: #{attrs['cost_price'].to_f.to_s} | Цена: #{attrs['price'].to_f.to_s}")
        product.update_attributes(attrs.except('sku', 'quantity'))
        product.taxons << taxon unless product.taxons.exists?(taxon)
        update_quantity(product)
    end

    def create_product
        log.info("Создан новый товар! Наименование: #{attrs['name']} | Cебестоимость: #{attrs['cost_price'].to_f.to_s} | Цена: #{attrs['price'].to_f.to_s} | Артикул: #{attrs['sku'].to_s}")
        product = Spree::Product.create!(attrs.merge(shipping_category_id: Spree::ShippingCategory.first.id).except('quantity'))
        product.taxons << taxon
        update_quantity(product)
    end

    def update_quantity(product)
        stock_location = Spree::StockLocation.active.first
        if stock_location && attrs['quantity'] > 0
            stock_movement = stock_location.stock_movements.build(quantity: attrs['quantity'])
            stock_movement.stock_item = stock_location.set_up_stock_item(product.master)
            stock_movement.save!
        end
    end

    def handle_missing_product
        conflict = Spree::Conflict.find_by_product_name(attrs['name'])
        similar_data_present = unless conflict
                                   sim_prods = Spree::ProductSynonim.name_matching(attrs['name']).limit(1)
                                   sim_prods.present? && sim_prods[0].pg_search_rank > Spree::Importers::MIN_PG_SEARCH_RANK ? true : false
                               end
        if similar_data_present || conflict.present?
            handle_conflict(conflict)
        else
            create_product
        end<commit_msg>dont update name of existing products<commit_after>class Spree::Importers::DataFactory

    attr_reader :log, :taxonomy, :taxon, :attrs

    def initialize(taxonomy_id, taxon_id, attrs={})
        @log = Logger.new(STDOUT)
        @taxonomy = Spree::Taxonomy.find(taxonomy_id)
        @taxon = Spree::Taxon.find(taxon_id)
        @attrs = attrs
        prepare_attrs
    end

    def solve
        raise ArgumentError.new("Option :name is required") unless attrs['name']
        products = Spree::Product.find_by_synonim(attrs['name'])
        if products.present?
            update_product(products.first)
        else
            handle_missing_product
        end
    end

    protected

    def prepare_attrs
        if attrs['name'][0] == "\""
            @attrs['name'][0]=''
        end
        if attrs['name'][-1] == "\""
            @attrs['name'][-1]=''
        end
        unless attrs['sku'].present?
            @attrs['sku'] = "%06d" % rand(999999)
        end
    end

    def update_product(product)
        log.info("Товар #{attrs['name']} найден в таблице! Обновляем атрибуты: Cебестоимость: #{attrs['cost_price'].to_f.to_s} | Цена: #{attrs['price'].to_f.to_s}")
        product.update_attributes(attrs.except('sku', 'quantity', 'name'))
        product.taxons << taxon unless product.taxons.exists?(taxon)
        update_quantity(product)
    end

    def create_product
        log.info("Создан новый товар! Наименование: #{attrs['name']} | Cебестоимость: #{attrs['cost_price'].to_f.to_s} | Цена: #{attrs['price'].to_f.to_s} | Артикул: #{attrs['sku'].to_s}")
        product = Spree::Product.create!(attrs.merge(shipping_category_id: Spree::ShippingCategory.first.id).except('quantity'))
        product.taxons << taxon
        update_quantity(product)
    end

    def update_quantity(product)
        stock_location = Spree::StockLocation.active.first
        if stock_location && attrs['quantity'] > 0
            stock_movement = stock_location.stock_movements.build(quantity: attrs['quantity'])
            stock_movement.stock_item = stock_location.set_up_stock_item(product.master)
            stock_movement.save!
        end
    end

    def handle_missing_product
        conflict = Spree::Conflict.find_by_product_name(attrs['name'])
        similar_data_present = unless conflict
                                   sim_prods = Spree::ProductSynonim.name_matching(attrs['name']).limit(1)
                                   sim_prods.present? && sim_prods[0].pg_search_rank > Spree::Importers::MIN_PG_SEARCH_RANK ? true : false
                               end
        if similar_data_present || conflict.present?
            handle_conflict(conflict)
        else
            create_product
        end
{'fraction_non_alphanumeric': 0.12403528114663727, 'fraction_numerical': 0.005512679162072767, 'mean_word_length': 2.5645055664702032, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2630111', 'n_tokens_mistral': 1716, 'n_tokens_neox': 1709, 'n_words': 277}