Esempio n. 1
0
 def test_create_variant(self):
     self.fake("products/632910392/variants",
               method='POST',
               body=self.load_fixture('variant'),
               headers={'Content-type': 'application/json'})
     v = shopify.Variant({'product_id': 632910392})
     v.save()
Esempio n. 2
0
 def export_products(self):
     """
     This functions export products of the user to his shopify shop
     :return:
     """
     export_products = ""
     products = self.env['product.template'].search([('create_uid', '=',
                                                      self.env.user.id)])
     shopify_products = shopify.Product.find(limit=250)
     for product in products:
         already_exist = False
         for shopify_product in shopify_products:
             if shopify_product.attributes['title'] == product.name:
                 already_exist = True
                 break
         if already_exist:
             continue
         export_products = export_products + product.name + " "
         new_product = shopify.Product()
         new_product.title = product.name
         new_product.body_html = product.description
         new_product.product_type = product.type
         product_variant = shopify.Variant({"title": "v1", "price": 123123})
         new_product.variants = [product_variant]
         new_product.save()
     if export_products:
         raise osv.except_osv(("Products Export Success"),
                              (export_products + " exported successfully"))
     else:
         raise osv.except_osv(("Products Export"),
                              ("non product to export"))
Esempio n. 3
0
def creat_a_product(**kwargs):
    session = shopify.Session(shop_url, api_version, access_token)
    shopify.ShopifyResource.activate_session(session)

    variants = []
    images = []
    new_product = shopify.Product()

    for key, value in kwargs.items():
        if key == 'variants':
            for item in value:
                variant = shopify.Variant(item)
                variants.append(variant)
            value = variants
        elif key == 'images':
            for item in value:
                image = shopify.Image()
                with open(item, "rb") as f:
                    filename = item.split("/")[-1:][0]
                    encoded = f.read()
                    image.attach_image(encoded, filename=filename)
                    images.append(image)
            value = images

        setattr(new_product, key, value)
    new_product.save()
    print(new_product.id)
    print(new_product.to_dict())
 def test_add_variant_to_product(self):
     self.fake("products/632910392/variants",
               method='POST',
               body=self.load_fixture('variant'),
               headers={'Content-type': 'application/json'})
     self.fake("products/632910392/variants/808950810",
               method='PUT',
               code=200,
               body=self.load_fixture('variant'),
               headers={'Content-type': 'application/json'})
     v = shopify.Variant()
     self.assertTrue(self.product.add_variant(v))
Esempio n. 5
0
def create_variants(variants, product):

    # variants = deepcopy(variants)
    product1 = shopify.Product.find(product.id)
    created_variants = []
    for variant in variants:
        # print(variant)
        # del variant['id']
        # vari = {
        #     "title": variant['title'],
        #     "option1": variant['option1'],
        #     "option2": variant['option2'],
        #     "option3": variant['option3'],
        #     "sku": variant['sku'],
        #     "requires_shipping": variant['requires_shipping'],
        #     "taxable": variant['taxable'],
        #     # "featured_image": variant['featured_image'],
        #     # "available": variant['available'],
        #     "price": variant['price'],
        #     "grams": variant['grams'],
        #     "compare_at_price": variant['compare_at_price'],
        #     "position": variant['position']
        # }
        # edit_variants(variant, product1)
        # for own_variant in product.variants:
        #     own_variant.attributes = vari
        # created_variants.append(shopify.Variant(vari))
        new_variant = shopify.Variant()
        new_variant.title = variant['title']
        new_variant.price = variant['price']
        new_variant.sku = variant['sku']
        new_variant.position = variant['position']
        new_variant.compare_at_price = variant['compare_at_price']
        new_variant.option1 = variant['option1']
        new_variant.option2 = variant['option2']
        new_variant.option3 = variant['option3']
        new_variant.taxable = variant['taxable']
        new_variant.grams = variant['grams']
        new_variant.requires_shipping = variant['requires_shipping']
        new_variant.inventory_policy = "continue"
        new_variant.inventory_quantity = 1
        new_variant.inventory_management = "shopify"
        new_variant.old_inventory_quantity = 1
        new_variant.fulfillment_service = "manual"
        created_variants.append(new_variant)
    product1.variants = []
    product1.variants = created_variants
    # product.variants = []
    save = product1.save()
    if save:
        print(product.title)
    else:
        print("Not Saved")
    def post_product(self, record):
        product = shopify.Product()
        product.title = record.name
        product.handle = record.default_code or record.name
        product.body_html = record.description_sale or record.description_purchase or ''

        if record.attribute_line_ids:
            product.options = [{
                'name': attribute_line.attribute_id.display_name
            } for attribute_line in record.attribute_line_ids]

        product.variants = []
        for local_variant in record.product_variant_ids:
            variant = {
                'price': local_variant.lst_price,
                'sku': local_variant.default_code or '',
                'barcode': local_variant.barcode or '',
                'inventory_management': 'shopify',
            }

            if record.attribute_line_ids:
                option_count = len(product.options)
                if option_count > 0:
                    variant.update(
                        option1=local_variant.
                        product_template_attribute_value_ids.filtered(
                            lambda self: product.options[0].get(
                                'name') in self.display_name).name)
                    if option_count > 1:
                        variant.update(
                            option2=local_variant.
                            product_template_attribute_value_ids.filtered(
                                lambda self: product.options[1].get(
                                    'name') in self.display_name).name)
                        if option_count > 2:
                            variant.update(
                                option2=local_variant.
                                product_template_attribute_value_ids.filtered(
                                    lambda self: product.options[2].get(
                                        'name') in self.display_name).name)
            variant = shopify.Variant(variant)
            product.variants.append(variant)
        if self.ensure_response(product, 'save'):
            for local_variant, remote_variant in zip(
                    record.product_variant_ids, product.variants):
                self.put_variant(local_variant, remote_variant.id, product)
            return True, product
        else:
            _logger.error(product.errors.errors)
            return False, product
