def sync_item_image(item):
    image_info = {"image": {}}

    if item.image:
        img_details = frappe.db.get_value("File", {"file_url": item.image},
                                          ["file_name", "content_hash"])

        if img_details and img_details[0] and img_details[1]:
            is_private = item.image.startswith("/private/files/")
            with open(
                    get_files_path(img_details[0].strip("/"),
                                   is_private=is_private), "rb") as image_file:
                image_info["image"]["attachment"] = base64.b64encode(
                    image_file.read())
            image_info["image"]["filename"] = img_details[0]

        elif item.image.startswith("http") or item.image.startswith("ftp"):
            image_info["image"]["src"] = item.image

        if image_info["image"]:
            try:
                if not exist_item_image(item.shopify_id, image_info):
                    post_request(
                        "/admin/products/{0}/images.json".format(
                            item.shopify_id), image_info)
            except ShopifyError:
                raise ShopifyError
def sync_erp_items(price_list, warehouse):
	for item in frappe.db.sql("""select item_code, item_name, item_group, description, has_variants, stock_uom from tabItem 
		where sync_with_shopify=1 and variant_of is null and shopify_id is null""", as_dict=1):
		variant_item_code_list = []
		
		item_data = {
					"product": {
						"title": item.get("item_code"),
						"body_html": item.get("description"),
						"product_type": item.get("item_group")
					}
				}
				
		if item.get("has_variants"):
			variant_list, options, variant_item_code = get_variant_attributes(item, price_list, warehouse)
			
			item_data["product"]["variants"] = variant_list
			item_data["product"]["options"] = options
			
			variant_item_code_list.extend(variant_item_code)
			
		else:
			item_data["product"]["variants"] = [get_price_and_stock_details(item, item.get("stock_uom"), warehouse, price_list)]
		new_item = post_request("/admin/products.json", item_data)
		erp_item = frappe.get_doc("Item", item.get("item_code"))
		erp_item.shopify_id = new_item['product'].get("id")
		erp_item.save()

		update_variant_item(new_item, variant_item_code_list)
def sync_item_image(item):
	image_info = {
        "image": {}
	}

	if item.image:
		img_details = frappe.db.get_value("File", {"file_url": item.image}, ["file_name", "content_hash"])

		if img_details and img_details[0] and img_details[1]:
			is_private = item.image.startswith("/private/files/")
			with open(get_files_path(img_details[0].strip("/"), is_private=is_private), "rb") as image_file:
			    image_info["image"]["attachment"] = base64.b64encode(image_file.read())
			image_info["image"]["filename"] = img_details[0]

		elif item.image.startswith("http") or item.image.startswith("ftp"):
			image_info["image"]["src"] = item.image

		if image_info["image"]:
			try:
				if not exist_item_image(item.shopify_id, image_info):
					post_request("/admin/products/{0}/images.json".format(item.shopify_id), image_info)
			except ShopifyError:
				raise ShopifyError
def sync_erp_customers():
	for customer in frappe.db.sql("""select name, customer_name from tabCustomer where ifnull(shopify_id, '') = ''
		and sync_with_shopify = 1 """, as_dict=1):
		cust = {
			"first_name": customer['customer_name']
		}

		addresses = frappe.db.sql("""select addr.address_line1 as address1, addr.address_line2 as address2,
						addr.city as city, addr.state as province, addr.country as country, addr.pincode as zip from
						tabAddress addr where addr.customer ='%s' """%(customer['customer_name']), as_dict=1)

		if addresses:
			cust["addresses"] = addresses

		cust = post_request("/admin/customers.json", { "customer": cust})

		customer = frappe.get_doc("Customer", customer['name'])
		customer.shopify_id = cust['customer'].get("id")
		customer.save()
def sync_erp_customers():
    for customer in frappe.db.sql(
            """select name, customer_name from tabCustomer where ifnull(shopify_id, '') = ''
		and sync_with_shopify = 1 """,
            as_dict=1):
        cust = {"first_name": customer['customer_name']}

        addresses = frappe.db.sql(
            """select addr.address_line1 as address1, addr.address_line2 as address2,
						addr.city as city, addr.state as province, addr.country as country, addr.pincode as zip from
						tabAddress addr where addr.customer ='%s' """ %
            (customer['customer_name']),
            as_dict=1)

        if addresses:
            cust["addresses"] = addresses

        cust = post_request("/admin/customers.json", {"customer": cust})

        customer = frappe.get_doc("Customer", customer['name'])
        customer.shopify_id = cust['customer'].get("id")
        customer.save()
	erp_item = frappe.get_doc("Item", item.get("item_code"))

	# check if the item really exists on shopify
	if item.get("shopify_id"):
		try:
			get_request("/admin/products/{}.json".format(item.get("shopify_id")))
		except requests.exceptions.HTTPError, e:
			if e.args[0] and e.args[0].startswith("404"):
				disable_shopify_sync(erp_item)
				return
			else:
				disable_shopify_sync(erp_item)
				raise
			
	if not item.get("shopify_id"):
		new_item = post_request("/admin/products.json", item_data)
		erp_item.shopify_id = new_item['product'].get("id")

		if not item.get("has_variants"):
			erp_item.shopify_variant_id = new_item['product']["variants"][0].get("id")

		erp_item.save()

		update_variant_item(new_item, variant_item_code_list)

	else:
		item_data["product"]["id"] = item.get("shopify_id")
		put_request("/admin/products/{}.json".format(item.get("shopify_id")), item_data)
				
	sync_item_image(erp_item)
    # check if the item really exists on shopify
    if item.get("shopify_id"):
        try:
            get_request("/admin/products/{}.json".format(
                item.get("shopify_id")))
        except requests.exceptions.HTTPError, e:
            if e.args[0] and e.args[0].startswith("404"):
                disable_shopify_sync(erp_item)
                return
            else:
                disable_shopify_sync(erp_item)
                raise

    if not item.get("shopify_id"):
        new_item = post_request("/admin/products.json", item_data)
        erp_item.shopify_id = new_item['product'].get("id")

        if not item.get("has_variants"):
            erp_item.shopify_variant_id = new_item['product']["variants"][
                0].get("id")

        erp_item.save()

        update_variant_item(new_item, variant_item_code_list)

    else:
        item_data["product"]["id"] = item.get("shopify_id")
        put_request("/admin/products/{}.json".format(item.get("shopify_id")),
                    item_data)