Example #1
0
def oc_validate(doc, method=None):
    site_name = doc.get('site_name')
    if not get(site_name):
        return

    # order status
    success, order_statuses = oc_api.get(site_name, use_pure_rest_api=True).get_order_statuses()
    if success:
        doc.update({
            'order_statuses_json': json.dumps(order_statuses)
        })

        # updating custom fields
        sales_order_oc_status = frappe.get_doc('Custom Field', 'Sales Order-oc_status')
        sales_order_oc_status.update({'options': '\n'.join(get_order_status_name_list(site_name))})
        sales_order_oc_status.save()

    # shipping methods
    success, shipping_methods = oc_api.get(site_name).get_shipping_methods()
    if success:
        doc.update({
            'shipping_methods_json': json.dumps(shipping_methods)
        })

    # payment methods
    success, payment_methods = oc_api.get(site_name).get_payment_methods()
    if success:
        doc.update({
            'payment_methods_json': json.dumps(payment_methods)
        })
Example #2
0
def test_connection(site_name):
    results = {}
    success, error = oc_api.get(site_name, use_pure_rest_api=True).check_connection()
    results['rest_api'] = {'success': success, 'error': error}
    success, error = oc_api.get(site_name, use_pure_rest_api=False).check_connection()
    results['rest_admin_api'] = {'success': success, 'error': error}
    return results
Example #3
0
def get_manufacturers(site_name):
    global OPENCART_MANUFACTURERS_CACHE
    manufacturers = OPENCART_MANUFACTURERS_CACHE.get(site_name)
    if manufacturers is None:
        manufacturers = list(oc_api.get(site_name).get_all_manufacturers())
        OPENCART_MANUFACTURERS_CACHE[site_name] = manufacturers
    return manufacturers
def pull(site_name, silent=False):
    '''Sync warehouses from Opencart site'''
    results = {}
    results_list = []
    check_count = 0
    update_count = 0
    add_count = 0
    skip_count = 0
    success = True

    oc_warehouse_success, oc_warehouses = oc_api.get(
        site_name, use_pure_rest_api=True).get_warehouse_json()
    for oc_warehouse in oc_warehouses:
        check_count += 1
        doc_oc_warehouse = get(site_name, oc_warehouse.get('warehouse_id'))
        if doc_oc_warehouse:
            # update existed Opencart Warehouse
            # check here for a need to update Opencart Warehouse
            params = {
                'warehouse_name': oc_warehouse.get('warehouse_name'),
                'oc_last_sync_from': datetime.now(),
            }
            doc_oc_warehouse.update(params)
            doc_oc_warehouse.save()
            update_count += 1
            extras = (1, 'updated', 'Updated')
            results_list.append(
                (doc_oc_warehouse.get('warehouse_name'),
                 doc_oc_warehouse.get('oc_warehouse_id'),
                 doc_oc_warehouse.get_formatted('oc_last_sync_from') or '',
                 doc_oc_warehouse.get('modified') or '') + extras)

        else:
            # creating new Opencart Warehouse
            params = {
                'doctype': 'Warehouse',
                'warehouse_name': oc_warehouse.get('warehouse_name'),
                'oc_site': site_name,
                'oc_warehouse_id': oc_warehouse.get('id'),
                'oc_sync_from': True,
                'oc_last_sync_from': datetime.now()
            }
            doc_oc_warehouse = frappe.get_doc(params)
            doc_oc_warehouse.insert(ignore_permissions=True)
            add_count += 1
            extras = (1, 'added', 'Added')
            results_list.append(
                (doc_oc_warehouse.get('warehouse_name'),
                 doc_oc_warehouse.get('oc_warehouse_id'),
                 doc_oc_warehouse.get_formatted('oc_last_sync_from') or '',
                 doc_oc_warehouse.get('modified') or '') + extras)
    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
def create_from_oc(site_name, customer_id, oc_order=None):
    if oc_order:
        customer_id = oc_order.get('customer_id')

    success, oc_customer = oc_api.get(site_name).get_customer(customer_id)

    if not success:
        frappe.throw('Cannot get Customer from Opencart site. Error: %s' % oc_customer.get('error') or 'Unknown')

    customer_group_id = oc_customer.get('customer_group_id', '')
    doc_customer_group = customer_groups.get(site_name, customer_group_id)

    if not doc_customer_group:
        frappe.throw('Could not found Customer Group with customer_group_id "%s"' % customer_group_id)

    default_price_list = doc_customer_group.get('default_price_list')
    territory_name = territories.DEFAULT
    if oc_order:
        if oc_order.get('shipping_iso_code_3') and oc_order.get('shipping_zone_code'):
            territory_name = territories.get_by_iso_code3(oc_order.get('shipping_iso_code_3'), oc_order.get('shipping_zone_code'))
        else:
            territory_name = territories.get_by_iso_code3(oc_order.get('payment_iso_code_3'), oc_order.get('payment_zone_code'))
    # create new Customer
    params = {
        'doctype': 'Customer',
        'customer_type': 'Individual',
        'territory': territory_name,
        'customer_name': make_full_name(oc_order.get('firstname'), oc_order.get('lastname')),
        'customer_group': doc_customer_group.get('name'),
        'naming_series': 'CUST-',
        'default_price_list': default_price_list,
        'oc_guest': 0,
        'oc_is_updating': 1,
        'oc_site': site_name,
        'oc_customer_id': customer_id,
        'oc_store_id': oc_customer.get('store_id') or '',
        'oc_status': 1,
        'oc_sync_from': True,
        'oc_last_sync_from': datetime.now(),
        'oc_sync_to': True,
        'oc_last_sync_to': datetime.now(),
        'oc_firstname': oc_order.get('firstname'),
        'oc_lastname': oc_order.get('lastname'),
        'oc_telephone': oc_order.get('telephone'),
        'oc_fax': oc_order.get('fax'),
        'oc_email': oc_order.get('email')
    }
    doc_customer = frappe.get_doc(params)
    doc_customer.insert(ignore_permissions=True)

    # addresses and contacts
    addresses.create_or_update(site_name, oc_customer, doc_customer)
    contacts.create_or_update(site_name, oc_customer, doc_customer)
    if oc_order:
        # addresses and contacts
        addresses.create_or_update_from_order(site_name, doc_customer, oc_order)
        contacts.create_or_update_from_order(site_name, doc_customer, oc_order)

    return doc_customer
def oc_delete(doc, method=None):
    site_name = doc.get('oc_site')
    oc_customer_id = doc.get('oc_customer_id')
    success, resp = oc_api.get(site_name).delete_customer(oc_customer_id)
    if success:
        frappe.msgprint('Customer was deleted successfully on Opencart site')
    else:
        frappe.throw('Customer is not deleted on Opencart site. Error: %s' % resp.get('error', 'Unknown'))
def pull(site_name, silent=False):
    '''Sync warehouses from Opencart site'''
    results = {}
    results_list = []
    check_count = 0
    update_count = 0
    add_count = 0
    skip_count = 0
    success = True

    oc_warehouse_success, oc_warehouses = oc_api.get(site_name, use_pure_rest_api=True).get_warehouse_json()
    for oc_warehouse in oc_warehouses:
        check_count += 1
        doc_oc_warehouse = get(site_name, oc_warehouse.get('warehouse_id'))
        if doc_oc_warehouse:
            # update existed Opencart Warehouse
            # check here for a need to update Opencart Warehouse
            params = {
                'warehouse_name': oc_warehouse.get('warehouse_name'),
                'oc_last_sync_from': datetime.now(),
            }
            doc_oc_warehouse.update(params)
            doc_oc_warehouse.save()
            update_count += 1
            extras = (1, 'updated', 'Updated')
            results_list.append((doc_oc_warehouse.get('warehouse_name'),
                                doc_oc_warehouse.get('oc_warehouse_id'),
                                doc_oc_warehouse.get_formatted('oc_last_sync_from') or '',
                                doc_oc_warehouse.get('modified') or '') + extras)

        else:
            # creating new Opencart Warehouse
            params = {
                'doctype': 'Warehouse',
                'warehouse_name': oc_warehouse.get('warehouse_name'),
                'oc_site': site_name,
                'oc_warehouse_id': oc_warehouse.get('id'),
                'oc_sync_from': True,
                'oc_last_sync_from': datetime.now()
            }
            doc_oc_warehouse = frappe.get_doc(params)
            doc_oc_warehouse.insert(ignore_permissions=True)
            add_count += 1
            extras = (1, 'added', 'Added')
            results_list.append((doc_oc_warehouse.get('warehouse_name'),
                                doc_oc_warehouse.get('oc_warehouse_id'),
                                doc_oc_warehouse.get_formatted('oc_last_sync_from') or '',
                                doc_oc_warehouse.get('modified') or '') + extras)
    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