Esempio n. 7
0
def randomProduct(title):
    images = []
    for i in range(random.randint(1, 4)):
        images.append(setUpImage(i + 1))
    variants = []
    variants.append(shopify.Variant({'price': random.randint(1, 100)}))
    attrs = {}
    attrs['title'] = title
    attrs['tags'] = ['bits and bobs, hats']
    attrs['body_html'] = '<p>Hat in Grey. 100% Alpaca.</p>'
    attrs['image'] = images[0]
    attrs['images'] = images
    attrs['variants'] = variants
    product = shopify.Product(attributes=attrs)
    return product
 def test_add_variant_to_product(self):
     self.fake(
         "products/632910392/variants",
         method="POST",
         body=self.load_fixture("variant"),
         headers={"Content-type": "application/json"},
     )
     self.fake(
         "products/632910392/variants/808950810",
         method="PUT",
         code=200,
         body=self.load_fixture("variant"),
         headers={"Content-type": "application/json"},
     )
     v = shopify.Variant()
     self.assertTrue(self.product.add_variant(v))
    def update_product_map_price(product, new_map_price):
        """
        This works right now but needs to be updated for multiple variants,

        The variants come in lists so that should be pretty easy to go through
        and change the one that needs to be changed.
        """
        update_product = shopify.Product.find(product.get_product_id())
        variant = shopify.Variant({'price': new_map_price, 'requires_shipping': True})
        if len(update_product.variants) == 1:
            update_product.variants = [variant]

        update_product.save()
        if update_product.errors:
            # something went wrong, see new_product.errors.full_messages() for example
            update_product.errors.full_messages()
Esempio n. 10
0
 def to_shopify_object(
         self,
         existing_object: Optional[shopify.Variant] = None
 ) -> shopify.Variant:
     if existing_object:
         obj = existing_object
     else:
         obj = shopify.Variant()
     for field in self.__fields__:
         if self.__getattribute__(field) is not None:
             obj.__setattr__(field, self.__getattribute__(field))
         # Special handling of compare at price. If this is None and price is given, then set to None.
         elif field == "compare_at_price" and self.__getattribute__(
                 "price") is not None:
             obj.__setattr__(field, None)
     return obj
 def export_product(self):
     """
             This functions export products of the user to his shopify shop
             :return:
             """
     shop_name = self.env.user.shop_name
     api_key = self.env.user.api_key
     api_password = self.env.user.api_password
     api_secret_key = self.env.user.api_secret_key
     shop_url = "https://%s:%s@%s.myshopify.com/admin" % (
         api_key, api_password, shop_name)
     shopify.ShopifyResource.set_site(shop_url)
     shopify.Session.setup(api_key=api_key, secret=api_secret_key)
     exported_products = ""
     products = self.env['product.template'].search([('id', 'in', self.ids)
                                                     ])
     shopify_products = shopify.Product.find(limit=250)
     for product in products:
         already_exist = False
         for shopify_product in shopify_products:
             if shopify_product.attributes['title'] == product.name:
                 already_exist = True
                 break
         if already_exist:
             continue
         exported_products = exported_products + product.name + " "
         new_product = shopify.Product()
         new_product.title = product.name
         new_product.body_html = product.description
         new_product.product_type = product.type
         product_variant = shopify.Variant({"title": "v1", "price": 123123})
         new_product.variants = [product_variant]
         new_product.save()
     if exported_products:
         raise osv.except_osv(
             ("Products Export Success"),
             (exported_products + " exported successfully"))
     else:
         raise osv.except_osv(("Products Export Message"),
                              ("non product to export"))
Esempio n. 12
0
    def put_variant(self, record, remote_id, product):
        variant = shopify.Variant({'id': remote_id})
        variant.product_id = product.id
        variant.price = round(
            record.with_context(pricelist=self.pricelist_id).price, 2)
        variant.sku = record.default_code or ''
        variant.barcode = record.barcode or ''
        variant.inventory_management = 'shopify'

        if record.image_1920:
            image = shopify.Image()
            image.alt = product.handle
            image.attachment = record.image_1920.decode('utf-8')
            image.product_id = product.id
            if self.ensure_response(image, 'save'):
                variant.image_id = image.id
            else:
                _logger.error(image.errors.errors)

        if record.product_template_attribute_value_ids:
            option_count = len(product.options)
            if option_count > 0:
                variant.option1 = record.product_template_attribute_value_ids.filtered(
                    lambda self: product.options[
                        0].name in self.display_name).name
                if option_count > 1:
                    variant.option2 = record.product_template_attribute_value_ids.filtered(
                        lambda self: product.options[
                            1].name in self.display_name).name
                    if option_count > 2:
                        variant.option3 = record.product_template_attribute_value_ids.filtered(
                            lambda self: product.options[
                                2].name in self.display_name).name

        if self.ensure_response(variant, 'save'):
            return True, variant
        else:
            _logger.error(variant.errors.errors)
            return False, variant
