def main(argv):
  # Authenticate and construct service.
  service, config, flags = shopping_common.init(
      argv, __doc__, parents=[argparser])
  merchant_id = config['merchantId']
  account_id = flags.account_id

  if not account_id:
    account_id = merchant_id
  elif merchant_id != account_id:
    shopping_common.check_mca(
        config,
        True,
        msg='Non-multi-client accounts can only get their own information.')

  status = service.accountstatuses().get(
      merchantId=merchant_id, accountId=merchant_id).execute()
  print('Account %s:' % status['accountId'])
  if shopping_common.json_absent_or_false(status, 'dataQualityIssues'):
    print('- No data quality issues.')
  else:
    print('- Found %d data quality issues:' % len(status['dataQualityIssues']))
    for issue in status['dataQualityIssues']:
      print('  - (%s) [%s]' % (issue['severity'], issue['id']))
      if shopping_common.json_absent_or_false(issue, 'exampleItems'):
        print('  - No example items.')
      else:
        print('  - Have %d examples from %d affected items:' %
              (len(issue['exampleItems']), issue['numItems']))
        for example in issue['exampleItems']:
          print('    - %s: %s' % (example['itemId'], example['title']))
Ejemplo n.º 2
0
def main(argv):
  # Authenticate and construct service.
  service, config, flags = shopping_common.init(
      argv, __doc__, parents=[argparser])
  merchant_id = config['merchantId']
  account_id = flags.account_id

  if merchant_id != account_id:
    shopping_common.check_mca(
        config,
        True,
        msg='Non-multi-client accounts can only get their own information.')

  try:
    status = service.accountstatuses().get(
        merchantId=merchant_id, accountId=merchant_id).execute()
    print 'Account %s:' % status['accountId']
    if shopping_common.json_absent_or_false(status, 'dataQualityIssues'):
      print '- No data quality issues.'
    else:
      print(
          '- Found %d data quality issues:' % len(status['dataQualityIssues']))
      for issue in status['dataQualityIssues']:
        print '  - (%s) [%s]' % (issue['severity'], issue['id'])
        if shopping_common.json_absent_or_false(issue, 'exampleItems'):
          print '  - No example items.'
        else:
          print('  - Have %d examples from %d affected items:' %
                (len(issue['exampleItems']), issue['numItems']))
          for example in issue['exampleItems']:
            print '    - %s: %s' % (example['itemId'], example['title'])
  except client.AccessTokenRefreshError:
    print('The credentials have been revoked or expired, please re-run the '
          'application to re-authorize')
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    shopping_common.check_mca(config, False)

    request = service.productstatuses().list(merchantId=merchant_id,
                                             maxResults=MAX_PAGE_SIZE)

    while request is not None:
        result = request.execute()
        if shopping_common.json_absent_or_false(result, 'resources'):
            print('No products were found.')
            break
        else:
            statuses = result['resources']
            for status in statuses:
                print('- Product "%s" with title "%s":' %
                      (status['productId'], status['title']))
                if shopping_common.json_absent_or_false(
                        status, 'dataQualityIssues'):
                    print('  No data quality issues.')
                else:
                    print('  Found %d data quality issues:' %
                          len(status['dataQualityIssues']))
                    for issue in status['dataQualityIssues']:
                        if shopping_common.json_absent_or_false(
                                issue, 'detail'):
                            print('  - (%s) [%s]' %
                                  (issue['severity'], issue['id']))
                        else:
                            print('  - (%s) [%s] %s' %
                                  (issue['severity'], issue['id'],
                                   issue['detail']))
            request = service.productstatuses().list_next(request, result)
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    email = None
    if shopping_common.json_absent_or_false(config, 'accountSampleUser'):
        print(
            'Must specify the user email to remove in the samples configuration.'
        )
        sys.exit(1)
    email = config['accountSampleUser']

    # First we need to retrieve the existing set of users.
    account = service.accounts().get(merchantId=merchant_id,
                                     accountId=merchant_id,
                                     fields='users').execute()

    if shopping_common.json_absent_or_false(account, 'users'):
        print('No users in account %d.' % merchant_id)
        sys.exit(1)

    matched = [u for u in account['users'] if u['emailAddress'] == email]
    if not matched:
        print('User %s was not found.' % email)
        sys.exit(1)

    for u in matched:
        account['users'].remove(u)

    # Patch account with new user list.
    service.accounts().patch(merchantId=merchant_id,
                             accountId=merchant_id,
                             body=account).execute()

    print('User %s was removed from merchant ID %d' % (email, merchant_id))