Example #8
0
def get_oc_init(site_name):
    global OPENCART_INIT_CACHE
    init_data = OPENCART_INIT_CACHE.get(site_name)
    if not init_data:
        success, data = oc_api.get(site_name).get_init()
        if not success:
            frappe.throw('Exception: Cannot get init data from Opencart site "%s"' % site_name)
        OPENCART_INIT_CACHE[site_name] = data
        init_data = data
    return init_data
Example #9
0
def oc_delete(doc, method=None):
    for doc_oc_product in doc.get('oc_products'):
        if not doc_oc_product.get('oc_sync_to'):
            continue
        site_name = doc_oc_product.get('oc_site')
        oc_product_id = doc_oc_product.get('oc_product_id')
        success = oc_api.get(site_name).delete_product(oc_product_id)
        if success:
            frappe.msgprint('Product was deleted successfully on Opencart site "%s"' % site_name)
        else:
            frappe.throw('Product is not deleted on Opencart site "%s". Error: Unknown' % site_name)
Example #10
0
def daily(site_name=None):
    # Get all oc sites
    if site_name:
        site_names = [[site_name]]
    else:
        site_names = frappe.db.sql("""select name from `tabOpencart Site`""")
    results = {}
    logs = [
        "<b>Sync Log on date: %s</b>" % datetime.now().strftime("%d-%b-%y")
    ]
    success = True

    # Sync
    for name in site_names:
        name = name[0]
        logs.append("Opencart Site: %s" % name)
        site_doc = frappe.get_doc("Opencart Site", name)
        root_item_group = site_doc.get('root_item_group')
        opencart_api = oc_api.get(name)

        # Sync groups and record log
        logs.append("Sync Item Groups")
        group_results = pull_categories_from_oc(name,
                                                root_item_group,
                                                opencart_api,
                                                silent=True)
        results['groups'] = group_results
        # logs += results.get('logs')
        success = success and group_results.get('success')

        # Sync items and record log
        logs.append("Sync Items")
        item_results = pull_products_from_oc(name,
                                             root_item_group,
                                             opencart_api,
                                             silent=True)
        results['items'] = item_results
        # logs += results_item.get('logs')
        success = success and item_results.get('success')
        continue

        # Send mail if unsuccessful
        logs = ['<p>%s</p>' % x for x in logs]
        frappe.sendmail(recipients=[str(site_doc.get('user'))],
                        sender=EMAIL_SENDER,
                        subject=EMAIL_SUBJECT %
                        (datetime.now().strftime("%d-%b-%y"),
                         "succeeded" if success else "failed"),
                        message='</br>'.join(logs))

    results['success'] = success
    return results
Example #11
0
def daily(site_name=None):
    # Get all oc sites
    if site_name:
        site_names = [[site_name]]
    else:
        site_names = frappe.db.sql("""select name from `tabOpencart Site`""")
    results = {}
    logs = ["<b>Sync Log on date: %s</b>" % datetime.now().strftime("%d-%b-%y")]
    success = True

    # Sync
    for name in site_names:
        name = name[0]
        logs.append("Opencart Site: %s" % name)
        site_doc = frappe.get_doc("Opencart Site", name)
        root_item_group = site_doc.get("root_item_group")
        opencart_api = oc_api.get(name)

        # Sync groups and record log
        logs.append("Sync Item Groups")
        group_results = pull_categories_from_oc(name, root_item_group, opencart_api, silent=True)
        results["groups"] = group_results
        # logs += results.get('logs')
        success = success and group_results.get("success")

        # Sync items and record log
        logs.append("Sync Items")
        item_results = pull_products_from_oc(name, root_item_group, opencart_api, silent=True)
        results["items"] = item_results
        # logs += results_item.get('logs')
        success = success and item_results.get("success")
        continue

        # Send mail if unsuccessful
        logs = ["<p>%s</p>" % x for x in logs]
        frappe.sendmail(
            recipients=[str(site_doc.get("user"))],
            sender=EMAIL_SENDER,
            subject=EMAIL_SUBJECT % (datetime.now().strftime("%d-%b-%y"), "succeeded" if success else "failed"),
            message="</br>".join(logs),
        )

    results["success"] = success
    return results
Example #12
0
def push_image(doc):
    if not doc.image:
        return
    site_name = doc.get('oc_site')
    image_file_data = frappe.get_doc('File Data', {
        'file_url': doc.image,
        'attached_to_doctype': 'Item',
        'attached_to_name': doc.get('name')
    })
    if not image_file_data:
        frappe.throw('Cannot find image in file path "%s"' % doc.image)
    file_name = image_file_data.get('file_name')
    file_path = get_files_path() + '/' + file_name
    oc_product_id = doc.get('oc_product_id')
    success = oc_api.get(site_name).set_product_image(oc_product_id, file_path)
    if success:
        frappe.msgprint('Image "%s" was uploaded successfully to Opencart site' % file_name)
    else:
        frappe.msgprint('Image "%s" was not uploaded to Opencart site' % file_name)