Esempio n. 13
0
def create_shopify_products(shopify_products):
    """
    Connect to shopify store, create products based on shopify_products dict
    coming from get_tahoe_courses() function and notify admins about product
    creation
    """
    try:
        # connect to shopify store
        shopify.ShopifyResource.set_site(shopify_store_admin_api)
        store = shopify.Shop.current()
        store_admin_name = store.name
        store_admin_email = store.customer_email
        # 1 Create products in store
        # 1.1 find existing SKUs from shopify to checkproduct doesn't exist
        variants = shopify.Variant.find()
        # SKU in shopify is Course ID in OpenEDX
        skus = []
        number_created_products = 0
        created_products_list = []
        for variant in variants:
            # Fill SKUs list with all courses id that exist in shopify
            skus.append(variant.sku)
        # 1.2 loop over shopify_products and create store products
        # shopify_products contains course metadata coming from OpenEDX
        for product in shopify_products:
            # 1.3 Check if the course already exist in store
            # Remember product_sku = result["course_id"]
            if not product["product_sku"] in skus:
                # 1.4 create products in store
                new_product = shopify.Product()
                new_image = shopify.Image()
                new_product.title = product["product_title"]
                new_product.body_html = product["product_description"]
                new_product.published = "false"
                new_product.published_at = ""
                # tag is site full URL
                new_product.tags = product["product_tag"]
                new_variant = shopify.Variant(
                    {
                        "sku": product["product_sku"],
                        "requires_shipping": False,
                        "inventory_policy": "deny",
                    }
                )
                new_product.variants = [new_variant]
                product_saved = new_product.save()
                if product_saved:
                    logging.info(
                        "{}: {} created successfully".format(
                            product["product_title"], product["product_sku"]
                        )
                    )
                else:
                    logging.error(
                        "unexpected error happened for {}: {} creation".format(
                            product["product_title"], product["product_sku"]
                        )
                    )
                new_image.src = product["product_image"]
                new_product.images = new_image
                new_image.product_id = new_product.id
                image_saved = new_image.save()
                if not image_saved and not product["product_image"]:
                    logging.error("{}: {} image didn't get saved")
                number_created_products += 1
                created_products_list.append(
                    [
                        product["product_title"],
                        product["product_sku"],
                        product["product_tag"],
                        date.today().strftime("%m-%d-%Y"),
                    ]
                )
            else:
                continue
        logging.info("{} product(s) created usccessfully".format(
            number_created_products
            )
        )
        # 2 Notify admins via email with created courses report
        # 2.1 Create CSV file from created products
        if number_created_products:
            text = "Number of created products in shopify: {} ".format(
                number_created_products
            )
            header = ["Product Name", "Product SKU", "Tahoe URL", "Created AT"]
            fp = NamedTemporaryFile(
                delete=False,
                prefix="created_product_",
                suffix=".csv",
                mode="w",
                dir="/tmp/",
            )
            writer = csv.writer(fp, quotechar='"', quoting=csv.QUOTE_ALL)
            writer.writerow(header)
            for created_product in created_products_list:
                writer.writerow(created_product)
            fp.flush()
            fp.close()
            data = open(fp.name, "rb").read()
            message = {
                "attachments": [
                    {
                        "content": base64.b64encode(data).decode("utf-8"),
                        "name": fp.name.split("/")[2],
                        "type": "text/csv",
                    }
                ],
                "from_email": "*****@*****.**",
                "from_name": "Appsembler Technical Support",
                "important": True,
                "subject": "You'r Shopify product creation report",
                "text": text,
                "to": [
                    {
                        "email": store_admin_email,
                        "name": store_admin_name,
                        "type": "to",
                    },
                    {
                        "email": "*****@*****.**",
                        "name": "Amir Tadrisi",
                        "type": "to",
                    },
                ],
            }
            if environment == "prod":
                mandrill_client.messages.send(message=message)
        return Response(
            "{} Product(s) got created".format(number_created_products),
            status=201
        )
    except Exception as e:
        logging.error(e)
        if environment == "prod":
            stackdriver_client.report_exception()
    def add_new_wheel(connection, wheel_variant):
        """
        Method that adds a new Wheel ProsWheel to Shopify
        :param wheel_variant: Wheel to add
        :return: Returns nothing
        """
        # TODO: Need to find a way to stream line this
        # TODO: Comment out the method

        # Make the tags that we want to add
        tags_to_add = []
        # Brand
        tags_to_add.append("Brand_" + wheel_variant.whl_manufact_nm)
        # Finish
        tags_to_add.append("Finish_" + wheel_variant.finish)
        # Bolt Pattern
        tags_to_add.append("Bolt Pattern_" + wheel_variant.bolt_pattern_metric)
        # Wheel Offset
        tags_to_add.append("Wheel Offset_" + wheel_variant.offset)
        # Wheel Size
        tags_to_add.append("Wheel Size_" + wheel_variant.size)

        # Make the bolt pattern setup
        lug_count = wheel_variant.lug_count
        dist1 = str(int(float(wheel_variant.bolt_pattern_mm_1)))
        bolt_pattern1 = lug_count + "x" + dist1
        # print(bolt_pattern1)
        dist2 = str(int(float(wheel_variant.bolt_pattern_mm_2)))
        bolt_pattern2 = ""
        if int(dist2) != 0:
            bolt_pattern2 = lug_count + "x" + dist2

        # 2 cases
        # 1) Is a variant
        if wheelTools.has_variants(wheel_variant):
            product_id = wheelTools.find_product_id(wheel_variant)
            new_wheel_product = shopify.Product.find(product_id)
            variant = shopify.Variant({'price': wheel_variant.map_price,
                                       'option1': wheel_variant.size,
                                       'option2': bolt_pattern1,
                                       'option3': wheel_variant.offset,
                                       'quantity': 1,
                                       'sku': wheel_variant.upc,
                                       'position': 1,
                                       'inventory_policy': "deny",
                                       'fulfillment_service': "manual",
                                       'inventory_management': "shopify",
                                       'inventory_quantity': wheel_variant.curr_stock,
                                       'taxable': True,
                                       'weight': float(wheel_variant.shipping_weight),
                                       'weight_unit': "g",  # g, kg
                                       'requires_shipping': True})

            # TODO: Need to organize this code
            # Below is all for when there is a second bolt pattern
            variant2 = shopify.Variant({'price': wheel_variant.map_price,
                                        'option1': wheel_variant.size,
                                        'option2': bolt_pattern2,
                                        'option3': wheel_variant.offset,
                                        'quantity': 1,
                                        'sku': wheel_variant.upc,
                                        'position': 1,
                                        'inventory_policy': "deny",
                                        'fulfillment_service': "manual",
                                        'inventory_management': "shopify",
                                        'inventory_quantity': wheel_variant.curr_stock,
                                        'taxable': True,
                                        'weight': float(wheel_variant.shipping_weight),
                                        'weight_unit': "g",  # g, kg
                                        'requires_shipping': True})

            # print(type(new_wheel_product.variants))
            if bolt_pattern1 not in new_wheel_product.tags:
                new_wheel_product.tags += "," + bolt_pattern1
            if bolt_pattern2 not in new_wheel_product.tags:
                new_wheel_product.tags += "," + bolt_pattern2
            # print(new_wheel_product)
            new_wheel_product.variants.append(variant)
            if bolt_pattern2 != "":
                new_wheel_product.variants.append(variant2)
            # print("Variants: ", new_wheel_product.variants)

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_wheel_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                   tags.add_tag(t)

            new_wheel_product.tags = tags.tags_to_string()
            new_wheel_product.save()

            if new_wheel_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                raise Exception("New Wheel Product Error:\n",new_wheel_product.errors.full_messages())


            wheelTools.add_wheel(product_id, wheel_variant)

            # TODO: Need to organize this code
            # Below is all for when there is a second bolt pattern

        # 2) Is not a variant
        else:
            # Update a product
            new_wheel_product = shopify.Product()
            new_wheel_product.options = [{'name': 'Tire Size'}, {'name': 'Bolt Pattern'}, {'name': 'Offset'}]
            new_wheel_product.title = wheel_variant.style_description
            new_wheel_product.vendor = "Wheel Pros"
            new_wheel_product.product_type = "Wheels"
            new_wheel_product.body_html = """<b>%s</b>
                                    <p>%s</p>
                                    """ % (wheel_variant.style_description,
                                           wheel_variant.part_number_description)
            variant = shopify.Variant({'price': wheel_variant.map_price,
                                       'option1': wheel_variant.size,
                                       'option2': bolt_pattern1,
                                       'option3': wheel_variant.offset,
                                       'quantity': 1,
                                       'sku': wheel_variant.upc,
                                       'position': 1,
                                       'inventory_policy': "deny",
                                       'fulfillment_service': "manual",
                                       'inventory_management': "shopify",
                                       'inventory_quantity': wheel_variant.curr_stock,
                                       'taxable': True,
                                       'weight': float(wheel_variant.shipping_weight),
                                       'weight_unit': "g",  # g, kg
                                       'requires_shipping': True})
            # TODO: Need to organize this code
            # Below is all for when there is a second bolt pattern
            variant2 = shopify.Variant({'price': wheel_variant.map_price,
                                       'option1': wheel_variant.size,
                                        'option2': bolt_pattern2,
                                        'option3': wheel_variant.offset,
                                       'quantity': 1,
                                       'sku': wheel_variant.upc,
                                       'position': 1,
                                       'inventory_policy': "deny",
                                       'fulfillment_service': "manual",
                                       'inventory_management': "shopify",
                                       'inventory_quantity': wheel_variant.curr_stock,
                                       'taxable': True,
                                       'weight': float(wheel_variant.shipping_weight),
                                       'weight_unit': "g",  # g, kg
                                       'requires_shipping': True})

            new_wheel_product.variants = [variant]
            if bolt_pattern2 != "":
                new_wheel_product.variants.append(variant2)

            new_wheel_product.tags = """WheelPros,Wheels"""

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_wheel_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_wheel_product.tags = tags.tags_to_string()

            image = shopify.Image()
            file_name = "%s" % wheel_variant.wheel_image
            if ShopifyTools.is_image_and_ready(file_name):
                image.src = file_name
            else:
                pass
                # Used to see when doesn't have an image
                # print(wheel_variant.upc)
                # print(wheel_variant.style_description)
                # print("-----------------")

            new_wheel_product.images = [image]
            new_wheel_product.save()

            wheelTools.add_wheel(new_wheel_product.id, wheel_variant)

            # print("PRODUCT ID: ", new_wheel_product.id)
            new_wheel_product.save()  # returns false if the record is invalid
            if new_wheel_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                raise Exception("New Wheel Product Error:\n",new_wheel_product.errors.full_messages())

        # Add to the database
        ShopifyToolsWheels.add_element(connection, "wheel_pros_wheels", f"('{new_wheel_product.id}', '{wheel_variant.style_description}', '{str(wheel_variant.upc)}', {wheel_variant.map_price}, '{wheel_variant.size}', '{bolt_pattern1}', '{wheel_variant.offset}', {wheel_variant.curr_stock}, {float(wheel_variant.shipping_weight)}, '{wheel_variant.wheel_image}', '{tags.tags_to_string()}')")
    def add_new_kit(kit_variant):
        # 2 cases
        # 1) Is a variant

        # Tags
        tags_to_add = []

        # Size
        tags_to_add.append("Size_" + kit_variant.get_size())
        tags_to_add.append(kit_variant.get_tire())
        tags_to_add.append(kit_variant.get_wheel())

        if kitTools.has_variants(kit_variant):
            product_id = kitTools.find_product_id(kit_variant)
            new_kit_product = shopify.Product.find(product_id)
            variant = shopify.Variant({
                'price': kit_variant.get_msrp(),
                'option1': kit_variant.get_wheel(),
                'option2': kit_variant.get_tire(),
                'sku': "a",
                'position': 1,
                'inventory_policy': "continue",
                'fulfillment_service': "manual",
                'inventory_management': "shopify",
                'inventory_quantity': 1,
                'taxable': False,
                'weight': 0,
                'weight_unit': "g",  # g, kg
                'requires_shipping': True
            })

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_kit_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_kit_product.tags = tags.tags_to_string()

            new_kit_product.variants.append(variant)
            new_kit_product.save()
            kitTools.add_kit(product_id, kit_variant)

            # TODO: Need to organize this code
            # Below is all for when there is a second bolt pattern

        # 2) Is not a variant
        else:
            # Update a product
            new_kit_product = shopify.Product()
            new_kit_product.options = [{'name': 'Wheel'}, {'name': 'Tire'}]
            new_kit_product.title = kit_variant.get_kit_name()
            new_kit_product.vendor = "Racks Deep Custom Performance"
            new_kit_product.product_type = "Kits"
            new_kit_product.body_html = """<b>%s</b>
                                            <h1>All Kits come mounted with new lugnuts</h1>
                                            """ % (kit_variant.get_kit_name())
            variant = shopify.Variant({
                'price': kit_variant.get_msrp(),
                'option1': kit_variant.get_wheel(),
                'option2': kit_variant.get_tire(),
                'sku': "a",
                'position': 1,
                'inventory_policy': "continue",
                'fulfillment_service': "manual",
                'inventory_management': "shopify",
                'inventory_quantity': 1,
                'taxable': False,
                'weight': 0,
                'weight_unit': "g",  # g, kg
                'requires_shipping': True
            })
            new_kit_product.variants = [variant]
            new_kit_product.tags = """WheelPros,
                                      Kits
                                      """

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_kit_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_kit_product.tags = tags.tags_to_string()

            #image = shopify.Image()
            #file_name = "%s" % (wheel_variant.get_wheel_image())
            #if ShopifyTools.is_image_and_ready(file_name):
            #    image.src = file_name
            # else:
            #    print(wheel_variant.get_upc)
            #    print(wheel_variant.get_style_description())
            #    print("-----------------")

            # new_wheel_product.images = [image]
            new_kit_product.save()

            kitTools.add_kit(new_kit_product.id, kit_variant)
            if new_kit_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                print(new_kit_product.errors.full_messages())
