Example #1
0
def create_item(client, product_id, data):
    try:
        res = (client.products[product_id].items.create(data))
    except ClientError as error:
        handle_http_error(error)

    return res
Example #2
0
 def _resolve_new_context(self, general_data):
     """Check that there is no ambiguity on the new specified context,
     and update the context_id accordingly."""
     try:
         if general_data.context_id:
             ctx = self._get_context(general_data.context_id)
             if not ctx:
                 raise click.ClickException(
                     f"The Context ID ({general_data.context_id}) doesn't exist",
                 )
             if (general_data.context_instance_id
                     and general_data.context_instance_id !=
                     ctx['instance_id']):
                 raise click.ClickException(
                     f"The Instance ID ({general_data.context_instance_id}) doesn't correspond "
                     f"to the Context ID ({general_data.context_id})", )
             general_data.context_name = ctx['name']
         elif general_data.context_instance_id:  # pragma: no branch
             ctx = self._client.ns('localization').contexts.filter(
                 instance_id=general_data.context_instance_id, ).first()
             if not ctx:
                 raise click.ClickException(
                     f"The Instance ID ({general_data.context_instance_id}) doesn't exist",
                 )
             general_data.context_id = ctx['id']
             general_data.context_name = ctx['name']
     except ClientError as error:
         handle_http_error(error)
Example #3
0
def update_item(client, product_id, item_id, data):
    try:
        res = client.products[product_id].items[item_id].update(data)
    except ClientError as error:
        handle_http_error(error)

    return res
Example #4
0
def wait_for_autotranslation(client, translation, wait_seconds=1, max_counts=5, silent=False):
    if isinstance(translation, dict):
        translation_id = translation['id']
    else:
        translation_id = translation
    progress = trange(0, max_counts, disable=silent, leave=False, bar_format=DEFAULT_BAR_FORMAT)
    for _ in progress:
        progress.set_description('Waiting for pending translation tasks')
        sleep(wait_seconds)
        try:
            translation = client.ns('localization').translations[translation_id].get()
        except ClientError as error:
            handle_http_error(error)
        status = translation['auto']['status']
        if status == 'processing':
            pass
        elif status in ('on', 'off'):
            break
        elif status == 'error':
            translation['auto']['error_message']
            raise click.ClickException(
                'The auto-translation task failed with error: '
                + translation['auto']['error_message'],
            )
        else:
            raise click.ClickException(f'Unknown auto-translation status: {status}')
    else:
        raise click.ClickException('Timeout waiting for pending translation tasks')
Example #5
0
def primarize_translation(
    api_url,
    api_key,
    translation_id,
    verbose=False,
):
    try:
        client = ConnectClient(
            api_key=api_key,
            endpoint=api_url,
            use_specs=False,
            max_retries=3,
            logger=RequestLogger() if verbose else None,
        )
        payload = {
            'primary': True,
        }
        translation = (client.ns('localization').translations[translation_id].
                       action('primarize').post(payload=payload))
    except ClientError as error:
        if error.status_code == 404:
            status = format_http_status(error.status_code)
            raise click.ClickException(
                f'{status}: Translation {translation_id} not found.')
        handle_http_error(error)
    return translation
Example #6
0
def test_handle_http_error_others(mocker, code, description, message):
    res = mocker.MagicMock()
    res.status_code = code

    with pytest.raises(ClickException) as e:
        handle_http_error(res)

    assert str(e.value) == f'{code} - {description}: {message}'
Example #7
0
 def _get_translation(self, translation_id):
     try:
         return self._client.ns(
             'localization').translations[translation_id].get()
     except ClientError as error:
         if error.status_code == 404:
             return None
         handle_http_error(error)
Example #8
0
def get_item(client, product_id, item_id):
    try:
        res = client.products[product_id].items[item_id].get()
    except ClientError as error:
        if error.status_code == 404:
            return
        handle_http_error(error)
    return res
Example #9
0
def test_handle_http_error_400(mocker):
    res = ClientError()
    res.status_code = 400
    res.errors = ['error1', 'error2']
    res.error_code = 'SYS-000'
    with pytest.raises(ClickException) as e:
        handle_http_error(res)

    assert str(e.value) == '400 - Bad Request: SYS-000 - error1,error2'
Example #10
0
def get_item_by_mpn(client, product_id, mpn):
    rql = R().mpn.eq(mpn)

    try:
        res = (client.products[product_id].items.filter(rql))
        return res.first()

    except ClientError as error:
        if error.status_code == 404:
            return
        handle_http_error(error)