Example #13
0
def pull(site_name, item_code=None, silent=False):
    '''Sync Item Prices from Opencart site'''
    results = {}
    results_list = []
    check_count = 0
    update_count = 0
    add_count = 0
    skip_count = 0
    success = True

    doc_stores = oc_stores.get_all(site_name)
    oc_api_cache = {}
    customer_groups_cache = {}

    for doc_store in doc_stores:
        if doc_store.get('oc_store_front_url') and doc_store.get(
                'oc_price_lists'):
            oc_api_cache[doc_store.get('name')] = oc_api.get(
                site_name, doc_store.get('oc_store_front_url'))
            print('store name=' + doc_store.get('oc_store_front_url'))
            # fill cache of customer groups
            for doc_oc_price_list in doc_store.get('oc_price_lists'):
                customer_group_name = doc_oc_price_list.get('customer_group')
                db_customer_group = frappe.db.get(
                    'Customer Group', {'name': customer_group_name})
                if not db_customer_group:
                    frappe.msgprint(
                        'Customer Group is not set for Opencart Price List in Opencart Store "%s"'
                        % doc_store.get('name'))
                    continue
                customer_groups_cache[db_customer_group.get(
                    'name')] = db_customer_group

    all_dict_items = []
    if item_code:
        all_dict_items = frappe.get_all(
            'Item',
            fields=['name', 'item_code'],
            filters={'item_code': item_code.upper()})
    else:
        all_dict_items = frappe.get_all('Item', fields=['name', 'item_code'])
    items_count_left_to_process = len(all_dict_items)
    for dict_item in all_dict_items:
        # for dict_item in [it for it in frappe.get_all('Item', fields=['name', 'item_code']) if it.get('name') == 'TESTAH']:
        item_code = dict_item.get('item_code')
        items_count_left_to_process -= 1
        print('processing %s, left to process %d' %
              (item_code or '', items_count_left_to_process))
        doc_oc_product = items.get_opencart_product(site_name,
                                                    dict_item.get('name'))
        if not doc_oc_product:
            skip_count += 1
            continue
        oc_product_id = doc_oc_product.get('oc_product_id')
        doc_item = frappe.get_doc('Item', dict_item.get('name'))
        for doc_store in doc_stores:
            oc_api_obj = oc_api_cache.get(doc_store.get('name'))
            if oc_api_obj:
                get_product_success, oc_product = oc_api_obj.get_product(
                    oc_product_id)
                if not get_product_success:
                    skip_count += 1
                    extras = (
                        1, 'skipped',
                        'Skipped: cannot get product with product_id %s' %
                        oc_product_id)
                    results_list.append(('', '', '', '', '') + extras)
                    continue
            # TODO
            # updating item for each store
            # items.update_item(site_name, doc_item, oc_product)
            for doc_oc_price_list in doc_store.get('oc_price_lists'):
                check_count += 1
                price_list_name = doc_oc_price_list.get('price_list')
                customer_group_name = doc_oc_price_list.get('customer_group')
                doc_price_list = frappe.get_doc('Price List', price_list_name)
                doc_item_price = get(item_code, price_list_name)

                # resolve price
                price = items.get_oc_product_price(
                    oc_product, doc_price_list.get('currency'))
                # price = float(oc_product.get('price', 0))
                customer_group_id = customer_groups_cache.get(
                    customer_group_name, {}).get('oc_customer_group_id')
                for discount in oc_product.get('discounts'):
                    if customer_group_id == discount.get(
                            'customer_group_id') and int(
                                discount.get('quantity', 0)) == 1:
                        # price = float(discount.get('price', 0))
                        price = items.get_oc_discount_price(
                            discount, doc_price_list.get('currency'))
                if doc_item_price:
                    # update existed Item Price
                    doc_item_price.update({
                        'price_list_rate': price,
                        'oc_is_updating': 1
                    })
                    doc_item_price.save()
                    update_count += 1
                    extras = (1, 'updated', 'Updated')
                    results_list.append(
                        (doc_item_price.get('name'),
                         doc_item_price.get('item_code'),
                         doc_item_price.get('price_list'),
                         doc_item_price.get('currency'),
                         doc_item_price.get('price_list_rate')) + extras)
                else:
                    # create new Item Price
                    params = {
                        'doctype': 'Item Price',
                        'oc_is_updating': 1,
                        'selling': 1,
                        'item_code': item_code,
                        'price_list': price_list_name,
                        'price_list_rate': price
                    }
                    doc_item_price = frappe.get_doc(params)
                    doc_item_price.insert(ignore_permissions=True)
                    add_count += 1
                    extras = (1, 'added', 'Added')
                    results_list.append(
                        (doc_item_price.get('name'),
                         doc_item_price.get('item_code'),
                         doc_item_price.get('price_list'),
                         doc_item_price.get('currency'),
                         doc_item_price.get('price_list_rate')) + extras)

                update_item(doc_item, doc_item_price)
        # get again updated Item and pushing it to Opencart site
        doc_item = frappe.get_doc('Item', doc_item.get('name'))
        items.push_item_to_oc(doc_item, site_name)

    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
def pull(site_name, silent=False):
    results = {}
    results_list = []
    check_count = 0
    add_count = 0
    update_count = 0
    skip_count = 0
    success = True

    site_doc = frappe.get_doc('Opencart Site', site_name)
    root_customer_group = site_doc.get('root_customer_group')
    opencart_api = oc_api.get(site_name)
    for oc_customer_group in opencart_api.get_customer_groups():
        check_count += 1
        doc_customer_group = get(site_name, oc_customer_group.id)
        if doc_customer_group:
            # update existed Customer Group
            db_customer_group = frappe.db.get('Customer Group', oc_customer_group.name)

            if db_customer_group:
                doc_customer_group = frappe.get_doc('Customer Group', oc_customer_group.name)
                params = {
                    'doctype': 'Customer Group',
                    'customer_group_name': oc_customer_group.name,
                    'description': oc_customer_group.description,
                    'oc_last_sync_from': datetime.now(),
                }
                doc_customer_group.update(params)
                doc_customer_group.save()
                update_count += 1
                extras = (1, 'updated', 'Updated')
                results_list.append((doc_customer_group.get('name'),
                                    doc_customer_group.get('parent_customer_group'),
                                    doc_customer_group.get('oc_customer_group_id'),
                                    doc_customer_group.get_formatted('oc_last_sync_from'),
                                    doc_customer_group.get('modified') or '') + extras)
            else:
                skip_count += 1
                extras = (1, 'skipped', 'Skipped: not found customer group by name')
                results_list.append((oc_customer_group.name, '',
                                    oc_customer_group.customer_group_id,
                                    '', '') + extras)
                continue
        else:
            params = {
                'doctype': 'Customer Group',
                'oc_site': site_name,
                'oc_customer_group_id': oc_customer_group.id,
                'customer_group_name': oc_customer_group.name,
                'description': oc_customer_group.description,
                'parent_customer_group': root_customer_group,
                'is_group': 'Yes',
                'oc_sync_from': True,
                'oc_last_sync_from': datetime.now(),
                'oc_sync_to': True,
                'oc_last_sync_to': datetime.now()
            }
            doc_customer_group = frappe.get_doc(params)

            # check if whether Customer Group name is unique or not
            if frappe.db.get('Customer Group', {'name': oc_customer_group.name}):
                skip_count += 1
                extras = (1, 'skipped', 'Skipped: duplicate name')
                results_list.append((oc_customer_group.name,
                                    doc_customer_group.get('parent_customer_group'),
                                    doc_customer_group.get('oc_customer_group_id'),
                                    doc_customer_group.get_formatted('oc_last_sync_from'),
                                    doc_customer_group.get('modified') or '') + extras)
                continue
            else:
                # creating new Customer Group
                doc_customer_group.insert(ignore_permissions=True)
                add_count += 1
                extras = (1, 'added', 'Added')
                results_list.append((doc_customer_group.get('name'),
                                    doc_customer_group.get('parent_customer_group'),
                                    doc_customer_group.get('oc_customer_group_id'),
                                    doc_customer_group.get_formatted('oc_last_sync_from'),
                                    doc_customer_group.get('modified') or '') + extras)
    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
Example #15
0
def pull_categories_from_oc(site_name, silent=False):
    results = {}
    results_list = []
    check_count = 0
    add_count = 0
    update_count = 0
    skip_count = 0
    success = True

    site_doc = frappe.get_doc('Opencart Site', site_name)
    root_item_group = site_doc.get('root_item_group')
    opencart_api = oc_api.get(site_name)
    doc_root_item_group = frappe.get_doc('Item Group', root_item_group)
    for oc_category in opencart_api.get_all_categories():
        # if not doc_root_item_group.get('oc_category_id'):
        #     doc_root_item_group.update({'oc_category_id': oc_category.id})
        #     doc_root_item_group.save()
        check_count += 1
        doc_item_group = get_item_group(site_name, oc_category.id)
        doc_parent_item_group = doc_root_item_group
        if oc_category.parent_id:
            doc_parent_item_group = get_item_group(site_name, oc_category.parent_id)

        if not doc_parent_item_group:
            skip_count += 1
            extras = (1, 'skipped', 'Skipped: parent group missed')
            results_list.append((oc_category.name, '', oc_category.id, '', '') + extras)
            continue

        if doc_item_group:
            # update existed Item Group
            params = {
                'description': oc_category.description,
                'show_in_website': 1,
                'parent_item_group': doc_parent_item_group.get('name'),
                'oc_last_sync_from': datetime.now()
            }
            doc_item_group.update(params)
            try:
                doc_item_group.save()
            except Exception as ex:
                update_count += 1
                extras = (1, 'updated', 'Updated: due to exception: %s' % str(ex))
                results_list.append((doc_item_group.get('name'),
                                    doc_item_group.get('parent_item_group'),
                                    doc_item_group.get('oc_category_id'),
                                    doc_item_group.get_formatted('oc_last_sync_from') or '',
                                    doc_item_group.get('modified') or '') + extras)
                continue
            update_count += 1
            extras = (1, 'updated', 'Updated')
            results_list.append((doc_item_group.get('name'),
                                 doc_item_group.get('parent_item_group'),
                                 doc_item_group.get('oc_category_id') or '',
                                 doc_item_group.get_formatted('oc_last_sync_from') or '',
                                 doc_item_group.get('modified') or '') + extras)
        else:
            # checking whether item group name is unique
            db_item_group = frappe.db.get('Item Group', {'name': oc_category.name})
            if db_item_group:
                # it means that the group with such name already exists
                # but the oc_category_id is missed or is different than from Opencart site
                doc_item_group = frappe.get_doc('Item Group', oc_category.name)
                skip_count += 1
                extras = (1, 'skipped', 'Skipped: duplicate name')
                results_list.append((oc_category.name, doc_parent_item_group.get('name'), oc_category.id, '', '') + extras)
                continue
            else:
                # creating new Item Group
                params = {
                    'doctype': 'Item Group',
                    'oc_site': site_name,
                    'item_group_name': oc_category.name,
                    'parent_item_group': doc_parent_item_group.get('name'),
                    'oc_category_id': oc_category.id,
                    'description': oc_category.description,
                    'show_in_website': 'Yes',
                    'oc_sync_from': True,
                    'oc_last_sync_from': datetime.now(),
                    'oc_sync_to': True,
                    'oc_last_sync_to': datetime.now(),
                    'is_group': 'Yes'
                }
                doc_item_group = frappe.get_doc(params)
                try:
                    doc_item_group.insert(ignore_permissions=True)
                except Exception as ex:
                    add_count += 1
                    extras = (1, 'added', 'Added: due to exception: %s' % str(ex))
                    results_list.append((doc_item_group.get('item_group_name'),
                                        doc_item_group.get('parent_item_group'),
                                        doc_item_group.get('oc_category_id') or '',
                                        doc_item_group.get_formatted('oc_last_sync_from') or '',
                                        doc_item_group.get('modified') or '') + extras)
                    continue
                add_count += 1
                extras = (1, 'added', 'Added')
                results_list.append((doc_item_group.get('name'),
                                    doc_item_group.get('parent_item_group'),
                                    doc_item_group.get('oc_category_id') or '',
                                    doc_item_group.get_formatted('oc_last_sync_from') or '',
                                    doc_item_group.get('modified') or '') + extras)
    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