def main(argv):
  # Authenticate and construct service.
  service, config, flags = shopping_common.init(
      argv, __doc__, parents=[argparser])
  merchant_id = config['merchantId']
  account_id = flags.account_id

  if merchant_id != account_id:
    shopping_common.check_mca(
        config,
        True,
        msg='Non-multi-client accounts can only get their own information.')

  status = service.accounttax().get(
      merchantId=merchant_id, accountId=merchant_id).execute()
  print('Account %s:' % status['accountId'])
  if shopping_common.json_absent_or_false(status, 'rules'):
    print('- No tax settings, so no tax is charged.')
  else:
    print('- Found %d tax rules:' % len(status['rules']))
    for issue in status['rules']:
      if not shopping_common.json_absent_or_false(issue, 'ratePercent'):
        print('  - For %s in %s: %s%%' %
              (issue['locationId'], issue['country'], issue['ratePercent']))
      if not shopping_common.json_absent_or_false(issue, 'useGlobalRate'):
        print('  - For %s in %s: using the global tax table rate.' %
              (issue['locationId'], issue['country']))
      if not shopping_common.json_absent_or_false(issue, 'shippingTaxed'):
        print('   NOTE: Shipping charges are also taxed.')
Ejemplo n.º 6
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = shopping_common.init(argv,
                                                  __doc__,
                                                  parents=[argparser])
    merchant_id = config['merchantId']
    product_id = flags.product_id
    shopping_common.check_mca(config, False)

    try:
        status = service.productstatuses().get(merchantId=merchant_id,
                                               productId=product_id).execute()

        print('- Product "%s" with title "%s":' %
              (status['productId'], status['title']))
        if shopping_common.json_absent_or_false(status, 'dataQualityIssues'):
            print '    No data quality issues.'
        else:
            print 'Found %d data quality issues:' % len(
                status['dataQualityIssues'])
            for issue in status['dataQualityIssues']:
                if shopping_common.json_absent_or_false(issue, 'detail'):
                    print '    - (%s) [%s]' % (issue['severity'], issue['id'])
                else:
                    print('    - (%s) [%s] %s' %
                          (issue['severity'], issue['id'], issue['detail']))
    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Ejemplo n.º 7
0
def product_insert(argv, products_list, mode):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']

    batch = {'entries': []}
    position = 0
    while position < len(products_list):
        batch['entries'] = []
        product_list = products_list[position:position + BATCH_SIZE]
        position += BATCH_SIZE
        for i in range(BATCH_SIZE):
            if len(product_list) > i:
                product = create_product(config, product_list[i], mode)
                # Add product to the batch.
                batch['entries'].append({
                    'batchId': i,
                    'merchantId': merchant_id,
                    'method': 'insert',
                    'product': product
                })
        try:
            request = service.products().custombatch(body=batch)
            try:
                result = request.execute()
            except:
                traceback.print_exc()
                #pdb.set_trace()

            if result['kind'] == 'content#productsCustomBatchResponse':
                entries = result['entries']
                for entry in entries:
                    if not shopping_common.json_absent_or_false(
                            entry, 'product'):
                        product = entry['product']
                        print('Product with offerId "%s" was update.' %
                              (product['offerId']))
                        f_log1.write(
                            str(product['offerId'].split('_')[-1]) + '\n')
                    elif not shopping_common.json_absent_or_false(
                            entry, 'errors'):
                        print(entry['errors'])
            else:
                print('There was an error. Response: %s' % (result))
        except client.AccessTokenRefreshError:
            print(
                'The credentials have been revoked or expired, please re-run the '
                'application to re-authorize')
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    email = None
    if shopping_common.json_absent_or_false(config, 'accountSampleUser'):
        print 'Must specify the user email to add in the samples configuration.'
        sys.exit(1)
    email = config['accountSampleUser']

    try:
        # First we need to retrieve the existing set of users.
        response = service.accounts().get(merchantId=merchant_id,
                                          accountId=merchant_id,
                                          fields='users').execute()

        account = response

        # Add new user to existing user list.
        new_user = {'emailAddress': email, 'admin': False}
        account['users'].append(new_user)

        # Patch account with new user list.
        response = service.accounts().patch(merchantId=merchant_id,
                                            accountId=merchant_id,
                                            body=account).execute()

        print 'Account %s was added to merchant ID %s' % (email, merchant_id)

    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Ejemplo n.º 9