Example #11
0
def dump_customers(api_url, api_key, account_id, output_file, silent, output_path=None):  # noqa: CCR001
    if not output_path:
        output_path = os.path.join(os.getcwd(), account_id)
    else:
        if not os.path.exists(output_path):
            raise ClickException(
                "Output Path does not exist",
            )
        output_path = os.path.join(output_path, account_id)

    if not output_file:
        output_file = os.path.join(output_path, 'customers.xlsx')
    else:
        output_file = os.path.join(output_path, output_file)

    if not os.path.exists(output_path):
        os.mkdir(output_path)
    elif not os.path.isdir(output_path):
        raise ClickException(
            "Exists a file with account id as name but a directory is expected, please rename it",
        )
    try:
        client = ConnectClient(
            max_retries=3,
            api_key=api_key,
            endpoint=api_url,
            use_specs=False,
            default_limit=1000,
        )
        wb = Workbook()
        _prepare_worksheet(wb.create_sheet('Customers'))
        _add_countries(wb.create_sheet('Countries'))

        customers = client.ns('tier').accounts.all()
        row_idx = 2
        count = customers.count()
        progress = trange(0, count, disable=silent, leave=True, bar_format=DEFAULT_BAR_FORMAT)
        for customer in customers:
            progress.set_description(f'Processing customer {customer["id"]}')
            progress.update(1)
            _fill_customer_row(wb['Customers'], row_idx, customer)
            row_idx += 1
    except ClientError as error:
        handle_http_error(error)

    default_sheet = wb['Sheet']
    wb.remove(default_sheet)
    wb.save(output_file)

    return output_file
Example #12
0
def dump_customers(api_url,
                   api_key,
                   account_id,
                   output_file,
                   silent,
                   verbose=False,
                   output_path=None):  # noqa: CCR001
    output_file = validate_output_options(
        output_path,
        output_file,
        default_dir_name=account_id,
        default_file_name='customers',
    )
    try:
        client = ConnectClient(
            max_retries=3,
            api_key=api_key,
            endpoint=api_url,
            use_specs=False,
            default_limit=1000,
            logger=RequestLogger() if verbose else None,
        )
        wb = Workbook()
        _prepare_worksheet(wb.create_sheet('Customers'))
        _add_countries(wb.create_sheet('Countries'))

        customers = client.ns('tier').accounts.all()
        row_idx = 2
        count = customers.count()
        progress = trange(0,
                          count,
                          disable=silent,
                          leave=True,
                          bar_format=DEFAULT_BAR_FORMAT)
        for customer in customers:
            progress.set_description(f'Processing customer {customer["id"]}')
            progress.update(1)
            _fill_customer_row(wb['Customers'], row_idx, customer)
            row_idx += 1
    except ClientError as error:
        handle_http_error(error)

    default_sheet = wb['Sheet']
    wb.remove(default_sheet)
    wb.save(output_file)

    return output_file
Example #13
0
def _get_translation_workbook(api_url, api_key, translation_id, verbose=False):
    try:
        client = ConnectClient(api_key=api_key,
                               endpoint=api_url,
                               use_specs=False)
        attributes_path = client.ns(
            'localization').translations[translation_id].attributes.path
        url = f'{api_url}/{attributes_path}'
        response = logged_request('GET',
                                  url,
                                  verbose,
                                  headers={
                                      'Content-type': EXCEL_CONTENT_TYPE,
                                      **get_headers(api_key),
                                  })
        if response.status_code != 200:
            raise ClientError(status_code=response.status_code)
        return load_workbook(filename=BytesIO(response.content))
    except ClientError as error:
        if error.status_code == 404:
            status = format_http_status(error.status_code)
            raise ClickException(
                f'{status}: Translation {translation_id} not found.')
        handle_http_error(error)