Example #16
0
def pull_products_from_oc(site_name, silent=False):
    results = {}
    results_list = []
    check_count = 0
    update_count = 0
    add_count = 0
    skip_count = 0
    success = True

    site_doc = frappe.get_doc('Opencart Site', site_name)
    opencart_api = oc_api.get(site_name)
    items_default_warehouse = site_doc.get('items_default_warehouse')
    if not items_default_warehouse:
        sync_info([], 'Please specify a Default Warehouse and proceed.', stop=True, silent=silent)

    for oc_category in opencart_api.get_all_categories():
        doc_item_group = item_groups.get_item_group(site_name, oc_category.id)
        for oc_product in opencart_api.get_products_by_category(oc_category.id):
            check_count += 1
            item_code = oc_product.get('model', '').upper()
            doc_item = get_item_by_item_code(item_code)

            # skip product if it is disabled on Opencart site
            if not int(oc_product.get('status') or 0):
                skip_count += 1
                extras = (1, 'skipped', 'Skipped: item with Item No. "%s" is disabled on Opencart site' % item_code)
                results_list.append((oc_product.get('name'), '', oc_product.get('product_id'), '', '') + extras)
                continue

            if doc_item_group:
                if doc_item:
                    try:
                        update_item(site_name, doc_item, oc_product, item_group=doc_item_group.get('name'))
                    except Exception as ex:
                        skip_count += 1
                        extras = (1, 'skipped', 'Skipped: due to exception: %s' % str(ex))
                        results_list.append((oc_product.get('name'), '', oc_product.get('product_id'), '', '') + extras)
                        continue

                    update_count += 1
                    extras = (1, 'updated', 'Updated')
                    results_list.append((doc_item.get('name'),
                                         doc_item_group.get('name'),
                                         oc_product.get('product_id'),
                                         doc_item.get_formatted('oc_last_sync_from'),
                                         doc_item.get('modified')) + extras)
                else:
                    skip_count += 1
                    extras = (1, 'skipped', 'Skipped: cannot found item with Item No. "%s"' % item_code)
                    results_list.append((oc_product.get('name'), '', oc_product.get('product_id'), '', '') + extras)
                    continue

                    params = {
                        'doctype': 'Item',
                        'item_code': oc_product.get('model'),
                        'item_group': doc_item_group.get('name'),
                        'is_group': 'No',
                        'default_warehouse': items_default_warehouse,
                        'item_name': oc_product.get('name'),
                        'description': oc_product.get('description'),
                        'show_in_website': 1,
                        'image': oc_product.get('image'),
                        'min_order_qty': oc_product.get('minimum'),
                        'oc_is_updating': 1,
                        'oc_site': site_name,
                        'oc_product_id': oc_product.get('product_id'),
                        'oc_manufacturer_id': oc_product.get('manufacturer_id'),
                        'oc_tax_class_id': oc_product.get('tax_class_id'),
                        'oc_stock_status': oc_product.get('stock_status'),
                        'oc_model': oc_product.get('model'),
                        'oc_sku': oc_product.get('sku'),
                        'oc_quantity': oc_product.get('quantity'),
                        'oc_status': int(oc_product.get('status') or 0),
                        'oc_meta_title': oc_product.get('meta_title'),
                        'oc_meta_keyword': oc_product.get('meta_keyword'),
                        'oc_meta_description': oc_product.get('meta_description'),
                        'price': oc_product.get('price'),
                        'oc_sync_from': True,
                        'oc_last_sync_from': datetime.now(),
                        'oc_sync_to': True,
                        'oc_last_sync_to': datetime.now()
                    }
                    doc_item = frappe.get_doc(params)
                    doc_item.insert(ignore_permissions=True)

                    # discounts
                    for oc_discount in oc_product.get('discounts'):
                        customer_group = customer_groups.get(site_name, oc_discount.get('customer_group_id'))
                        if not customer_group:
                            continue
                        doc_item.append('oc_discounts', {
                            'item_name': doc_item.get('name'),
                            'customer_group': customer_group.get('name'),
                            'quantity': oc_discount.get('quantity'),
                            'priority': oc_discount.get('priority'),
                            'price': oc_discount.get('price'),
                            'date_start': oc_discount.get('date_start'),
                            'date_end': oc_discount.get('date_end'),
                        })

                    # cpesials
                    for oc_special in oc_product.get('special'):
                        customer_group = customer_groups.get(site_name, oc_special.get('customer_group_id'))
                        if not customer_group:
                            continue
                        doc_item.append('oc_specials', {
                            'item_name': doc_item.get('name'),
                            'customer_group': customer_group.get('name'),
                            'priority': oc_special.get('priority'),
                            'price': oc_special.get('price'),
                            'date_start': oc_special.get('date_start'),
                            'date_end': oc_special.get('date_end'),
                        })
                    doc_item.update({'oc_is_updating': 1})
                    doc_item.save()
                    add_count += 1
                    extras = (1, 'added', 'Added')
                    results_list.append((doc_item.get('name'),
                                        doc_item_group.get('name'),
                                        oc_product.get('product_id'),
                                        doc_item.get_formatted('oc_last_sync_from'),
                                        doc_item.get('modified')) + extras)
            else:
                skip_count += 1
                extras = (1, 'skipped', 'Skipped: missed parent category')
                results_list.append((oc_product.get('name'), '', oc_product.get('product_id'), '', '') + extras)

    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
