def sync_item_image_handle (doc, site_doc, api_map, headers, image_path=None): # Check if we have image if (not image_path or image_path==''): frappe.throw('There is no image to sync') # Let's get the file image_file_data = frappe.get_doc("File Data", { "file_url": image_path, "attached_to_doctype": "Item", "attached_to_name": doc.get('name') }) if (image_file_data is None): frappe.throw('Cannot find image with path %s' %image_path) file_path = get_files_path() + '/' + image_file_data.get('file_name') # Push image onto oc server res = oc_requests(site_doc.get('server_base_url'), headers, api_map, 'Product Image', \ file_path=file_path, url_params={'id': doc.get(OC_PROD_ID)}, stop=True) if res: if (res.get('success')): doc.update({'last_sync_image': datetime.now()}) frappe.msgprint('Successfully updated product\'s image on Opencart') return doc.last_sync_image else: frappe.throw('Unknown error posting image. Image not updated %s' %json.dumps(res))
def sync_item_image_handle(doc, site_doc, api_map, headers, image_path=None): # Check if we have image if (not image_path or image_path == ''): frappe.throw('There is no image to sync') # Let's get the file image_file_data = frappe.get_doc( "File Data", { "file_url": image_path, "attached_to_doctype": "Item", "attached_to_name": doc.get('name') }) if (image_file_data is None): frappe.throw('Cannot find image with path %s' % image_path) file_path = get_files_path() + '/' + image_file_data.get('file_name') # Push image onto oc server res = oc_requests(site_doc.get('server_base_url'), headers, api_map, 'Product Image', \ file_path=file_path, url_params={'id': doc.get(OC_PROD_ID)}, stop=True) if res: if (res.get('success')): doc.update({'last_sync_image': datetime.now()}) frappe.msgprint( 'Successfully updated product\'s image on Opencart') return doc.last_sync_image else: frappe.throw('Unknown error posting image. Image not updated %s' % json.dumps(res))
def update_item_qty_handler(doc, site_doc, api_map, headers, silent=False): logs = [] success = False qty = get_item_qty(doc) # Cannot find product id -> cannot sync if (not doc.get(OC_PROD_ID)): sync_info(logs, 'Product ID for Opencart is missing', stop=True, silent=silent, error=True) data = [{ "product_id": doc.get(OC_PROD_ID), "quantity": str(cint(qty)) }] # Push qty to opencart res = oc_requests(site_doc.get('server_base_url'), headers, api_map, 'Product Quantity', stop=False, data=data) if res: # Not successful if (not res.get('success')): sync_info(logs, 'Quantity for product %s not updated on Opencart. Error: %s' %(doc.get('name'), res.get('error')), stop=False, silent=silent, error=True) else: success = True sync_info(logs, 'Quantity for product %s successfully updated on Opencart'%doc.get('name'), stop=False, silent=silent) return { 'success': success, 'logs': logs }
def oc_delete_item (doc, site_doc, api_map, headers, method=None): # Push delete on oc server res = oc_requests(site_doc.get('server_base_url'), headers, api_map, 'Product Delete', url_params={'id': doc.get(OC_PROD_ID)}, stop=True) if res: # Not successful if (not res.get('success')): frappe.msgprint('Product not deleted on Opencart. Error: %s' %(res.get('error'))) else: frappe.msgprint('Product successfully deleted on Opencart')
def sync_all_items(server_base_url, api_map, header_key, header_value, silent=False): # Header headers = {} headers[header_key] = header_value # Query for items that has synced time < modified time items = frappe.db.sql("""select name, oc_product_id, item_code, item_name, description, \ oc_meta_keyword, oc_meta_description, oc_price, oc_enable, item_group, modified, last_sync_oc from `tabItem` where last_sync_oc<modified and oc_product_id is not null""") # Init results results = [] logs = [] success = False if (len(items)==0): sync_info(logs, 'All items are up to date', stop=True, silent=silent) else: data = [] names = [] for item in items: names.append("'"+item[0]+"'") data.append ({ "product_id": item[1], "model": item[2], "sku": item[2], "price": item[7] or 0, "status": item[8], "product_store": ["0"], "product_category": [item[9]], "product_description": { "1":{ "name": item[3], "meta_keyword" : item[5] or '', "meta_description" : item[6] or '', "description" : item[4] or '' } }, # Irrelevant "sort_order": "1", "tax_class_id": "1", "manufacturer_id": "1" }) results.append([item[2], item[3], item[1], item[10], item[11]]) # Bulk Update to server res = oc_requests(server_base_url, headers, api_map, 'Bulk Product Edit', data=data, stop=False, logs=logs, silent=silent) if res: # Success ? if (not res.get('success')): sync_info(logs, 'Some product not updated on Opencart. Error: %s' %(res.get('error')), stop=False, silent=silent) else: frappe.db.sql("""update `tabItem` set last_sync_oc = Now() where name in (%s)""" %(','.join(names))) sync_info(logs, '%d Product(s) successfully updated to Opencart site' %len(items), stop=False, silent=silent) success = True return { 'results': results, 'success': success, 'logs': logs }
def oc_delete_group (doc, site_doc, api_map, headers, method=None): # Delete are not allow if cannot connect to opencart res = oc_requests(site_doc.get('server_base_url'), headers, api_map, 'Category Delete', \ url_params={'id': doc.get(OC_CAT_ID)}, stop=True) if res: # Not successful if (not res.get('success')): frappe.msgprint('Category not deleted on Opencart. Error: %s' %(res.get('error'))) else: frappe.msgprint('Category successfully deleted on Opencart')
def oc_delete_group(doc, site_doc, api_map, headers, method=None): # Delete are not allow if cannot connect to opencart res = oc_requests(site_doc.get('server_base_url'), headers, api_map, 'Category Delete', \ url_params={'id': doc.get(OC_CAT_ID)}, stop=True) if res: # Not successful if (not res.get('success')): frappe.msgprint('Category not deleted on Opencart. Error: %s' % (res.get('error'))) else: frappe.msgprint('Category successfully deleted on Opencart')
def oc_delete_item(doc, site_doc, api_map, headers, method=None): # Push delete on oc server res = oc_requests(site_doc.get('server_base_url'), headers, api_map, 'Product Delete', url_params={'id': doc.get(OC_PROD_ID)}, stop=True) if res: # Not successful if (not res.get('success')): frappe.msgprint('Product not deleted on Opencart. Error: %s' % (res.get('error'))) else: frappe.msgprint('Product successfully deleted on Opencart')
def oc_validate_group(doc, site_doc, api_map, headers, method=None): # Update is allowed even when opencart is down is_updating = doc.get(OC_CAT_ID) and doc.get(OC_CAT_ID) > 0 data = { "sort_order": "1", "parent_id": "0", "status": doc.get('enable_on_opencart'), "category_store": ["0"], "category_description": { "1": { "name": doc.get('name'), "description": doc.get('opencart_description') or "", "meta_keyword": doc.get('opencart_meta_keyword') or "", "meta_description": doc.get('opencart_meta_description') or "", } }, "keyword": ','.join(["category", doc.get('name')]), "column": "1" } # Get API obj api_name = 'Category Edit' if is_updating else 'Category Add' api_params = {'id': doc.get(OC_CAT_ID)} if is_updating else None # Push change to server res = oc_requests(site_doc.get('server_base_url'), headers, api_map, api_name, \ url_params = api_params, data=data) if res: # Check success action = 'updated' if is_updating else 'added' if (not res.get('success')): frappe.msgprint('Category not %s. Error: %s' % (action, res.get('error'))) else: if (not is_updating): doc.update({OC_CAT_ID: res.get('category_id')}) doc.opencart_last_sync = datetime.now() frappe.msgprint('Category successfully %s' % action)
def oc_validate_group (doc, site_doc, api_map, headers, method=None): # Update is allowed even when opencart is down is_updating = doc.get(OC_CAT_ID) and doc.get(OC_CAT_ID) > 0 data = { "sort_order": "1", "parent_id": "0", "status": doc.get('enable_on_opencart'), "category_store": ["0"], "category_description": { "1":{ "name": doc.get('name'), "description" : doc.get('opencart_description') or "", "meta_keyword" : doc.get('opencart_meta_keyword') or "", "meta_description" : doc.get('opencart_meta_description') or "", } }, "keyword": ','.join(["category", doc.get('name')]), "column": "1" } # Get API obj api_name = 'Category Edit' if is_updating else 'Category Add' api_params = {'id': doc.get(OC_CAT_ID)} if is_updating else None # Push change to server res = oc_requests(site_doc.get('server_base_url'), headers, api_map, api_name, \ url_params = api_params, data=data) if res: # Check success action = 'updated' if is_updating else 'added' if (not res.get('success')): frappe.msgprint('Category not %s. Error: %s' %(action, res.get('error'))) else: if (not is_updating): doc.update({OC_CAT_ID: res.get('category_id')}) doc.opencart_last_sync= datetime.now() frappe.msgprint('Category successfully %s'%action)
def oc_validate_item(doc, site_doc, api_map, headers, method=None): # Get the group product_categories = [] root_group = site_doc.get('root_item_group') if (doc.get('item_group') == root_group): product_categories.append(0) else: # Check valid group valid_groups = [x[0] for x in get_child_groups(root_group)] valid_groups.append(root_group) # Check if current group is valid if (doc.get('item_group') not in valid_groups): raise Exception( 'To be able to sold on selected Ecommerce site, Item Group must be one of the followings: %s' % str(valid_groups)) # Check if the group already synced first time item_group = frappe.get_doc("Item Group", doc.get('item_group')) if (not item_group.get(OC_CAT_ID)): raise Exception( 'Category you selected has not been synced to opencart. Please do a manual sync <a href="%s">here</a> ' % str(site_doc.get_url())) product_categories.append(item_group.get(OC_CAT_ID)) # Pass validation is_updating = doc.get(OC_PROD_ID) and doc.get(OC_PROD_ID) > 0 # Get quantity qty = get_item_qty(doc) data = { "model": doc.get('item_code'), "sku": doc.get('item_code'), "price": doc.get('oc_price'), "status": doc.get('oc_enable'), "quantity": str(cint(qty)), "product_store": ["0"], "product_category": product_categories, "product_description": { "1": { "name": doc.get('item_name'), "meta_keyword": doc.get('oc_meta_keyword') or '', "meta_description": doc.get('oc_meta_description') or '', "description": doc.get('description') or '' } }, # Irrelevant "sort_order": "1", "tax_class_id": "1", "manufacturer_id": "1" } # Get API obj api_name = 'Product Edit' if is_updating else 'Product Add' api_params = {'id': doc.get(OC_PROD_ID)} if is_updating else None # Push change to server res = oc_requests(site_doc.get('server_base_url'), headers, api_map, api_name, data=data, url_params=api_params) if res: # Check success action = 'updated' if is_updating else 'added' if (not res.get('success')): frappe.msgprint('Product not %s on Opencart. Error: %s' % (action, res.get('error'))) else: doc.update({'last_sync_oc': datetime.now()}) if (not is_updating): doc.update({OC_PROD_ID: res.get('product_id')}) frappe.msgprint('Product successfully %s on Opencart' % action)
def sync_all_items(server_base_url, api_map, header_key, header_value, silent=False): # Header headers = {} headers[header_key] = header_value # Query for items that has synced time < modified time items = frappe.db.sql( """select name, oc_product_id, item_code, item_name, description, \ oc_meta_keyword, oc_meta_description, oc_price, oc_enable, item_group, modified, last_sync_oc from `tabItem` where last_sync_oc<modified and oc_product_id is not null""" ) # Init results results = [] logs = [] success = False if (len(items) == 0): sync_info(logs, 'All items are up to date', stop=True, silent=silent) else: data = [] names = [] for item in items: names.append("'" + item[0] + "'") data.append({ "product_id": item[1], "model": item[2], "sku": item[2], "price": item[7] or 0, "status": item[8], "product_store": ["0"], "product_category": [item[9]], "product_description": { "1": { "name": item[3], "meta_keyword": item[5] or '', "meta_description": item[6] or '', "description": item[4] or '' } }, # Irrelevant "sort_order": "1", "tax_class_id": "1", "manufacturer_id": "1" }) results.append([item[2], item[3], item[1], item[10], item[11]]) # Bulk Update to server res = oc_requests(server_base_url, headers, api_map, 'Bulk Product Edit', data=data, stop=False, logs=logs, silent=silent) if res: # Success ? if (not res.get('success')): sync_info(logs, 'Some product not updated on Opencart. Error: %s' % (res.get('error')), stop=False, silent=silent) else: frappe.db.sql( """update `tabItem` set last_sync_oc = Now() where name in (%s)""" % (','.join(names))) sync_info( logs, '%d Product(s) successfully updated to Opencart site' % len(items), stop=False, silent=silent) success = True return {'results': results, 'success': success, 'logs': logs}
def sync_child_groups(item_group_name, site_name, server_base_url, api_map, header_key, header_value, silent=False): # item_group = frappe.get_doc("Item Group", item_group_name) logs = [] # Check if any is not updated count = frappe.db.sql("""select count(*) from \ (select if(opencart_last_sync + INTERVAL %(buffer)s SECOND > modified, 1, 0) as updated \ from `tabItem Group` where lft>%(lft)s and rgt<=%(rgt)s) as cat_tbl where cat_tbl.updated=0""", {"lft": item_group.lft, "rgt": item_group.rgt, "buffer": OC_CAT_SYNC_BUFFER}) # Init for result results = {} results_list = [] update_count = 0 add_count = 0 success = True # Skip if everything is up to date if (count[0][0]==0): sync_info(logs, 'All items groups are up to date', stop=True, silent=silent) else: # site_doc = frappe.get_doc("Opencart Site", site_name) groups = frappe.db.sql("""select name, if(opencart_last_sync + INTERVAL %(buffer)s SECOND > modified, 1, 0) as updated \ from `tabItem Group` where lft>%(lft)s and rgt<=%(rgt)s order by lft asc""", {"lft": item_group.lft, "rgt": item_group.rgt, "buffer": OC_CAT_SYNC_BUFFER}) # Header headers = {} headers[header_key] = header_value # Loop through group and update for group in groups: group_name, group_updated = group group_doc = frappe.get_doc("Item Group", group_name) # Check if it synced already 2 sec buffer. # Because we save using code the modified get updated after last_sync time if (group_updated): extras = (1, 'updated', 'Updated') else: extras = (0, 'not-updated', 'Not Updated') # Parent category parent_id = "0" if group_doc.get('parent_item_group')!=item_group_name: parent_doc = frappe.get_doc("Item Group", group_doc.get('parent_item_group')) parent_id = parent_doc.get('opencart_category_id') # Sync with oc is_updating = group_doc.get(OC_CAT_ID) and group_doc.get(OC_CAT_ID) > 0 data = { "sort_order": "1", "parent_id": parent_id, "status": group_doc.get('enable_on_opencart'), "category_store": ["0"], "category_description": { "1":{ "name": group_doc.get('name'), "description" : group_doc.get('opencart_description') or "", "meta_keyword" : group_doc.get('opencart_meta_keyword') or "", "meta_description" : group_doc.get('opencart_meta_description') or "", } }, "keyword": ','.join(["category", group_doc.get('name')]), # Prevent error from "column": "1" } # Get API obj api_name = 'Category Edit' if is_updating else 'Category Add' api_params = {'id': group_doc.get(OC_CAT_ID)} if is_updating else None # Push change to server res = oc_requests(server_base_url, headers, api_map, api_name, url_params=api_params, data=data, logs=logs, silent=silent, stop=False) if res is None or res.get('success')==False: success = False sync_info(logs, "Failed to update/add item group: %s. Error: %s"%(group_name, \ res.get('error') if hasattr(res, 'error') else 'Unknown error'), error=True, silent=silent) # Handle response else: updating_props = { "sell_on_opencart": True, "opencart_site": site_name, "opencart_last_sync": datetime.now() } if not group_doc.opencart_category_id: updating_props.update({"opencart_category_id": res.get('category_id')}) group_doc.update(updating_props) group_doc.ignore_validate=True group_doc.save() # Add count if (is_updating): update_count+=1 extras = (group_updated, 'just-updated', 'Just Updated') sync_info(logs, "Successfully updated item group: %s."%(group_name), error=False, silent=True) else: add_count+=1 extras = (group_updated, 'just-added', 'Just Added') sync_info(logs, "Successfully added item group: %s."%(group_name), error=False, silent=True) # Update images as well, optional sync_group_image_handle (group_doc, site_doc, api_map, headers) # Append results results_list.append((group_doc.get('name'), group_doc.get('parent_item_group'), \ group_doc.get('opencart_category_id'), group_doc.get_formatted('opencart_last_sync'), \ group_doc.get('modified'))+extras) results = { 'add_count': add_count, 'update_count': update_count, 'results': results_list, 'success': success, 'logs': logs } return results
def sync_child_groups(item_group_name, site_name, server_base_url, api_map, header_key, header_value, silent=False): # item_group = frappe.get_doc("Item Group", item_group_name) logs = [] # Check if any is not updated count = frappe.db.sql( """select count(*) from \ (select if(opencart_last_sync + INTERVAL %(buffer)s SECOND > modified, 1, 0) as updated \ from `tabItem Group` where lft>%(lft)s and rgt<=%(rgt)s) as cat_tbl where cat_tbl.updated=0""", { "lft": item_group.lft, "rgt": item_group.rgt, "buffer": OC_CAT_SYNC_BUFFER }) # Init for result results = {} results_list = [] update_count = 0 add_count = 0 success = True # Skip if everything is up to date if (count[0][0] == 0): sync_info(logs, 'All items groups are up to date', stop=True, silent=silent) else: # site_doc = frappe.get_doc("Opencart Site", site_name) groups = frappe.db.sql( """select name, if(opencart_last_sync + INTERVAL %(buffer)s SECOND > modified, 1, 0) as updated \ from `tabItem Group` where lft>%(lft)s and rgt<=%(rgt)s order by lft asc""", { "lft": item_group.lft, "rgt": item_group.rgt, "buffer": OC_CAT_SYNC_BUFFER }) # Header headers = {} headers[header_key] = header_value # Loop through group and update for group in groups: group_name, group_updated = group group_doc = frappe.get_doc("Item Group", group_name) # Check if it synced already 2 sec buffer. # Because we save using code the modified get updated after last_sync time if (group_updated): extras = (1, 'updated', 'Updated') else: extras = (0, 'not-updated', 'Not Updated') # Parent category parent_id = "0" if group_doc.get('parent_item_group') != item_group_name: parent_doc = frappe.get_doc( "Item Group", group_doc.get('parent_item_group')) parent_id = parent_doc.get('opencart_category_id') # Sync with oc is_updating = group_doc.get( OC_CAT_ID) and group_doc.get(OC_CAT_ID) > 0 data = { "sort_order": "1", "parent_id": parent_id, "status": group_doc.get('enable_on_opencart'), "category_store": ["0"], "category_description": { "1": { "name": group_doc.get('name'), "description": group_doc.get('opencart_description') or "", "meta_keyword": group_doc.get('opencart_meta_keyword') or "", "meta_description": group_doc.get('opencart_meta_description') or "", } }, "keyword": ','.join(["category", group_doc.get('name')]), # Prevent error from "column": "1" } # Get API obj api_name = 'Category Edit' if is_updating else 'Category Add' api_params = { 'id': group_doc.get(OC_CAT_ID) } if is_updating else None # Push change to server res = oc_requests(server_base_url, headers, api_map, api_name, url_params=api_params, data=data, logs=logs, silent=silent, stop=False) if res is None or res.get('success') == False: success = False sync_info(logs, "Failed to update/add item group: %s. Error: %s"%(group_name, \ res.get('error') if hasattr(res, 'error') else 'Unknown error'), error=True, silent=silent) # Handle response else: updating_props = { "sell_on_opencart": True, "opencart_site": site_name, "opencart_last_sync": datetime.now() } if not group_doc.opencart_category_id: updating_props.update( {"opencart_category_id": res.get('category_id')}) group_doc.update(updating_props) group_doc.ignore_validate = True group_doc.save() # Add count if (is_updating): update_count += 1 extras = (group_updated, 'just-updated', 'Just Updated') sync_info(logs, "Successfully updated item group: %s." % (group_name), error=False, silent=True) else: add_count += 1 extras = (group_updated, 'just-added', 'Just Added') sync_info(logs, "Successfully added item group: %s." % (group_name), error=False, silent=True) # Update images as well, optional sync_group_image_handle(group_doc, site_doc, api_map, headers) # Append results results_list.append((group_doc.get('name'), group_doc.get('parent_item_group'), \ group_doc.get('opencart_category_id'), group_doc.get_formatted('opencart_last_sync'), \ group_doc.get('modified'))+extras) results = { 'add_count': add_count, 'update_count': update_count, 'results': results_list, 'success': success, 'logs': logs } return results
def oc_validate_item (doc, site_doc, api_map, headers, method=None): # Get the group product_categories = [] root_group = site_doc.get('root_item_group') if (doc.get('item_group') == root_group): product_categories.append(0) else: # Check valid group valid_groups = [x[0] for x in get_child_groups(root_group)] valid_groups.append(root_group) # Check if current group is valid if (doc.get('item_group') not in valid_groups): raise Exception('To be able to sold on selected Ecommerce site, Item Group must be one of the followings: %s'%str(valid_groups)) # Check if the group already synced first time item_group = frappe.get_doc("Item Group", doc.get('item_group')) if (not item_group.get(OC_CAT_ID)): raise Exception('Category you selected has not been synced to opencart. Please do a manual sync <a href="%s">here</a> '%str(site_doc.get_url())) product_categories.append(item_group.get(OC_CAT_ID)) # Pass validation is_updating = doc.get(OC_PROD_ID) and doc.get(OC_PROD_ID) > 0 # Get quantity qty = get_item_qty(doc) data = { "model": doc.get('item_code'), "sku": doc.get('item_code'), "price": doc.get('oc_price'), "status": doc.get('oc_enable'), "quantity": str(cint(qty)), "product_store": ["0"], "product_category": product_categories, "product_description": { "1":{ "name": doc.get('item_name'), "meta_keyword" : doc.get('oc_meta_keyword') or '', "meta_description" : doc.get('oc_meta_description') or '', "description" : doc.get('description') or '' } }, # Irrelevant "sort_order": "1", "tax_class_id": "1", "manufacturer_id": "1" } # Get API obj api_name = 'Product Edit' if is_updating else 'Product Add' api_params = {'id': doc.get(OC_PROD_ID)} if is_updating else None # Push change to server res = oc_requests(site_doc.get('server_base_url'), headers, api_map, api_name, data=data, url_params = api_params) if res: # Check success action = 'updated' if is_updating else 'added' if (not res.get('success')): frappe.msgprint('Product not %s on Opencart. Error: %s' %(action, res.get('error'))) else: doc.update({'last_sync_oc': datetime.now()}) if (not is_updating): doc.update({OC_PROD_ID: res.get('product_id')}) frappe.msgprint('Product successfully %s on Opencart'%action)