Example #14
0
def dump_product(  # noqa: CCR001
    api_url,
    api_key,
    product_id,
    output_file,
    silent,
    verbose=False,
    output_path=None,
):
    output_file = validate_output_options(output_path,
                                          output_file,
                                          default_dir_name=product_id)
    media_path = os.path.join(os.path.dirname(output_file), 'media')
    if not os.path.exists(media_path):
        os.mkdir(media_path)
    try:
        client = ConnectClient(
            api_key=api_key,
            endpoint=api_url,
            use_specs=False,
            max_retries=3,
            logger=RequestLogger() if verbose else None,
        )
        product = client.products[product_id].get()
        wb = Workbook()

        _setup_locales_list(wb.active, client)

        connect_api_location = parse.urlparse(api_url)
        media_location = f'{connect_api_location.scheme}://{connect_api_location.netloc}'
        _setup_cover_sheet(
            wb.active,
            product,
            media_location,
            client,
            media_path,
        )

        _dump_capabilities(wb.create_sheet('Capabilities'), product, silent)
        _dump_external_static_links(
            wb.create_sheet('Embedding Static Resources'), product, silent)
        _dump_media(
            wb.create_sheet('Media'),
            client,
            product_id,
            silent,
            media_location,
            media_path,
        )
        _dump_templates(wb.create_sheet('Templates'), client, product_id,
                        silent)
        _dump_items(wb.create_sheet('Items'), client, product_id, silent)
        _dump_parameters(
            wb.create_sheet('Ordering Parameters'),
            client,
            product_id,
            'ordering',
            silent,
        )
        _dump_parameters(
            wb.create_sheet('Fulfillment Parameters'),
            client,
            product_id,
            'fulfillment',
            silent,
        )
        _dump_parameters(
            wb.create_sheet('Configuration Parameters'),
            client,
            product_id,
            'configuration',
            silent,
        )
        _dump_actions(wb.create_sheet('Actions'), client, product_id, silent)
        _dump_configuration(wb.create_sheet('Configuration'), client,
                            product_id, silent)
        _dump_translations(wb, client, product_id, silent)
        wb.save(output_file)

    except ClientError as error:
        status = format_http_status(error.status_code)
        if error.status_code == 404:
            raise ClickException(f'{status}: Product {product_id} not found.')

        handle_http_error(error)

    return output_file
Example #15
0
def create_unit(client, data):
    try:
        res = client.ns('settings').units.create(data)
    except ClientError as error:
        handle_http_error(error)
    return res
Example #16
0
def delete_item(client, product_id, item_id):
    try:
        client.products[product_id].items[item_id].delete()
    except ClientError as error:
        handle_http_error(error)
Example #17
0
def dump_product(api_url,
                 api_key,
                 product_id,
                 output_file,
                 silent,
                 output_path=None):  # noqa: CCR001
    if not output_path:
        output_path = os.path.join(os.getcwd(), product_id)
    else:
        if not os.path.exists(output_path):
            raise ClickException("Output Path does not exist", )
        output_path = os.path.join(output_path, product_id)

    media_path = os.path.join(output_path, 'media')

    if not output_file:
        output_file = os.path.join(output_path, f'{product_id}.xlsx')
    else:
        output_file = os.path.join(output_path, output_file)

    if not os.path.exists(output_path):
        os.mkdir(output_path)
    elif not os.path.isdir(output_path):
        raise ClickException(
            "Exists a file with product name but a directory is expected, please rename it",
        )

    if not os.path.exists(media_path):
        os.mkdir(media_path)
    try:
        client = ConnectClient(
            api_key=api_key,
            endpoint=api_url,
            use_specs=False,
            max_retries=3,
        )
        product = client.products[product_id].get()
        wb = Workbook()
        connect_api_location = parse.urlparse(api_url)
        media_location = f'{connect_api_location.scheme}://{connect_api_location.netloc}'
        _setup_cover_sheet(
            wb.active,
            product,
            media_location,
            client,
            media_path,
        )

        _dump_capabilities(wb.create_sheet('Capabilities'), product, silent)
        _dump_external_static_links(
            wb.create_sheet('Embedding Static Resources'), product, silent)
        _dump_media(
            wb.create_sheet('Media'),
            client,
            product_id,
            silent,
            media_location,
            media_path,
        )
        _dump_templates(wb.create_sheet('Templates'), client, product_id,
                        silent)
        _dump_items(wb.create_sheet('Items'), client, product_id, silent)
        _dump_parameters(
            wb.create_sheet('Ordering Parameters'),
            client,
            product_id,
            'ordering',
            silent,
        )
        _dump_parameters(
            wb.create_sheet('Fulfillment Parameters'),
            client,
            product_id,
            'fulfillment',
            silent,
        )
        _dump_parameters(
            wb.create_sheet('Configuration Parameters'),
            client,
            product_id,
            'configuration',
            silent,
        )
        _dump_actions(wb.create_sheet('Actions'), client, product_id, silent)
        _dump_configuration(wb.create_sheet('Configuration'), client,
                            product_id, silent)

        wb.save(output_file)

    except ClientError as error:
        status = format_http_status(error.status_code)
        if error.status_code == 404:
            raise ClickException(f'{status}: Product {product_id} not found.')

        handle_http_error(error)

    return output_file