Example #17
0
def push_item_to_oc(doc_item, site_name=None):
    for doc_oc_product in doc_item.get('oc_products'):
        if not doc_oc_product.get('oc_sync_to'):
            continue
        cur_site_name = doc_oc_product.get('oc_site')
        if site_name is not None and cur_site_name != site_name:
            continue
        data = {
            'model': doc_oc_product.get('oc_model') or doc_item.get('name'),  # mandatory
            'sku': doc_oc_product.get('oc_sku') or doc_oc_product.get('oc_model'),  # mandatory
            'quantity': doc_oc_product.get('oc_quantity') or '0',  # mandatory
            'price': doc_oc_product.get('price'),
            'tax_class_id': doc_oc_product.get('oc_tax_class_id'),  # mandatory
            'manufacturer_id': doc_oc_product.get('oc_manufacturer_id'),  # mandatory
            # 'sort_order': '1',  # mandatory
            'status': doc_oc_product.get('oc_status'),
            # ,
            # 'upc': '',
            # 'ean': '',
            # 'jan': '',
            # 'isbn': '',
            # 'mpn': '',
            # 'location': '',
            'stock_status_id': doc_oc_product.get('oc_stock_status_id')
            # 'reward': '400',
            # 'points': '200',
            # 'image': doc_oc_product.get('image'),
            # 'other_images': [
            #     'catalog/image/image2.png',
            #     'catalog/image/image3.png'
            # ],
            # 'date_available': '2009-02-03',
            # 'weight': '146.4',
            # 'weight_class_id': '2',
            # 'length': '10',
            # 'width': '20',
            # 'height': '2',
            # 'length_class_id': '1',
            # 'subtract': '1',
            # 'minimum': '1',
            # 'product_store': [  # mandatory
            #     '12'
            # ],
            # 'product_category': [
            #     doc_item_group.get('oc_category_id')
            # ],
            # 'product_description': [
            #     {
            #         'language_id': 1,
            #         'name': doc_item.get('item_name'),
            #         'description': doc_item.get('description'),
            #         'meta_description': doc_item.get('oc_meta_description'),
            #         'meta_title': doc_item.get('oc_meta_title'),
            #         'meta_keyword': doc_item.get('oc_meta_keyword'),
            #     }
            #     # ,
            #     # {
            #     # 'language_id': 2,
            #     # 'name': 'test product hun',
            #     # 'meta_title': 'test product meta_title',
            #     # 'meta_description': 'test product meta_description hu',
            #     # 'meta_keyword': 'test product meta_keyword hun',
            #     # 'description': 'test product description hu'
            #     # }
            # ]
            # 'product_option': [
            # {
            #     'product_option_value': [
            #     {
            #         'price': 10,
            #         'price_prefix': '+',
            #         'subtract': '0',
            #         'points': '0',
            #         'points_prefix': '0',
            #         'weight': '0',
            #         'weight_prefix': '0',
            #         'option_value_id': '46',
            #         'quantity': '300'
            #     },
            #     {
            #         'price': 20,
            #         'price_prefix': '+',
            #         'subtract': '0',
            #         'points': '0',
            #         'points_prefix': '0',
            #         'weight': '0',
            #         'weight_prefix': '0',
            #         'option_value_id': '47',
            #         'quantity': '500'
            #     },
            #     {
            #         'price': false,
            #         'price_prefix': '+',
            #         'subtract': '0',
            #         'points': '0',
            #         'points_prefix': '0',
            #         'weight': '0',
            #         'weight_prefix': '0',
            #         'option_value_id': '48',
            #         'quantity': '10'
            #     }
            #     ],
            #     'type': 'select',
            #     'required': '1',
            #     'option_id': '11'
            # },
            # {
            #     'option_value': 'demo text option value',
            #     'type': 'text',
            #     'required': '1',
            #     'option_id': '4'
            # }
            # ],
            # 'product_attribute': [
            #     {
            #         'attribute_id': '16',
            #         'product_attribute_description':
            #         [
            #             {
            #             'language_id': '1',
            #             'text': 'demo attribute value'
            #             }
            #         ]
            #     }
            # ]
            # ,'product_special':[
            #     {
            #         'customer_group_id':'1',
            #         'price':'10',
            #         'priority':'1',
            #         'date_start':'2015-02-23',
            #         'date_end':'2015-02-27'
            #     },
            #     {
            #         'customer_group_id':'1',
            #         'price':'8',
            #         'priority':'1',
            #         'date_start':'2015-02-23',
            #         'date_end':'2015-02-27'
            #     }
            # ]
            # ,'product_discount':[
            #     {
            #         'customer_group_id':'1',
            #         'price':'10',
            #         'priority':'1',
            #         'quantity':'10',
            #         'date_start':'2015-02-23',
            #         'date_end':'2015-02-27'
            #     }
            # ]
        }

        # update multi currency prices
        if doc_oc_product.get('multi_currency_price'):
            prices = []
            for currency_code, price_field_name in CURRENCY_TO_PRICE_FIELD_MAP.items():
                prices.append({
                    'price': str(doc_oc_product.get(price_field_name)) if doc_oc_product.get(price_field_name) is not None else '',
                    'code': currency_code,
                })
            data.update({
                'prices': prices
            })

        # specials
        product_special = []
        for doc_oc_special in doc_item.oc_specials:
            if cur_site_name != doc_oc_special.get('oc_site'):
                continue
            doc_customer_group = frappe.get_doc('Customer Group', doc_oc_special.get('customer_group'))
            customer_group_id = doc_customer_group.get('oc_customer_group_id')
            if not customer_group_id:
                continue
            if cur_site_name != doc_customer_group.get('oc_site'):
                frappe.throw('Customer Group "%s" does not exist in Opencart site "%s"' % (doc_customer_group.get('name'), cur_site_name))
            product_special.append({
                'customer_group_id': customer_group_id,
                'price': doc_oc_special.price,
                'priority': doc_oc_special.priority,
                'date_start': doc_oc_special.date_start,
                'date_end': doc_oc_special.date_end,
            })
        data['product_special'] = product_special

        # discounts
        product_discount = []
        for doc_oc_discount in doc_item.oc_discounts:
            if cur_site_name != doc_oc_discount.get('oc_site'):
                continue
            doc_customer_group = frappe.get_doc('Customer Group', doc_oc_discount.get('customer_group'))
            customer_group_id = doc_customer_group.get('oc_customer_group_id')
            if not customer_group_id:
                continue
            if cur_site_name != doc_customer_group.get('oc_site'):
                frappe.throw('Customer Group "%s" does not exist in Opencart site "%s"' % (doc_customer_group.get('name'), cur_site_name))
            product_discount_json = {
                'customer_group_id': customer_group_id,
                'price': doc_oc_discount.price,
                'priority': doc_oc_discount.priority,
                'quantity': doc_oc_discount.quantity,
                'date_start': doc_oc_discount.date_start,
                'date_end': doc_oc_discount.date_end,
            }
            # update multi currency prices for discount
            if doc_oc_discount.get('multi_currency_price'):
                prices = []
                for currency_code, price_field_name in CURRENCY_TO_PRICE_FIELD_MAP.items():
                    prices.append({
                        'price': str(doc_oc_discount.get(price_field_name)) if doc_oc_discount.get(price_field_name) is not None else '',
                        'code': currency_code,
                    })
                product_discount_json.update({
                    'prices': prices
                })
            product_discount.append(product_discount_json)

        data['product_discount'] = product_discount

        # updating or creating product
        oc_product_id = doc_oc_product.get('oc_product_id')
        get_product_success, oc_product = oc_api.get(cur_site_name).get_product(oc_product_id)
        if oc_product_id and get_product_success:
            # update existed product on Opencart site
            success = oc_api.get(cur_site_name).update_product(oc_product_id, data)
            if success:
                frappe.msgprint('Product is updated successfully on Opencart site "%s"' % cur_site_name)
                doc_oc_product.update({'oc_last_sync_to': datetime.now()})
            else:
                frappe.msgprint('Product is not updated on Opencart site "%s". Error: Unknown' % cur_site_name)
        else:
            # add new product on Opencart site
            success, product_id = oc_api.get(cur_site_name).create_product(data)
            if success:
                doc_oc_product.update({
                    'oc_product_id': product_id,
                    'oc_last_sync_to': datetime.now()
                })
                frappe.msgprint('Product is created successfully on Opencart site "%s"' % cur_site_name)
            else:
                frappe.msgprint('Product is not created on Opencart site "%s". Error: Unknown' % cur_site_name)