Esempio n. 16
0
    def process_item(self, item, of_color):
        """Check if item already exists. If not, create a new variant and add it."""
        skip = False

        similar_variants = 0
        for p in self._current_products[item[self.k("Style")]]:
            # if p.product_type != item[self.k("Category")]:
            #     skip = True
            #     continue
            # skip = False
            color_option = ""
            color = item[self.k("Color Name")].lower().strip()
            size_option = ""
            size = item[self.k("Size")].lower().strip()

            if len(p.options) >= 2:
                for option in p.options:
                    if option.name == 'Color':
                        color_option = 'option{}'.format(option.position)
                    if option.name == 'Size':
                        size_option = 'option{}'.format(option.position)
            else:
                size_option = 'option1'
                color_option = 'option2'

            if color_option and size_option:
                variant = None
                for v in p.variants:
                    c = v.attributes[color_option].lower()
                    cb = c == color
                    s = v.attributes[size_option].lower()
                    sb = s == size
                    if v.attributes[color_option].lower() == color \
                            and v.attributes[size_option].lower() == size:
                        variant = v
                        break
                if variant:
                    skip = True
                    if variant.id:
                        if self._sanmar:
                            # price = self.get_price(item)
                            price = self.get_price(item)
                            if price != variant.price:
                                variant.price = price
                                variant.save()
                            # if price != 0 and price != "":
                            #     variant.price = price

                        self._shopify_ids[str(item[self.k("Item Number")])] = {
                            "variant_id": variant.id,
                            "product_id": p.id
                        }
                        key = 'sanmar' if self._sanmar else 'alpha'
                        inum = str(item[self.k("Item Number")])
                        self._product_ids.setdefault(str(p.id), {}).setdefault(
                            str(variant.id), {})[key] = inum
                    break
        product = None
        for p in self._current_products[item[self.k("Style")]]:
            if len(p.variants) + of_color - similar_variants < 100:
                product = p
                break

        skip = True
        if not skip:
            if not product:
                product = self.new_product(
                    item[self.k("Mill Name")], item[self.k("Style")],
                    self.get_description_short(item),
                    item[self.k("Full Feature Description")],
                    item[self.k("Category")],
                    len(self._current_products[item[self.k("Style")]]))

            color_option = ""
            size_option = ""
            try:
                color_option = [
                    'option{}'.format(o.position) for o in product.options
                    if o.name.lower() == "color"
                ][0]
                size_option = [
                    'option{}'.format(o.position) for o in product.options
                    if o.name.lower() == "size"
                ][0]
            except IndexError:
                size_option = 'option1'
                color_option = 'option2'

            # If total variants, plus the all of that color, mines the ones already made with the same color >= 100
            # then a new product needs created. Shopify limits 100 variants / product.
            color = item[self.k("Color Name")].lower().strip()
            similar_variants = len([
                v for v in product.variants
                if str(v.attributes[color_option]).lower() == color
            ])
            if len(product.variants) + of_color - similar_variants >= 100:
                for x in range(
                        len(self._current_products[item[self.k("Style")]])):
                    if product.id == self._current_products[item[self.k(
                            "Style")]][x].id:
                        self._current_products[item[self.k(
                            "Style")]][x] = product
                        break

                size_option = 'option1'
                color_option = 'option2'
                product = self.new_product(
                    item[self.k("Mill Name")], item[self.k("Style")],
                    self.get_description_short(item),
                    item[self.k("Full Feature Description")],
                    item[self.k("Category")],
                    len(self._current_products[item[self.k("Style")]]))

            price = self.get_price(item)

            variant = shopify.Variant({
                color_option:
                item[self.k("Color Name")].title().strip(),
                size_option:
                item[self.k("Size").strip()],
                'product_id':
                product.id
            })
            self._images[item[self.k("Front of Image Name")]] = {
                "product_id": product.id
            }
            if price != 0 and price != "":
                variant.price = price
            product.variants.append(variant)

            found = False
            for x in range(len(self._current_products[item[self.k("Style")]])):
                if product.id == self._current_products[item[self.k(
                        "Style")]][x].id:
                    self._current_products[item[self.k("Style")]][x] = product
                    found = True
                    break
            if not found:
                self._current_products[item[self.k("Style")]].append(product)