0
def get_product_list(argv,inven_file):
	# Authenticate and construct service.
	service, config, _ = shopping_common.init(argv, __doc__)
	merchant_id = config['merchantId']
	try:
		request = service.products().list(
				merchantId=merchant_id, maxResults=MAX_PAGE_SIZE)

		while request is not None:
			result = request.execute()
			if shopping_common.json_absent_or_false(result, 'resources'):
				print('No products were found.')
				break
			else:
				products = result['resources']
				for product in products:
					# print(product)
					# exit()
					inven_file.write('\t'.join([product['id'],product.get('gtin',''),product['price'].get('value',''),product['condition'],product['availability']])+'\n')
					print('Product "%s" was found.' % (product['id']))
				request = service.products().list_next(request, result)

	except client.AccessTokenRefreshError:
		print('The credentials have been revoked or expired, please re-run the '
					'application to re-authorize')
Ejemplo n.º 10
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    adwords_id = None
    if shopping_common.json_absent_or_false(config, 'accountSampleAdWordsCID'):
        print(
            'Must specify the AdWords CID to link in the samples configuration.'
        )
        sys.exit(1)
    adwords_id = config['accountSampleAdWordsCID']

    # First we need to retrieve the existing set of users.
    response = service.accounts().get(merchantId=merchant_id,
                                      accountId=merchant_id,
                                      fields='adwordsLinks').execute()

    account = response

    # Add new user to existing user list.
    adwords_link = {'adwordsId': adwords_id, 'status': 'active'}
    account.setdefault('adwordsLinks', []).append(adwords_link)

    # Patch account with new user list.
    response = service.accounts().patch(merchantId=merchant_id,
                                        accountId=merchant_id,
                                        body=account).execute()

    print('AdWords ID %d was added to merchant ID %d' %
          (adwords_id, merchant_id))
def main(argv):
  # Authenticate and construct service.
  service, config, _ = shopping_common.init(argv, __doc__)
  merchant_id = config['merchantId']
  adwords_id = None
  if shopping_common.json_absent_or_false(config, 'accountSampleAdWordsCID'):
    print 'Must specify the AdWords CID to link in the samples configuration.'
    sys.exit(1)
  adwords_id = config['accountSampleAdWordsCID']

  try:
    # First we need to retrieve the existing set of users.
    response = service.accounts().get(merchantId=merchant_id,
                                      accountId=merchant_id,
                                      fields='adwordsLinks').execute()

    account = response

    # Add new user to existing user list.
    adwords_link = {'adwordsId': adwords_id, 'status': 'active'}
    account.setdefault('adwordsLinks', []).append(adwords_link)

    # Patch account with new user list.
    response = service.accounts().patch(merchantId=merchant_id,
                                        accountId=merchant_id,
                                        body=account).execute()

    print 'AdWords ID %s was added to merchant ID %s' % (adwords_id,
                                                         merchant_id)

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Ejemplo n.º 12
0
def main(argv):
  # Authenticate and construct service.
  service, config, _ = shopping_common.init(argv, __doc__)
  merchant_id = config['merchantId']
  email = None
  if shopping_common.json_absent_or_false(config, 'accountSampleUser'):
    print('Must specify the user email to add in the samples configuration.')
    sys.exit(1)
  email = config['accountSampleUser']

  # First we need to retrieve the existing set of users.
  response = service.accounts().get(
      merchantId=merchant_id, accountId=merchant_id,
      fields='users').execute()

  account = response

  # Add new user to existing user list.
  new_user = {'emailAddress': email, 'admin': False}
  account['users'].append(new_user)

  # Patch account with new user list.
  response = service.accounts().patch(
      merchantId=merchant_id, accountId=merchant_id, body=account).execute()

  print('Account %s was added to merchant ID %d' % (email, merchant_id))