def oc_validate(doc, method=None):
    site_name = doc.get('oc_site')
    customer_group_name = doc.get('customer_group')
    valid_customer_group_names = [customer_group.get('name') for customer_group in customer_groups.get_all_by_oc_site(site_name) if customer_group.get('oc_customer_group_id')]
    if customer_group_name not in valid_customer_group_names:
        frappe.throw('To sync Customer to Opencart Site, Customer Group must be one of the following:\n%s' % cstr(', '.join(valid_customer_group_names)))
    doc_customer_group = frappe.get_doc('Customer Group', customer_group_name)
    doc.oc_firstname = doc.get('customer_name').strip().split()[0]
    doc.oc_lastname = ' '.join(doc.get('customer_name').strip().split()[1:])
    data = {
        'firstname': doc.oc_firstname,
        'lastname': doc.oc_lastname,
        'email': doc.get('oc_email'),
        'telephone': doc.get('oc_telephone'),
        'fax': doc.get('oc_fax'),
        'status': doc.get('oc_status'),
        'customer_group_id': doc_customer_group.get('oc_customer_group_id')
        # 'custom_field': {
        #         'account': {
        #             '1': '6666555777',
        #             '2': '1'
        #         }
        # },
        # 'address': [
        #     {
        #         'firstname': 'firstname',
        #         'lastname': 'lastname',
        #         'company': 'companyname',
        #         'address_1': 'address_1',
        #         'address_2': 'address_2',
        #         'city': 'cit',
        #         'country_id': '1',
        #         'zone_id': '1',
        #         'postcode': '3333',
        #         'country': 'india',
        #         'default': '1'
        #     },
        #     {
        #         'firstname': 'firstname',
        #         'lastname': 'lastname',
        #         'company': 'companyname',
        #         'address_1': 'address_1',
        #         'address_2': 'address_2',
        #         'city': 'city',
        #         'country_id': '1',
        #         'zone_id': '1',
        #         'postcode': '3333',
        #         'country': 'india'
        #     }
        # ]
    }


            # 'phone': oc_customer.get('telephone', ''),
            # 'fax': oc_customer.get('fax', ''),
            # 'email_id': oc_customer.get('email', ''),
            # 'customer_name': oc_address.get('firstname', '') + ' ' + oc_address.get('lastname', ''),
            # 'pincode': oc_address.get('postcode', ''),
            # 'country': oc_address.get('country', ''),
            # 'state': oc_address.get('zone'),
            # 'city': oc_address.get('city', ''),
            # 'address_line1': oc_address.get('address_1', ''),
            # 'address_line2': oc_address.get('address_2', ''),
            # 'oc_site': site_name,
            # 'oc_address_id': oc_customer.get('address_id'),


    # # addresses
    # addresses = []
    # address_fields = ['name', 'oc_address_id', 'address_line1', 'address_line2', 'city', 'pincode', 'country']
    # db_addresses = frappe.get_all('Address', fields=address_fields, filters={'oc_site': site_name, 'customer': doc.get('name')})
    # raise Exception(str(db_addresses))
    # for db_address in db_addresses:
    #     db_contact = frappe.db.get('Contact', {'oc_site': site_name, 'oc_contact_id': db_address.get('oc_address_id')})
    #     if not db_contact:
    #         frappe.msgprint('Cannot find Contact related to Customer "%s"' % (doc.get('name')))
    #         continue
    #     addresses.append({
    #         'firstname': db_contact.get('first_name'),
    #         'lastname': db_contact.get('last_name'),
    #         # 'company': db_address.get(''),
    #         'address_1': db_address.get('address_line1'),
    #         'address_2': db_address.get('address_line2'),
    #         'city': db_address.get('city'),
    #         # 'country_id': '1',
    #         # 'zone_id': '1',
    #         'postcode': db_address.get('pincode'),
    #         'country': db_address.get('country'),
    #         # 'default': '1'
    #     })
    # if addresses:
    #     data['address'] = addresses

    # updating or creating customer
    oc_customer_id = doc.get('oc_customer_id')
    get_customer_success, oc_customer = False, {}
    if oc_customer_id:
        get_customer_success, oc_customer = oc_api.get(site_name).get_customer(oc_customer_id)

    if get_customer_success:
        # update existed customer on Opencart site
        success, resp = oc_api.get(site_name).update_customer(oc_customer_id, data)
        if success:
            frappe.msgprint('Customer is updated successfully on Opencart site')
            doc.update({'oc_last_sync_to': datetime.now()})
        else:
            frappe.msgprint('Customer is not updated on Opencart site.\nError: %s' % resp.get('error') or 'Unknown')
    else:
        # add new customer on Opencart site
        random_password = uuid.uuid4().hex[:20]
        data.update({
            'password': random_password,
            'confirm': random_password,
            'approved': '1',
            'safe': '1',
            'newsletter': '0'
        })
        success, resp = oc_api.get(site_name).create_customer(data)
        if success:
            doc.update({
                'oc_customer_id': resp.get('data', {}).get('id', ''),
                'oc_last_sync_to': datetime.now()
            })
            frappe.msgprint('Customer is created successfully on Opencart site')
        else:
            frappe.msgprint('Customer is not created on Opencart site.\nError: %s' % resp.get('error') or 'Unknown')
def pull(site_name, item_code=None, silent=False):
    '''Sync Item Prices from Opencart site'''
    results = {}
    results_list = []
    check_count = 0
    update_count = 0
    add_count = 0
    skip_count = 0
    success = True

    doc_stores = oc_stores.get_all(site_name)
    oc_api_cache = {}
    customer_groups_cache = {}

    for doc_store in doc_stores:
        if doc_store.get('oc_store_front_url') and doc_store.get('oc_price_lists'):
            oc_api_cache[doc_store.get('name')] = oc_api.get(site_name, doc_store.get('oc_store_front_url'))
            print('store name=' + doc_store.get('oc_store_front_url'))
            # fill cache of customer groups
            for doc_oc_price_list in doc_store.get('oc_price_lists'):
                customer_group_name = doc_oc_price_list.get('customer_group')
                db_customer_group = frappe.db.get('Customer Group', {'name': customer_group_name})
                if not db_customer_group:
                    frappe.msgprint('Customer Group is not set for Opencart Price List in Opencart Store "%s"' % doc_store.get('name'))
                    continue
                customer_groups_cache[db_customer_group.get('name')] = db_customer_group

    all_dict_items = []
    if item_code:
        all_dict_items = frappe.get_all('Item', fields=['name', 'item_code'], filters={'item_code': item_code.upper()})
    else:
        all_dict_items = frappe.get_all('Item', fields=['name', 'item_code'])
    items_count_left_to_process = len(all_dict_items)
    for dict_item in all_dict_items:
    # for dict_item in [it for it in frappe.get_all('Item', fields=['name', 'item_code']) if it.get('name') == 'TESTAH']:
        item_code = dict_item.get('item_code')
        items_count_left_to_process -= 1
        print('processing %s, left to process %d' % (item_code or '', items_count_left_to_process))
        doc_oc_product = items.get_opencart_product(site_name, dict_item.get('name'))
        if not doc_oc_product:
            skip_count += 1
            continue
        oc_product_id = doc_oc_product.get('oc_product_id')
        doc_item = frappe.get_doc('Item', dict_item.get('name'))
        for doc_store in doc_stores:
            oc_api_obj = oc_api_cache.get(doc_store.get('name'))
            if oc_api_obj:
                get_product_success, oc_product = oc_api_obj.get_product(oc_product_id)
                if not get_product_success:
                    skip_count += 1
                    extras = (1, 'skipped', 'Skipped: cannot get product with product_id %s' % oc_product_id)
                    results_list.append(('', '', '', '', '') + extras)
                    continue
            # TODO
            # updating item for each store
            # items.update_item(site_name, doc_item, oc_product)
            for doc_oc_price_list in doc_store.get('oc_price_lists'):
                check_count += 1
                price_list_name = doc_oc_price_list.get('price_list')
                customer_group_name = doc_oc_price_list.get('customer_group')
                doc_price_list = frappe.get_doc('Price List', price_list_name)
                doc_item_price = get(item_code, price_list_name)

                # resolve price
                price = items.get_oc_product_price(oc_product, doc_price_list.get('currency'))
                # price = float(oc_product.get('price', 0))
                customer_group_id = customer_groups_cache.get(customer_group_name, {}).get('oc_customer_group_id')
                for discount in oc_product.get('discounts'):
                    if customer_group_id == discount.get('customer_group_id') and int(discount.get('quantity', 0)) == 1:
                        # price = float(discount.get('price', 0))
                        price = items.get_oc_discount_price(discount, doc_price_list.get('currency'))
                if doc_item_price:
                    # update existed Item Price
                    doc_item_price.update({
                        'price_list_rate': price,
                        'oc_is_updating': 1
                    })
                    doc_item_price.save()
                    update_count += 1
                    extras = (1, 'updated', 'Updated')
                    results_list.append((doc_item_price.get('name'),
                                        doc_item_price.get('item_code'),
                                        doc_item_price.get('price_list'),
                                        doc_item_price.get('currency'),
                                        doc_item_price.get('price_list_rate')) + extras)
                else:
                    # create new Item Price
                    params = {
                        'doctype': 'Item Price',
                        'oc_is_updating': 1,
                        'selling': 1,
                        'item_code': item_code,
                        'price_list': price_list_name,
                        'price_list_rate': price
                    }
                    doc_item_price = frappe.get_doc(params)
                    doc_item_price.insert(ignore_permissions=True)
                    add_count += 1
                    extras = (1, 'added', 'Added')
                    results_list.append((doc_item_price.get('name'),
                                        doc_item_price.get('item_code'),
                                        doc_item_price.get('price_list'),
                                        doc_item_price.get('currency'),
                                        doc_item_price.get('price_list_rate')) + extras)

                update_item(doc_item, doc_item_price)
        # get again updated Item and pushing it to Opencart site
        doc_item = frappe.get_doc('Item', doc_item.get('name'))
        items.push_item_to_oc(doc_item, site_name)

    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