Esempio n. 17
0
    def add_new_product(filter_variant):
        """
        Method that adds a new Wheel Pros Tire to Shopify
        :param ds18_variant: Tire to add:
        :return: Returns nothing
        """
        # TODO: Need to find a way to stream line this
        # TODO: Comment out the method

        # Make the tags that we want to add
        tags_to_add = []
        # Brand
        #print(filter_variant)
        tags_to_add.append("Type_" +
                           str(filter_variant.get_prod_description()))

        # 2 cases
        # 1) Is a variant
        print(filter_variant)
        if filterTools.has_variants(filter_variant):
            product_id = filterTools.find_product_id(filter_variant)
            new_filter_product = shopify.Product.find(product_id)[0]
            print("Type of new_filter_project: ", type(new_filter_product))
            variant = shopify.Variant({
                'price':
                float(filter_variant.get_map_price()),
                'quantity':
                1,
                'sku':
                filter_variant.get_upc(),
                'position':
                1,
                'inventory_policy':
                'continue',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                1,
                'taxable':
                False,
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            # Get tags already put in
            tags = Tags()
            print("Type of new_filter_project: ", type(new_filter_product))
            tags.string_to_tags(new_filter_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_filter_product.tags = tags.tags_to_string()

            new_filter_product.tags = tags.tags_to_string()
            new_filter_product.variants.append(variant)
            new_filter_product.save()
            if new_filter_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                new_filter_product.errors.full_messages()
            filterTools.add_product(product_id, filter_variant)
            # 2) Is not a variant
        else:
            print(filter_variant)
            new_filter_product = shopify.Product()
            # Built the tire name
            new_filter_product.title = filter_variant.get_prod_description()
            new_filter_product.vendor = 'S&B Filters'
            new_filter_product.product_type = 'Filters'
            new_filter_product.body_html = """%s
                                   """ % (
                filter_variant.get_prod_description())
            variant = shopify.Variant({
                'price':
                float(filter_variant.get_map_price()),
                'quantity':
                1,
                'sku':
                filter_variant.get_upc(),
                'position':
                1,
                'inventory_policy':
                'continue',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                1,
                'taxable':
                False,
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            new_filter_product.variants = [variant]

            new_filter_product.tags = """S&B Filters,
                       Filters"""

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_filter_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_filter_product.tags = tags.tags_to_string()

            url_for_image = filter_variant.get_image_url().split("|")[0]
            print("The image: ", url_for_image)

            # if not ShopifyToolsFilter.url_is_alive(url_for_image):
            #    url_for_image = "https://sandbfilters.s3.us-east-2.amazonaws.com/" + filter_variant.get_part_num() + ".png"

            image = shopify.Image()
            image.src = url_for_image
            new_filter_product.images = [image]

            filterTools.add_product(new_filter_product.id, filter_variant)
            new_filter_product.save()  # returns false if the record is invalid
            if new_filter_product.errors:
                print("Hello")
                # something went wrong, see new_product.errors.full_messages() for example
                new_filter_product.errors.full_messages()
Esempio n. 18
0
  def post(self, request, *args, **kwargs):
    reseller_id = kwargs['accountId']
    dzero = decimal.Decimal(0)

    consignor_id = request.data.get('consignorId')
    category_id = request.data.get('categoryId')
    title = request.data.get('title')

    price = request.data.get('price', dzero)
    price = price if price else dzero

    retail_price = request.data.get('retailPrice', dzero)
    retail_price = retail_price if retail_price else dzero

    cost_net = request.data.get('costNet', dzero)
    cost_net = cost_net if cost_net else dzero

    quantity = request.data.get('quantity', 0)
    tag_quantity = request.data.get('tagQuantity', 0)

    item_fee = request.data.get('itemFee', dzero)
    item_fee = item_fee if item_fee else dzero

    allow_donate = request.data.get('allowDonate', False)
    featured_product = request.data.get('featuredProduct', False)

    shipping_handling = request.data.get('shippingHandling', dzero)
    shipping_handling = shipping_handling if shipping_handling else dzero

    web_fee = request.data.get('webFee', dzero)
    web_fee = web_fee if web_fee else dzero

    weight = request.data.get('weight', 0)
    width = request.data.get('width', 0)
    height = request.data.get('height', 0)
    date_received = request.data.get('dateReceived', datetime.datetime.now(datetime.timezone.utc))
    date_updated = datetime.datetime.now(datetime.timezone.utc)
    list_ready = request.data.get('listReady', False)
    post_date = datetime.datetime.now(datetime.timezone.utc)

    description = request.data.get('description', '')

    reseller = Reseller.objects.filter(pk=reseller_id).first()
    consignor = Consignor.objects.filter(pk=consignor_id).first()
    category = Category.objects.filter(pk=category_id).first()

    item = Item(
      reseller=reseller,
      consignor=consignor,
      category=category,
      title=title,
      price=price,
      retail_price=retail_price,
      cost_net=cost_net,
      quantity=quantity,
      tag_quantity=tag_quantity,
      item_fee=item_fee,
      allow_donate=allow_donate,
      featured_product=featured_product,
      shipping_handling=shipping_handling,
      web_fee=web_fee,
      weight=weight,
      width=width,
      height=height,
      date_received=date_received,
      list_ready=list_ready,
      post_date=post_date,
      date_updated=date_updated,
      status='NEW'
    )
      
    item.save()

    attributes = request.data.get('attributes')
    attributes = json.loads(attributes)

    for a in attributes:
      print(a)
      attribute_id = a['attributeId']
      attribute = Attributes.objects.filter(pk=attribute_id).first()
      ItemAttributes(reseller=reseller, item=item, attribute=attribute, value=a['value']).save()

    session = shopify.Session(reseller.domain, '2019-04', reseller.shopify_access_token)
    shopify.ShopifyResource.activate_session(session)
    new_product = shopify.Product()
    new_product.title = title
    new_product.product_type = category.json()['displayName']
    description = """
        <strong> {0} </strong>
        <br /><br />
        """.format(description)

    new_product.save()

    variant_object = {
            "product_id": new_product.id,
            "inventory_quantity": str(quantity),
            "price": str(price),
            "weight": weight
        }

    for a in attributes:
      attribute_id = a['attributeId']
      attribute = Attributes.objects.filter(pk=attribute_id).first()
      new_product.add_metafield(shopify.Metafield({
        'namespace': 'attribute',
        'key': attribute.json()['name'],
        'value': a['value'],
        'value_type': 'string',
      }))
      variant_object[attribute.json()['name']] = a['value']
      description = """
        {0}
        <strong> {1} </strong>: {2}
        <br />
      """.format(description, attribute.json()['name'], a['value'])

    variant = shopify.Variant(variant_object)
    variant.save()
    new_product.body_html = description
    new_product.add_variant(variant)
      
    new_product.save()

    item.description = description
    item.save()

    for image in request.data.getlist('image'):
      file_type = image.name.rsplit('.', 1)[1]
      photo = ItemPhotos(reseller=reseller, item=item, file_type=file_type)
      photo.save()
      photo_json = photo.json()
      content_type = "image/" + photo.file_type
      response = self.spaces_client.put_object(
          Body=image,  # Path to local file
          Bucket=photo_json['bucket'],  # Name of Space
          Key=photo_json['url'],
          ACL='public-read',
          ContentType=content_type)

    return Response(status=status.HTTP_201_CREATED)
Esempio n. 19
0
    def add_new_tire(connection, tire_variant):
        """
        Method that adds a new Wheel Pros Tire to Shopify
        :param tire_variant: Tire to add:
        :return: Returns nothing
        """
        # TODO: Need to find a way to stream line this
        # TODO: Comment out the method

        # Make the tags that we want to add
        tags_to_add = []
        # Ply
        if tire_variant.get_ply() != "0":
            tags_to_add.append("Ply_" + tire_variant.get_ply())
        # Speed Rating
        # tags_to_add.append("Speed Rating_"+tire_variant.get_speed_rating())
        # Rim Diameter
        tags_to_add.append("Rim Diameter_" + tire_variant.get_rim_diameter() +
                           "\"")
        # Tire Diameter
        # tags_to_add.append("Tire Diameter_"+tire_variant.get_tire_diameter())
        # Full Model Name
        # tags_to_add.append("Model_"+tire_variant.get_full_model_name())
        # Construction Type
        tags_to_add.append("Construction Type_" +
                           tire_variant.get_construction_type())
        # Terrain
        tags_to_add.append("Terrain_" + tire_variant.get_terrain())

        # Need to find out the correct price
        if float(tire_variant.get_map_price()) == 0:
            price_for_tire = tire_variant.get_mrsp_price()
        else:
            price_for_tire = tire_variant.get_map_price()

        #Need to take out certain parts and change option1
        option1 = tire_variant.get_tire_size_description()
        option1 = option1.replace("R", "X")
        option1 = option1.replace("LT", "")
        option1 = option1.replace("-", "X")

        # 2 cases
        # 1) Is a variant
        if tireTools.has_variants(tire_variant):
            product_id = tireTools.find_product_id(tire_variant)
            new_tire_product = shopify.Product.find(product_id)
            variant = shopify.Variant({
                'price':
                float(price_for_tire),
                'option1':
                option1,
                'quantity':
                1,
                'sku':
                tire_variant.get_upc(),
                'position':
                1,
                'inventory_policy':
                'deny',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                tire_variant.get_curr_stock(),
                'taxable':
                False,
                'weight':
                float(tire_variant.get_weight()),
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_tire_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_tire_product.tags = tags.tags_to_string()
            new_tire_product.variants.append(variant)
            new_tire_product.save()
            tireTools.add_tire(product_id, tire_variant)
            # 2) Is not a variant
        else:
            new_tire_product = shopify.Product()
            new_tire_product.options = [{'name': 'Tire Size'}]
            # Built the tire name
            new_tire_product.title = tire_variant.get_full_model_name()
            new_tire_product.vendor = 'Wheel Pros'
            new_tire_product.product_type = 'Tires'
            new_tire_product.body_html = """<b>%s</b>
                                   <p>%s</p>
                                   """ % (tire_variant.get_tire_description(),
                                          tire_variant.get_part_num())
            variant = shopify.Variant({
                'price':
                float(price_for_tire),
                'option1':
                option1,
                'quantity':
                1,
                'sku':
                tire_variant.get_upc(),
                'position':
                1,
                'inventory_policy':
                'deny',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                tire_variant.get_curr_stock(),
                'taxable':
                False,
                'weight':
                float(tire_variant.get_weight()),
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            new_tire_product.variants = [variant]

            new_tire_product.tags = """WheelPros,
                       Tires,
                       %s,
                       %s,
                       %s,
                       %s,""" % (tire_variant.get_full_model_name(),
                                 tire_variant.get_part_num(),
                                 tire_variant.get_tire_size(),
                                 tire_variant.get_upc())

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_tire_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            image = shopify.Image()
            file_name = tire_variant.get_picture_cd()
            image.src = file_name
            new_tire_product.images = [image]
            new_tire_product.save()

            tireTools.add_tire(new_tire_product.id, tire_variant)
            new_tire_product.save()  # returns false if the record is invalid
            if new_tire_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                new_tire_product.errors.full_messages()
            # Add to the database
        ShopifyToolsTires.add_element(
            connection, "wheel_pros_tires",
            f"('{new_tire_product.id}', '{tire_variant.get_full_model_name()}', '{tire_variant.upc}', {tire_variant.map_price}, '{option1}', '', '', {tire_variant.curr_stock}, {float(tire_variant.weight)}, '{tire_variant.get_picture_cd()}', '{tags.tags_to_string()}')"
        )
    def add_new_product(ds18_variant):
        """
        Method that adds a new Wheel Pros Tire to Shopify
        :param ds18_variant: Tire to add:
        :return: Returns nothing
        """
        # TODO: Need to find a way to stream line this
        # TODO: Comment out the method
        print(ds18_variant.get_model())

        # Make the tags that we want to add
        tags_to_add = []
        # Brand
        tags_to_add.append("Brand_" + ds18_variant.get_collection())

        # 2 cases
        # 1) Is a variant
        if ds18Tools.has_variants(ds18_variant):
            return
            product_id = ds18Tools.find_product_id(ds18_variant)
            new_ds18_product = shopify.Product.find(product_id)
            variant = shopify.Variant({
                'price':
                float(ds18_variant.get_msrp_price()),
                'quantity':
                1,
                'sku':
                ds18_variant.get_model(),
                'position':
                1,
                'inventory_policy':
                'continue',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                1,
                'taxable':
                False,
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_ds18_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_ds18_product.tags = tags.tags_to_string()

            new_ds18_product.tags = tags.tags_to_string()
            new_ds18_product.variants.append(variant)
            new_ds18_product.save()
            ds18Tools.add_product(product_id, ds18_variant)
            # 2) Is not a variant
        else:
            new_ds18_product = shopify.Product()
            # Built the tire name
            new_ds18_product.title = ds18_variant.get_name()
            new_ds18_product.vendor = 'DS 18'
            new_ds18_product.product_type = 'Sound'
            new_ds18_product.body_html = """<b>%s</b>
                                   <p>%s</p>
                                   """ % (ds18_variant.get_brand,
                                          ds18_variant.get_name())
            variant = shopify.Variant({
                'price':
                float(ds18_variant.get_msrp_price()),
                'quantity':
                1,
                'sku':
                ds18_variant.get_model(),
                'position':
                1,
                'inventory_policy':
                'continue',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                1,
                'taxable':
                False,
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            new_ds18_product.variants = [variant]

            new_ds18_product.tags = """DS18,
                       Sound"""

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_ds18_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_ds18_product.tags = tags.tags_to_string()

            image = shopify.Image()
            image.src = "https://ds18.s3.us-east-2.amazonaws.com/" + ds18_variant.get_model(
            ).replace("-", "").replace("/", "") + ".jpg"
            new_ds18_product.images = [image]

            ds18Tools.add_product(new_ds18_product.id, ds18_variant)
            new_ds18_product.save()  # returns false if the record is invalid
            if new_ds18_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                new_ds18_product.errors.full_messages()