Ejemplo n.º 13
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = shopping_common.init(argv,
                                                  __doc__,
                                                  parents=[argparser])
    merchant_id = config['merchantId']
    datafeed_ids = flags.datafeed_ids

    batch = {
        'entries': [{
            'batchId': i,
            'merchantId': merchant_id,
            'method': 'delete',
            'datafeedId': v,
        } for i, v in enumerate(datafeed_ids)],
    }

    request = service.datafeeds().custombatch(body=batch)
    result = request.execute()

    if result['kind'] == 'content#datafeedsCustomBatchResponse':
        for entry in result['entries']:
            if not shopping_common.json_absent_or_false(entry, 'errors'):
                print('Errors for batch entry %d:' % entry['batchId'])
                print(
                    json.dumps(entry['errors'],
                               sort_keys=True,
                               indent=2,
                               separators=(',', ': ')))
            else:
                print('Successfully deleted datafeed %s (batch entry %d).' %
                      (datafeed_ids.get(entry['batchId']), entry['batchId']))
    else:
        print('There was an error. Response: %s' % result)
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    shopping_common.check_mca(config, True)

    try:
        request = service.accounts().list(merchantId=merchant_id,
                                          maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            if shopping_common.json_absent_or_false(result, 'resources'):
                print 'No accounts were found.'
            else:
                accounts = result['resources']
                for account in accounts:
                    print('Account "%s" with name "%s" was found.' %
                          (account['id'], account['name']))

                request = service.accounts().list_next(request, result)
                break

    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def create_product_sample(config, offer_id, **overwrites):
    """Creates a sample product object for the product samples.

  Args:
      config: dictionary, Python version of config JSON
      offer_id: string, offer id for new product
      **overwrites: dictionary, a set of product attributes to overwrite

  Returns:
      A new product in dictionary form.
  """
    website_url = 'http://my-book-shop.com'
    if not shopping_common.json_absent_or_false(config, 'websiteUrl'):
        website_url = config['websiteUrl']

    product = {
        'offerId':
        offer_id,
        'title':
        'A Tale of Two Cities',
        'description':
        'A classic novel about the French Revolution',
        'link':
        website_url + '/tale-of-two-cities.html',
        'imageLink':
        website_url + '/tale-of-two-cities.jpg',
        'contentLanguage':
        _constants.CONTENT_LANGUAGE,
        'targetCountry':
        _constants.TARGET_COUNTRY,
        'channel':
        _constants.CHANNEL,
        'availability':
        'in stock',
        'condition':
        'new',
        'googleProductCategory':
        'Media > Books',
        'gtin':
        '9780007350896',
        'price': {
            'value': '2.50',
            'currency': 'USD'
        },
        'shipping': [{
            'country': 'US',
            'service': 'Standard shipping',
            'price': {
                'value': '0.99',
                'currency': 'USD'
            }
        }],
        'shippingWeight': {
            'value': '200',
            'unit': 'grams'
        }
    }
    product.update(overwrites)
    return product
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    shopping_common.check_mca(config, True)

    try:
        request = service.accountstatuses().list(merchantId=merchant_id,
                                                 maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            if shopping_common.json_absent_or_false(result, 'resources'):
                print 'No accounts were found.'
                break
            else:
                statuses = result['resources']
                for status in statuses:
                    print 'Account %s:' % status['accountId']
                    if shopping_common.json_absent_or_false(
                            status, 'dataQualityIssues'):
                        print '- No data quality issues.'
                    else:
                        print('- Found %d data quality issues:' %
                              len(status['dataQualityIssues']))
                        for issue in status['dataQualityIssues']:
                            print '  - (%s) [%s]' % (issue['severity'],
                                                     issue['id'])
                            if shopping_common.json_absent_or_false(
                                    issue, 'exampleItems'):
                                print '  - No example items.'
                            else:
                                print(
                                    '  - Have %d examples from %d affected items:'
                                    % (len(issue['exampleItems']),
                                       issue['numItems']))
                                for example in issue['exampleItems']:
                                    print '    - %s: %s' % (example['itemId'],
                                                            example['title'])
                request = service.accountstatuses().list_next(request, result)

    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Ejemplo n.º 17
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']

    batch = {'entries': []}

    for i in range(BATCH_SIZE):
        offer_id = 'book#%s' % shopping_common.get_unique_id()
        product = product_sample.create_product_sample(
            config,
            offer_id,
            title='This is book number %d' % (i, ),
            price={
                'value': '%d.50' % (i, ),
                'currency': 'USD'
            })
        # Add product to the batch.
        batch['entries'].append({
            'batchId': i,
            'merchantId': merchant_id,
            'method': 'insert',
            'product': product
        })

    try:
        request = service.products().custombatch(body=batch)
        result = request.execute()

        if result['kind'] == 'content#productsCustomBatchResponse':
            entries = result['entries']
            for entry in entries:
                if not shopping_common.json_absent_or_false(entry, 'product'):
                    product = entry['product']
                    print(
                        'Product with offerId "%s" and title "%s" was created.'
                        % (product['offerId'], product['title']))
                elif not shopping_common.json_absent_or_false(entry, 'errors'):
                    print entry['errors']
        else:
            print 'There was an error. Response: %s' % (result)
    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']

    batch = {
        'entries': [{
            'batchId':
            i,
            'merchantId':
            merchant_id,
            'method':
            'insert',
            'product':
            product_sample.create_product_sample(
                config,
                'book#%s' % shopping_common.get_unique_id(),
                title='This is book number %d' % i,
                price={
                    'value': '%d.50' % i,
                    'currency': 'USD',
                }),
        } for i in range(BATCH_SIZE)],
    }

    request = service.products().custombatch(body=batch)
    result = request.execute()

    if result['kind'] == 'content#productsCustomBatchResponse':
        entries = result['entries']
        for entry in entries:
            if not shopping_common.json_absent_or_false(entry, 'product'):
                product = entry['product']
                print(
                    'Product "%s" with offerId "%s" and title "%s" was created.'
                    % (product['id'], product['offerId'], product['title']))
            elif not shopping_common.json_absent_or_false(entry, 'errors'):
                print('Errors for batch entry %d:' % entry['batchId'])
                print(
                    json.dumps(entry['errors'],
                               sort_keys=True,
                               indent=2,
                               separators=(',', ': ')))
    else:
        print('There was an error. Response: %s' % result)
def main(argv):
    # Authenticate and construct service.
    service, config, flags = shopping_common.init(argv,
                                                  __doc__,
                                                  parents=[argparser])
    merchant_id = config['merchantId']
    account_id = flags.account_id

    if not account_id:
        account_id = merchant_id
    elif merchant_id != account_id:
        shopping_common.check_mca(
            config,
            True,
            msg='Non-multi-client accounts can only get their own information.'
        )

    settings = shippingsettings_sample.create_shippingsettings_sample()
    service.shippingsettings().update(merchantId=merchant_id,
                                      accountId=merchant_id,
                                      body=settings).execute()
    status = service.shippingsettings().get(merchantId=merchant_id,
                                            accountId=merchant_id).execute()
    print('Account %s:' % status['accountId'])
    if shopping_common.json_absent_or_false(status, 'postalCodeGroups'):
        print('- No postal code groups.')
    else:
        print('- %d postal code group(s):' % len(status['postalCodeGroups']))
    if shopping_common.json_absent_or_false(status, 'services'):
        print('- No services.')
    else:
        print('- %d service(s):' % len(status['services']))
        for service in status['services']:
            print('  Service "%s":' % service['name'])
            print('  - Delivery country: %s' % service['deliveryCountry'])
            print('  - Currency: %s' % service['currency'])
            print('  - Active: %s' % service['active'])
            print('  - Delivery time: %d - %d days' %
                  (service['deliveryTime']['minTransitTimeInDays'],
                   service['deliveryTime']['maxTransitTimeInDays']))
            if shopping_common.json_absent_or_false(service, 'rateGroups'):
                print('  - No rate groups.')
            else:
                print('  - %d rate groups.' % len(service['rateGroups']))
Ejemplo n.º 20
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = shopping_common.init(argv,
                                                  __doc__,
                                                  parents=[argparser])
    merchant_id = config['merchantId']
    account_id = flags.account_id

    if merchant_id != account_id:
        shopping_common.check_mca(
            config,
            True,
            msg='Non-multi-client accounts can only get their own information.'
        )

    try:
        status = service.shippingsettings().get(
            merchantId=merchant_id, accountId=merchant_id).execute()
        print 'Account %s:' % status['accountId']
        if shopping_common.json_absent_or_false(status, 'postalCodeGroups'):
            print '- No postal code groups.'
        else:
            print '- %d postal code group(s):' % len(
                status['postalCodeGroups'])
        if shopping_common.json_absent_or_false(status, 'services'):
            print '- No services.'
        else:
            print '- %d service(s):' % len(status['services'])
            for service in status['services']:
                print '  Service "%s":' % service['name']
                print '  - Delivery country: %s' % service['deliveryCountry']
                print '  - Currency: %s' % service['currency']
                print '  - Active: %s' % service['active']
                print('  - Delivery time: %d - %d days' %
                      (service['deliveryTime']['minTransitTimeInDays'],
                       service['deliveryTime']['maxTransitTimeInDays']))
                if shopping_common.json_absent_or_false(service, 'rateGroups'):
                    print '  - No rate groups.'
                else:
                    print '  - %d rate groups.' % len(service['rateGroups'])
    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Ejemplo n.º 21
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = shopping_common.init(argv,
                                                  __doc__,
                                                  parents=[argparser])
    merchant_id = config['merchantId']
    account_id = flags.account_id

    if merchant_id != account_id:
        shopping_common.check_mca(
            config,
            True,
            msg='Non-multi-client accounts can only set their own information.'
        )

    try:
        settings = accounttax_sample.create_accounttax_sample(account_id)
        status = service.accounttax().update(merchantId=merchant_id,
                                             accountId=merchant_id,
                                             body=settings).execute()
        print 'Account %s:' % status['accountId']
        if shopping_common.json_absent_or_false(status, 'rules'):
            print '- No tax settings, so no tax is charged.'
        else:
            print('- Found %d tax rules:' % len(status['rules']))
            for issue in status['rules']:
                if not shopping_common.json_absent_or_false(
                        issue, 'ratePercent'):
                    print('  - For %s in %s: %s%%' %
                          (issue['locationId'], issue['country'],
                           issue['ratePercent']))
                if not shopping_common.json_absent_or_false(
                        issue, 'useGlobalRate'):
                    print(
                        '  - For %s in %s: using the global tax table rate.' %
                        (issue['locationId'], issue['country']))
                if not shopping_common.json_absent_or_false(
                        issue, 'shippingTaxed'):
                    print '   NOTE: Shipping charges are also taxed.'
    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Ejemplo n.º 22
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    adwords_id = None
    if shopping_common.json_absent_or_false(config, 'accountSampleAdWordsCID'):
        print 'Must specify the AdWords CID to unlink in the samples configuration.'
        sys.exit(1)
    adwords_id = config['accountSampleAdWordsCID']

    try:
        # First we need to retrieve the existing set of users.
        account = service.accounts().get(merchantId=merchant_id,
                                         accountId=merchant_id,
                                         fields='adwordsLinks').execute()

        if shopping_common.json_absent_or_false(account, 'adwordsLinks'):
            print 'No AdWords accounts linked to account %d.' % (merchant_id, )
            sys.exit(1)

        matched = [
            l for l in account['adwordsLinks'] if l['adwordsId'] == adwords_id
        ]
        if not matched:
            print 'AdWords account %s was not linked.' % (adwords_id, )
            sys.exit(1)

        for u in matched:
            account['adwordsLinks'].remove(u)

        # Patch account with new user list.
        service.accounts().patch(merchantId=merchant_id,
                                 accountId=merchant_id,
                                 body=account).execute()

        print 'AdWords ID %s was removed from merchant ID %s' % (adwords_id,
                                                                 merchant_id)

    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def _list_all_orders(orders, merchant_id, **args):
    request = orders.list(merchantId=merchant_id, **args)
    while request is not None:
        result = request.execute()
        if shopping_common.json_absent_or_false(result, 'resources'):
            print('No orders were found.')
        else:
            order_resources = result['resources']
            for order in order_resources:
                print_order(order)
            request = orders.list_next(request, result)
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    shopping_common.check_mca(config, False)

    try:
        request = service.productstatuses().list(merchantId=merchant_id,
                                                 maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            if shopping_common.json_absent_or_false(result, 'resources'):
                print 'No products were found.'
            else:
                statuses = result['resources']
                for status in statuses:
                    print('- Product "%s" with title "%s":' %
                          (status['productId'], status['title']))
                    if shopping_common.json_absent_or_false(
                            status, 'dataQualityIssues'):
                        print '  No data quality issues.'
                    else:
                        print('  Found %d data quality issues:' %
                              len(status['dataQualityIssues']))
                        for issue in status['dataQualityIssues']:
                            if shopping_common.json_absent_or_false(
                                    issue, 'detail'):
                                print '  - (%s) [%s]' % (issue['severity'],
                                                         issue['id'])
                            else:
                                print('  - (%s) [%s] %s' %
                                      (issue['severity'], issue['id'],
                                       issue['detail']))
                request = service.productstatuses().list_next(request, result)
                break

    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Ejemplo n.º 25
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    shopping_common.check_mca(config, True)

    account_names = [
        'account%s' % shopping_common.get_unique_id()
        for i in range(BATCH_SIZE)
    ]
    batch = {
        'entries': [{
            'batchId': i,
            'merchantId': merchant_id,
            'method': 'insert',
            'account': {
                'name': v,
                'websiteUrl': 'https://%s.example.com/' % v,
            },
        } for i, v in enumerate(account_names)],
    }

    request = service.accounts().custombatch(body=batch)
    result = request.execute()

    if result['kind'] == 'content#accountsCustomBatchResponse':
        for entry in result['entries']:
            if not shopping_common.json_absent_or_false(entry, 'account'):
                account = entry['account']
                print('Account %s with name "%s" was created.' %
                      (account['id'], account['name']))
            elif not shopping_common.json_absent_or_false(entry, 'errors'):
                print('Errors for batch entry %d:' % entry['batchId'])
                print(
                    json.dumps(entry['errors'],
                               sort_keys=True,
                               indent=2,
                               separators=(',', ': ')))
    else:
        print('There was an error. Response: %s' % result)
Ejemplo n.º 26
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    email = None
    if shopping_common.json_absent_or_false(config, 'accountSampleUser'):
        print 'Must specify the user email to remove in the samples configuration.'
        sys.exit(1)
    email = config['accountSampleUser']

    try:
        # First we need to retrieve the existing set of users.
        account = service.accounts().get(merchantId=merchant_id,
                                         accountId=merchant_id,
                                         fields='users').execute()

        if shopping_common.json_absent_or_false(account, 'users'):
            print 'No users in account %d.' % (merchant_id, )
            sys.exit(1)

        matched = [u for u in account['users'] if u['emailAddress'] == email]
        if not matched:
            print 'User %s was not found.' % (email, )
            sys.exit(1)

        for u in matched:
            account['users'].remove(u)

        # Patch account with new user list.
        response = service.accounts().patch(merchantId=merchant_id,
                                            accountId=merchant_id,
                                            body=account).execute()

        print 'User %s was removed from merchant ID %s' % (email, merchant_id)

    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']

    batch = {
        'entries': [{
            'batchId':
            i,
            'merchantId':
            merchant_id,
            'method':
            'insert',
            'datafeed':
            datafeed_sample.create_datafeed_sample(
                config, 'feed%s' % shopping_common.get_unique_id()),
        } for i in range(BATCH_SIZE)],
    }

    request = service.datafeeds().custombatch(body=batch)
    result = request.execute()

    if result['kind'] == 'content#datafeedsCustomBatchResponse':
        entries = result['entries']
        for entry in entries:
            if not shopping_common.json_absent_or_false(entry, 'datafeed'):
                print('Datafeed %s with name "%s" created.' %
                      (entry['datafeed']['id'], entry['datafeed']['name']))
            elif not shopping_common.json_absent_or_false(entry, 'errors'):
                print('Errors for batch entry %d:' % entry['batchId'])
                print(
                    json.dumps(entry['errors'],
                               sort_keys=True,
                               indent=2,
                               separators=(',', ': ')))
    else:
        print('There was an error. Response: %s' % result)
Ejemplo n.º 28
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']
    adwords_id = None
    if shopping_common.json_absent_or_false(config, 'accountSampleAdWordsCID'):
        print('Must specify the AdWords CID to unlink in the samples config.')
        sys.exit(1)
    adwords_id = config['accountSampleAdWordsCID']

    # First we need to retrieve the existing set of users.
    account = service.accounts().get(merchantId=merchant_id,
                                     accountId=merchant_id,
                                     fields='adwordsLinks').execute()

    if shopping_common.json_absent_or_false(account, 'adwordsLinks'):
        print('No AdWords accounts linked to account %d.' % merchant_id)
        sys.exit(1)

    matched = [
        l for l in account['adwordsLinks'] if l['adwordsId'] == adwords_id
    ]
    if not matched:
        print('AdWords account %d was not linked.' % adwords_id)
        sys.exit(1)

    for u in matched:
        account['adwordsLinks'].remove(u)

    # Patch account with new user list.
    service.accounts().patch(merchantId=merchant_id,
                             accountId=merchant_id,
                             body=account).execute()

    print('AdWords ID %d was removed from merchant ID %d' %
          (adwords_id, merchant_id))
Ejemplo n.º 29
0
def _print_line_item(item):
    """Factored out line item printing to reduce nesting depth."""
    def print_if_nonzero(value, text):
        if value > 0:
            print('  - %s: %s' % (text, value))

    print('  Line item %s' % item['id'])
    print('  - Product: %s (%s)' %
          (item['product']['id'], item['product']['title']))
    print('  - Price: %s %s' %
          (item['price']['value'], item['price']['currency']))
    print('  - Tax: %s %s' % (item['tax']['value'], item['tax']['currency']))
    print_if_nonzero(item['quantityOrdered'], 'Quantity ordered')
    print_if_nonzero(item['quantityPending'], 'Quantity pending')
    print_if_nonzero(item['quantityShipped'], 'Quantity shipped')
    print_if_nonzero(item['quantityDelivered'], 'Quantity delivered')
    print_if_nonzero(item['quantityReturned'], 'Quantity returned')
    print_if_nonzero(item['quantityCanceled'], 'Quantity canceled')
    if not shopping_common.json_absent_or_false(item, 'shippingDetails'):
        print('  - Ship by date: %s' % item['shippingDetails']['shipByDate'])
        print('  - Deliver by date: %s' %
              item['shippingDetails']['deliverByDate'])
        method = item['shippingDetails']['method']
        print('  - Deliver via %s %s (%s - %s days).' %
              (method['carrier'], method['methodName'],
               method['minDaysInTransit'], method['maxDaysInTransit']))
    if not shopping_common.json_absent_or_false(item, 'cancellations'):
        print('  - %d cancellation(s):' % len(item['cancellations']))
        for cancel in item['cancellations']:
            print('    Cancellation:')
            if not shopping_common.json_absent_or_false(cancel, 'actor'):
                print('    - Actor: %s' % cancel['actor'])
            print('    - Creation date: %s' % cancel['creationDate'])
            print('    - Quantity: %d' % cancel['quantity'])
            print('    - Reason: %s' % cancel['reason'])
            print('    - Reason text: %s' % cancel['reasonText'])
    if (not shopping_common.json_absent_or_false(item, 'returnInfo')
            and item['returnInfo']['isReturnable']):
        print('  - Item is returnable.')
        print('    - Days to return: %s' % item['returnInfo']['daysToReturn'])
        print('    - Return policy is at %s.' %
              item['returnInfo']['policyUrl'])
    else:
        print('  - Item is not returnable.')
    if not shopping_common.json_absent_or_false(item, 'returns'):
        print('  - %d return(s):' % len(item['returns']))
        for ret in item['returns']:
            print('    Return:')
            if not shopping_common.json_absent_or_false(ret, 'actor'):
                print('    - Actor: %s' % ret['actor'])
            print('    - Creation date: %s' % ret['creationDate'])
            print('    - Quantity: %d' % ret['quantity'])
            print('    - Reason: %s' % ret['reason'])
            print('    - Reason text: %s' % ret['reasonText'])
Ejemplo n.º 30
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = shopping_common.init(argv, __doc__)
    merchant_id = config['merchantId']

    request = service.datafeeds().list(merchantId=merchant_id)

    while request is not None:
        result = request.execute()
        if shopping_common.json_absent_or_false(result, 'resources'):
            print('No datafeeds were found.')
            break
        else:
            datafeeds = result['resources']
            for datafeed in datafeeds:
                print('Datafeed %s with name "%s" was found.' %
                      (datafeed['id'], datafeed['name']))
        request = service.datafeeds().list_next(request, result)