Example #20
0
def pull_product_from_oc(site_name, item_name, doc_item=None, silent=False):
    results = {}
    success = True
    status = None

    if doc_item is None:
        doc_item = frappe.get_doc('Item', item_name)

    site_doc = frappe.get_doc('Opencart Site', site_name)
    items_default_warehouse = site_doc.get('items_default_warehouse')
    doc_oc_product = get_opencart_product(site_name, doc_item.get('name'))
    success, oc_product = oc_api.get(site_name).get_product(doc_oc_product.get('oc_product_id'))

    if not success:
        results = {
            'success': success,
            'status': 'Cannot get product from Opencart site'
        }
        return results

    if doc_item:
        update_item(site_name, doc_item, oc_product)
        extras = (1, 'updated', 'Updated')
        status = (doc_item.get('name'),
                  '',  # doc_item_group.get('name'),
                  doc_item.get('oc_product_id'),
                  doc_item.get_formatted('oc_last_sync_from'),
                  doc_item.get('modified')) + extras
    else:
        params = {
            'doctype': 'Item',
            'item_code': oc_product.get('model'),
            # 'item_group': doc_item_group.get('name'),
            'is_group': 'No',
            'default_warehouse': items_default_warehouse,
            'item_name': oc_product.get('name'),
            'description': oc_product.get('description'),
            'show_in_website': 1,
            'image': oc_product.get('image'),
            'min_order_qty': oc_product.get('minimum'),
            'oc_is_updating': 1,
            'oc_site': site_name,
            'oc_product_id': oc_product.get('product_id'),
            'oc_manufacturer_id': oc_product.get('manufacturer_id'),
            'oc_tax_class_id': oc_product.get('tax_class_id'),
            'oc_stock_status': oc_product.get('stock_status'),
            'oc_model': oc_product.get('model'),
            'oc_sku': oc_product.get('sku'),
            'oc_quantity': oc_product.get('quantity'),
            'oc_status': int(oc_product.get('status') or 0),
            'oc_meta_title': oc_product.get('meta_title'),
            'oc_meta_keyword': oc_product.get('meta_keyword'),
            'oc_meta_description': oc_product.get('meta_description'),
            'price': oc_product.get('price'),
            'oc_sync_from': True,
            'oc_last_sync_from': datetime.now(),
            'oc_sync_to': True,
            'oc_last_sync_to': datetime.now()
        }
        doc_item = frappe.get_doc(params)
        doc_item.insert(ignore_permissions=True)

        # discounts
        for oc_discount in oc_product.get('discounts'):
            customer_group = customer_groups.get(site_name, oc_discount.get('customer_group_id'))
            if not customer_group:
                continue
            doc_item.append('oc_discounts', {
                'item_name': doc_item.get('name'),
                'customer_group': customer_group.get('name'),
                'quantity': oc_discount.get('quantity'),
                'priority': oc_discount.get('priority'),
                'price': oc_discount.get('price'),
                'date_start': oc_discount.get('date_start'),
                'date_end': oc_discount.get('date_end'),
            })

        # cpesials
        for oc_special in oc_product.get('special'):
            customer_group = customer_groups.get(site_name, oc_special.get('customer_group_id'))
            if not customer_group:
                continue
            doc_item.append('oc_specials', {
                'item_name': doc_item.get('name'),
                'customer_group': customer_group.get('name'),
                'priority': oc_special.get('priority'),
                'price': oc_special.get('price'),
                'date_start': oc_special.get('date_start'),
                'date_end': oc_special.get('date_end'),
            })
        doc_item.update({'oc_is_updating': 1})
        doc_item.save()
        extras = (1, 'added', 'Added')
        status = (doc_item.get('name'),
                  '',  # doc_item_group.get('name'),
                  doc_item.get('oc_product_id'),
                  doc_item.get_formatted('oc_last_sync_from'),
                  doc_item.get('modified')) + extras
    results = {
        'success': success,
        'status': status
    }
    return results
def pull_customers_from_oc(site_name, silent=False):
    '''Sync customers from Opencart site'''
    results = {}
    results_list = []
    check_count = 0
    update_count = 0
    add_count = 0
    skip_count = 0
    success = False

    site_doc = frappe.get_doc('Opencart Site', site_name)
    # root_customer_group = site_doc.get('root_customer_group')
    default_customer_territory = site_doc.get('default_customer_territory') or 'All Territories'
    doc_customer_groups_cache = {}
    for success, oc_customer in oc_api.get(site_name).get_customers():
    # success, oc_customer = oc_api.get(site_name).get_customer('1332')
    # while True:
    #     if check_count >= 1:
    #         break
        check_count += 1

        oc_customer_name = make_full_name(oc_customer.get('firstname'), oc_customer.get('lastname'))
        customer_id = oc_customer.get('customer_id')

        # validation
        # missed_mandatory_fields = [field for field in OC_MANDATORY_FIELDS if not oc_customer.get(field)]
        # if missed_mandatory_fields:
        #     skip_count += 1
        #     extras = (1, 'skipped', 'Skipped: mandatory fileds missed: %s' % ', '.join(missed_mandatory_fields))
        #     results_list.append((oc_customer_name, customer_id, '', '', '') + extras)
        #     continue

        doc_customer_group = doc_customer_groups_cache.get(oc_customer.get('customer_group_id'))
        if not doc_customer_group:
            doc_customer_group = customer_groups.get(site_name, oc_customer.get('customer_group_id'))
            doc_customer_groups_cache[oc_customer.get('customer_group_id')] = doc_customer_group

        if not doc_customer_group:
            skip_count += 1
            extras = (1, 'skipped', 'Skipped: parent group missed')
            results_list.append((oc_customer_name, customer_id, '', '', '') + extras)
            continue

        doc_customer = get_customer(site_name, customer_id)
        if doc_customer:
            # update existed Customer
            # check here for a need to update Customer
            params = {
                'customer_name': oc_customer_name,
                'customer_group': doc_customer_group.get('name'),
                'oc_last_sync_from': datetime.now(),
                'oc_is_updating': 1,
                'oc_store_id': oc_customer.get('store_id') or '',
                'oc_status': 1,
                'oc_firstname': oc_customer.get('firstname'),
                'oc_lastname': oc_customer.get('lastname'),
                'oc_telephone': oc_customer.get('telephone'),
                'oc_fax': oc_customer.get('fax'),
                'oc_email': oc_customer.get('email'),
            }
            doc_customer.update(params)
            doc_customer.save()

            # addresses and contacts
            addresses.create_or_update(site_name, oc_customer, doc_customer)
            contacts.create_or_update(site_name, oc_customer, doc_customer)

            update_count += 1
            extras = (1, 'updated', 'Updated')
            results_list.append((doc_customer.get('name'),
                                 doc_customer.get('oc_customer_id'),
                                 doc_customer_group.get('name'),
                                 doc_customer.get_formatted('oc_last_sync_from'),
                                 doc_customer.get('modified')) + extras)

        else:
            default_price_list = doc_customer_group.get('default_price_list')
            # do not allow to aad new customer if default_price_list is missed in customer's group
            # if not default_price_list:
            #     skip_count += 1
            #     extras = (1, 'skipped', 'Skipped: missed default price list in customer group')
            #     results_list.append((oc_customer_name, customer_id, '', '', '') + extras)
            #     continue

            # create new Customer
            params = {
                'doctype': 'Customer',
                'customer_type': 'Individual',
                'territory': default_customer_territory,
                'customer_name': oc_customer_name,
                'customer_group': doc_customer_group.get('name'),
                'naming_series': 'CUST-',
                'default_price_list': default_price_list,
                'oc_is_updating': 1,
                'oc_site': site_name,
                'oc_customer_id': customer_id,
                'oc_store_id': oc_customer.get('store_id') or '',
                'oc_status': 1,
                'oc_sync_from': True,
                'oc_last_sync_from': datetime.now(),
                'oc_sync_to': True,
                'oc_last_sync_to': datetime.now(),
                'oc_firstname': oc_customer.get('firstname'),
                'oc_lastname': oc_customer.get('lastname'),
                'oc_telephone': oc_customer.get('telephone'),
                'oc_fax': oc_customer.get('fax'),
                'oc_email': oc_customer.get('email')
            }
            doc_customer = frappe.get_doc(params)
            if not doc_customer.get('customer_name').strip():
                continue
            doc_customer.insert(ignore_permissions=True)

            # addresses and contacts
            addresses.create_or_update(site_name, oc_customer, doc_customer)
            contacts.create_or_update(site_name, oc_customer, doc_customer)

            add_count += 1
            extras = (1, 'added', 'Added')
            results_list.append((doc_customer.get('customer_name'),
                                 doc_customer.get('oc_customer_id'),
                                 doc_customer_group.get('name'),
                                 doc_customer.get_formatted('oc_last_sync_from'),
                                 doc_customer.get('modified')) + extras)
    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
def pull(site_name, silent=False):
    '''Sync Item Attributes from Opencart site'''
    results = {}
    results_list = []
    check_count = 0
    update_count = 0
    add_count = 0
    skip_count = 0
    success = False

    for oc_product_option in oc_api.get(site_name).get_product_options():
        check_count += 1
        doc_item_attr = get(site_name, oc_product_option.id)
        if doc_item_attr:
            # update existed Item Attribute
            params = {
                'attribute_name': oc_product_option.name,
                'oc_last_sync_from': datetime.now(),
            }
            doc_item_attr.update(params)
            doc_item_attr.save()
            update_count += 1
            extras = (1, 'updated', 'Updated')
            results_list.append((doc_item_attr.get('name'),
                                 doc_item_attr.get('oc_option_id'),
                                 doc_item_attr.get_formatted('oc_last_sync_from'),
                                 doc_item_attr.get('modified')) + extras)
        else:
            item_attribute_values = []
            for option_val in oc_product_option.option_values_list:
                item_attribute_values.append({
                    'attribute_value': option_val.name,
                    'abbr': option_val.name,
                    'oc_site': site_name,
                    'oc_option_value_id': option_val.option_value_id,
                    'oc_image': option_val.image,
                    'oc_thumb': option_val.thumb
                })
            params = {
                'doctype': 'Item Attribute',
                'attribute_name': oc_product_option.name,
                'item_attribute_values': item_attribute_values,
                'oc_site': site_name,
                'oc_option_id': oc_product_option.id,
                'oc_sync_from': True,
                'oc_last_sync_from': datetime.now(),
                'oc_sync_to': True,
                'oc_last_sync_to': datetime.now()
            }
            doc_item_attr = frappe.get_doc(params)
            # check if whether Item Attribute name is unique or not
            if frappe.db.get('Item Attribute', {'name': oc_product_option.name}):
                skip_count += 1
                extras = (1, 'skipped', 'Skipped: duplicate name')
                results_list.append((oc_product_option.name,
                                     oc_product_option.id,
                                     '',
                                     '') + extras)
                continue
            else:
                # creating new Item Attribute
                doc_item_attr.insert(ignore_permissions=True)
                add_count += 1
                extras = (1, 'added', 'Added')
                results_list.append((doc_item_attr.get('name'),
                                     doc_item_attr.get('oc_option_id'),
                                     doc_item_attr.get_formatted('oc_last_sync_from'),
                                     doc_item_attr.get('modified')) + extras)
    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results
Example #23
0
def pull(site_name, silent=False):
    '''Sync Item Attributes from Opencart site'''
    results = {}
    results_list = []
    check_count = 0
    update_count = 0
    add_count = 0
    skip_count = 0
    success = False

    for oc_product_option in oc_api.get(site_name).get_product_options():
        check_count += 1
        doc_item_attr = get(site_name, oc_product_option.id)
        if doc_item_attr:
            # update existed Item Attribute
            params = {
                'attribute_name': oc_product_option.name,
                'oc_last_sync_from': datetime.now(),
            }
            doc_item_attr.update(params)
            doc_item_attr.save()
            update_count += 1
            extras = (1, 'updated', 'Updated')
            results_list.append(
                (doc_item_attr.get('name'), doc_item_attr.get('oc_option_id'),
                 doc_item_attr.get_formatted('oc_last_sync_from'),
                 doc_item_attr.get('modified')) + extras)
        else:
            item_attribute_values = []
            for option_val in oc_product_option.option_values_list:
                item_attribute_values.append({
                    'attribute_value': option_val.name,
                    'abbr': option_val.name,
                    'oc_site': site_name,
                    'oc_option_value_id': option_val.option_value_id,
                    'oc_image': option_val.image,
                    'oc_thumb': option_val.thumb
                })
            params = {
                'doctype': 'Item Attribute',
                'attribute_name': oc_product_option.name,
                'item_attribute_values': item_attribute_values,
                'oc_site': site_name,
                'oc_option_id': oc_product_option.id,
                'oc_sync_from': True,
                'oc_last_sync_from': datetime.now(),
                'oc_sync_to': True,
                'oc_last_sync_to': datetime.now()
            }
            doc_item_attr = frappe.get_doc(params)
            # check if whether Item Attribute name is unique or not
            if frappe.db.get('Item Attribute',
                             {'name': oc_product_option.name}):
                skip_count += 1
                extras = (1, 'skipped', 'Skipped: duplicate name')
                results_list.append((oc_product_option.name,
                                     oc_product_option.id, '', '') + extras)
                continue
            else:
                # creating new Item Attribute
                doc_item_attr.insert(ignore_permissions=True)
                add_count += 1
                extras = (1, 'added', 'Added')
                results_list.append(
                    (doc_item_attr.get('name'),
                     doc_item_attr.get('oc_option_id'),
                     doc_item_attr.get_formatted('oc_last_sync_from'),
                     doc_item_attr.get('modified')) + extras)
    results = {
        'check_count': check_count,
        'add_count': add_count,
        'update_count': update_count,
        'skip_count': skip_count,
        'results': results_list,
        'success': success,
    }
    return results