예제 #1
0
def do(list_offers):
    # Authenticate and construct service.
    service, config, _ = common.init(sys.argv, __doc__)
    merchant_id = config['merchantId']

    for offer in list_offers:
        product_id = offer['published_id']

        # First we need to retrieve the full object, since there are no partial
        # updates for the products collection in Content API v2.
        product = service.products().get(merchantId=merchant_id,
                                         productId=product_id).execute()

        # Let's fix the warning about product_type and update the product.
        # product['productType'] = 'English/Classics'
        product['description'] = offer['description']
        product['link'] = offer['link']
        product['imageLink'] = offer['imageLink']
        product['title'] = offer['title']
        product['price'] = offer['price']

        # Notice that we use insert. The products service does not have an update
        # method. Inserting a product with an ID that already exists means the same
        # as doing an update.
        request = service.products().insert(merchantId=merchant_id,
                                            body=product)

        result = request.execute()
        print('Product with offerId "%s" was updated.' % (result['offerId']))
예제 #2
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = 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:
        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'])
    issues = status.get('dataQualityIssues')
    if not issues:
        print('- No data quality issues.')
        return
    print('- Found %d data quality issues:' % len(issues))
    for issue in issues:
        print('  - (%s) [%s]' % (issue['severity'], issue['id']))
        items = issue.get('exampleItems')
        if not items:
            print('    No example items.')
            continue
        print('    Have %d examples from %d affected items:' %
              (len(items), issue['numItems']))
        for example in items:
            print('    - %s: %s' % (example['itemId'], example['title']))
예제 #3
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__)
    merchant_id = config['merchantId']
    email = config.get('accountSampleUser')
    if not email:
        print(
            'Must specify the user email to add in the samples configuration.')
        sys.exit(1)

    # 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))
예제 #4
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = common.init(argv, __doc__, parents=[argparser])
    merchant_id = config['merchantId']
    account_ids = flags.account_ids
    common.check_mca(config, True)

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

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

    if result['kind'] == 'content#accountsCustomBatchResponse':
        entries = result['entries']
        for entry in entries:
            errors = entry.get('errors')
            if errors:
                print('Errors for batch entry %d:' % entry['batchId'])
                print(
                    json.dumps(errors,
                               sort_keys=True,
                               indent=2,
                               separators=(',', ': ')))
            else:
                print('Account %s deleted (batch entry %d).' %
                      (account_ids[entry['batchId']], entry['batchId']))
    else:
        print('There was an error. Response: %s' % result)
예제 #5
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = 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:
        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'])
    rules = status.get('rules')
    if not rules:
        print('- No tax settings, so no tax is charged.')
        return
    print('- Found %d tax rules:' % len(rules))
    for rule in rules:
        rate_percent = rule.get('ratePercent')
        if rate_percent:
            print('  - For %s in %s: %s%%' %
                  (rule['locationId'], rule['country'], rate_percent))
        use_global = rule.get('useGlobalRate')
        if use_global:
            print('  - For %s in %s: using the global tax table rate.' %
                  (rule['locationId'], rule['country']))
        taxed_shipping = rule.get('shippingTaxed')
        if taxed_shipping:
            print('   NOTE: Shipping charges are also taxed.')
예제 #6
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__)
    merchant_id = config['merchantId']
    common.check_mca(config, True)

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

    while request is not None:
        result = request.execute()
        statuses = result.get('resources')
        if not statuses:
            print('No statuses were returned.')
            break
        for status in statuses:
            print('Account %s:' % status['accountId'])
            issues = status.get('dataQualityIssues')
            if not issues:
                print('- No data quality issues.')
                continue
            print('- Found %d data quality issues:' % len(issues))
            for issue in issues:
                print('  - (%s) [%s]' % (issue['severity'], issue['id']))
                items = issue.get('exampleItems')
                if not items:
                    print('    No example items.')
                    continue
                print('    Have %d examples from %d affected items:' %
                      (len(items), issue['numItems']))
                for example in items:
                    print('    - %s: %s' %
                          (example['itemId'], example['title']))
        request = service.accountstatuses().list_next(request, result)
예제 #7
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = 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']:
            errors = entry.get('errors')
            if errors:
                print('Errors for batch entry %d:' % entry['batchId'])
                print(
                    json.dumps(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)
예제 #8
0
def do(product_ids):
    # Authenticate and construct service.
    service, config, _ = common.init(sys.argv, __doc__)
    merchant_id = config['merchantId']

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

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

    if result['kind'] == 'content#productsCustomBatchResponse':
        for entry in result['entries']:
            errors = entry.get('errors')
            if errors:
                print('Errors for batch entry %d:' % entry['batchId'])
                print(
                    json.dumps(entry['errors'],
                               sort_keys=True,
                               indent=2,
                               separators=(',', ': ')))
            else:
                print('Deletion of product %s (batch entry %d) successful.' %
                      (batch['entries'][entry['batchId']]['productId'],
                       entry['batchId']))

    else:
        print('There was an error. Response: %s' % result)
예제 #9
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = common.init(argv, __doc__, parents=[argparser])
    merchant_id = config['merchantId']
    datafeed_id = flags.datafeed_id

    request = service.datafeeds().delete(merchantId=merchant_id,
                                         datafeedId=datafeed_id)
    request.execute()
    print('Datafeed %s was deleted.' % datafeed_id)
예제 #10
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = common.init(argv, __doc__, parents=[argparser])
    merchant_id = config['merchantId']
    account_id = flags.account_id
    common.check_mca(config, True)

    request = service.accounts().delete(merchantId=merchant_id,
                                        accountId=account_id)
    request.execute()
    print('Account %s was deleted.' % account_id)
예제 #11
0
def main(argv):
  # Authenticate and construct service.
  service, config, _ = common.init(argv, __doc__)
  merchant_id = config['merchantId']

  offer_id = 'book#%s' % common.get_unique_id()
  product = sample.create_product_sample(config, offer_id)

  # Add product.
  request = service.products().insert(merchantId=merchant_id, body=product)

  result = request.execute()
  print('Product with offerId "%s" and title "%s" was created.' %
        (result['offerId'], result['title']))
예제 #12
0
def main(argv):
  # Authenticate and construct service.
  service, config, flags = common.init(
      argv, __doc__, parents=[argparser])
  merchant_id = config['merchantId']
  product_id = flags.product_id
  common.check_mca(config, False)

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

  print('- Product "%s" with title "%s":' %
        (status['productId'], status['title']))
  print(json.dumps(status, sort_keys=True, indent=2, separators=(',', ': ')))
예제 #13
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__)
    merchant_id = config['merchantId']

    name = 'feed%s' % common.get_unique_id()
    datafeed = sample.create_datafeed_sample(config, name)

    # Add datafeed.
    request = service.datafeeds().insert(merchantId=merchant_id, body=datafeed)

    result = request.execute()

    print('Datafeed with name "%s" and ID %s was created.' %
          (result['name'], result['id']))
예제 #14
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = common.init(argv, __doc__, parents=[argparser])
    merchant_id = config['merchantId']
    account_id = flags.account_id
    common.check_mca(config, True)

    new_name = 'updated-account%s' % common.get_unique_id()
    request = service.accounts().patch(merchantId=merchant_id,
                                       accountId=account_id,
                                       body={'name': new_name})

    result = request.execute()
    print('Account with id %s was updated with new name "%s".' %
          (account_id, result['name']))
예제 #15
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__)
    merchant_id = config['merchantId']
    common.check_mca(config, True)

    name = 'account%s' % common.get_unique_id()
    account = {'name': name, 'websiteUrl': 'https://%s.example.com/' % name}

    # Add account.
    request = service.accounts().insert(merchantId=merchant_id, body=account)

    result = request.execute()

    print('Created sub-account ID %s for MCA %d.' %
          (result['id'], merchant_id))
예제 #16
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = common.init(argv, __doc__, parents=[argparser])
    merchant_id = config['merchantId']
    datafeed_id = flags.datafeed_id

    # Changing the scheduled fetch time to 7:00.
    request = service.datafeeds().patch(merchantId=merchant_id,
                                        datafeedId=datafeed_id,
                                        body={'fetchSchedule': {
                                            'hour': 7
                                        }})

    result = request.execute()
    print('Datafeed with ID %s and fetchSchedule %s was updated.' %
          (result['id'], str(result['fetchSchedule'])))
예제 #17
0
def do():
    # Authenticate and construct service.
    service, config, _ = common.init(sys.argv, __doc__)
    merchant_id = config['merchantId']

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

    products = []
    while request is not None:
        result = request.execute()
        products_temp = result.get('resources')
        if not products_temp:
            print('No products were found.')
            break
        products.extend(products_temp)
        request = service.products().list_next(request, result)
    return products
예제 #18
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = 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:
        common.check_mca(
            config,
            True,
            msg='Non-multi-client accounts can only get their own information.'
        )

    account = service.accounts().get(merchantId=merchant_id,
                                     accountId=merchant_id).execute()
    print('Account %s with name "%s" was found.' %
          (account['id'], account['name']))
예제 #19
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__)

    print('--------------------------------')
    accounts.workflow(service, config)
    print('--------------------------------')
    accountstatuses.workflow(service, config)
    print('--------------------------------')
    accounttax.workflow(service, config)
    print('--------------------------------')
    datafeeds.workflow(service, config)
    print('--------------------------------')
    products.workflow(service, config)
    print('--------------------------------')
    productstatuses.workflow(service, config)
    print('--------------------------------')
    shippingsettings.workflow(service, config)
    print('--------------------------------')
예제 #20
0
def main(argv):
  # Authenticate and construct service.
  service, config, _ = common.init(argv, __doc__)
  merchant_id = config['merchantId']
  common.check_mca(config, True)

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

  while request is not None:
    result = request.execute()
    accounts = result.get('resources')
    if not accounts:
      print('No accounts were found.')
      break
    for account in accounts:
      print('Account %s with name "%s" was found.' %
            (account['id'], account['name']))
    request = service.accounts().list_next(request, result)
예제 #21
0
def main(argv):
  # Authenticate and construct service.
  service, config, _ = common.init(argv, __doc__)
  merchant_id = config['merchantId']
  common.check_mca(config, False)

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

  while request is not None:
    result = request.execute()
    statuses = result.get('resources')
    if not statuses:
      print('No product statuses were returned.')
      break
    for stat in statuses:
      print('- Product "%s" with title "%s":' %
            (stat['productId'], stat['title']))
      print(json.dumps(stat, sort_keys=True, indent=2, separators=(',', ': ')))
    request = service.productstatuses().list_next(request, result)
예제 #22
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = 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:
        common.check_mca(
            config,
            True,
            msg='Non-multi-client accounts can only get their own information.'
        )

    status = service.shippingsettings().get(merchantId=merchant_id,
                                            accountId=merchant_id).execute()
    print('Account %s:' % status['accountId'])
    postal_groups = status.get('postalCodeGroups')
    if not postal_groups:
        print('- No postal code groups.')
    else:
        print('- %d postal code group(s):' % len(postal_groups))
    services = status.get('services')
    if not services:
        print('- No services.')
    else:
        print('- %d service(s):' % len(services))
        for service in 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']))
            rate_groups = service.get('rateGroups')
            if not rate_groups:
                print('  - No rate groups.')
            else:
                print('  - %d rate group(s).' % len(rate_groups))
예제 #23
0
def main(argv):
    # Authenticate and construct service.
    service, config, flags = common.init(argv, __doc__, parents=[argparser])
    merchant_id = config['merchantId']
    product_id = flags.product_id

    new_status = {
        'availability': 'out of stock',
        'price': {
            'value': 3.00,
            'currency': 'USD'
        }
    }

    request = service.inventory().set(merchantId=merchant_id,
                                      storeCode=product_id.split(':')[0],
                                      productId=product_id,
                                      body=new_status)

    request.execute()
    print('Product with ID "%s" was updated.' % product_id)
예제 #24
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__)
    merchant_id = config['merchantId']

    batch = {
        'entries': [{
            'batchId':
            i,
            'merchantId':
            merchant_id,
            'method':
            'insert',
            'datafeed':
            sample.create_datafeed_sample(config,
                                          'feed%s' % 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:
            datafeed = entry.get('datafeed')
            errors = entry.get('errors')
            if datafeed:
                print('Datafeed %s with name "%s" created.' %
                      (datafeed['id'], datafeed['name']))
            elif errors:
                print('Errors for batch entry %d:' % entry['batchId'])
                print(
                    json.dumps(errors,
                               sort_keys=True,
                               indent=2,
                               separators=(',', ': ')))
    else:
        print('There was an error. Response: %s' % result)
예제 #25
0
def main(argv):
  # Authenticate and construct service.
  service, config, _ = common.init(argv, __doc__)
  merchant_id = config['merchantId']
  common.check_mca(config, True)

  account_names = [
      'account%s' % 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']:
      account = entry.get('account')
      errors = entry.get('errors')
      if account:
        print('Account %s with name "%s" was created.' %
              (account['id'], account['name']))
      elif errors:
        print('Errors for batch entry %d:' % entry['batchId'])
        print(json.dumps(errors, sort_keys=True, indent=2,
                         separators=(',', ': ')))
  else:
    print('There was an error. Response: %s' % result)
예제 #26
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__)
    merchant_id = config['merchantId']
    adwords_id = config.get('accountSampleAdWordsCID')
    if not adwords_id:
        print('Must specify the AdWords CID to unlink in the samples config.')
        sys.exit(1)

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

    adwords_links = account.get('adwordsLinks')
    if not adwords_links:
        print('No AdWords accounts linked to account %d.' % merchant_id)
        sys.exit(1)

    # Do an integer comparison to match the version from the configuration.
    matched = [l for l in adwords_links if int(l['adwordsId']) == adwords_id]
    if not matched:
        print('AdWords account %d was not linked.' % adwords_id)
        sys.exit(1)

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

    # 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))
예제 #27
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__)
    merchant_id = config['merchantId']
    email = config.get('accountSampleUser')
    if not email:
        print(
            'Must specify the user email to remove in the samples configuration.'
        )
        sys.exit(1)

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

    users = account.get('users')
    if not users:
        print('No users in account %d.' % merchant_id)
        sys.exit(1)

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

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

    # 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))
예제 #28
0
def do(list_offers):
  # Authenticate and construct service.
  service, config, _ = common.init(sys.argv, __doc__)
  merchant_id = config['merchantId']
  batch_size = len(list_offers)

  batch = {
      'entries': [{
          'batchId': i,
          'merchantId': merchant_id,
          'method': 'insert',
          'product': sample.create_product_sample(
              config,
              common.get_unique_id(),
              list_offers[i]),
          } for i in range(batch_size)],
  }

  # print(batch['entries'][0])
  request = service.products().custombatch(body=batch)
  result = request.execute()

  if result['kind'] == 'content#productsCustomBatchResponse':
    entries = result['entries']
    for entry in entries:
      product = entry.get('product')
      errors = entry.get('errors')
      if product:
        print('Product "%s" with offerId "%s" and title "%s" was created.' %
              (product['id'], product['offerId'], product['title']))
      elif errors:
        print('Errors for batch entry %d:' % entry['batchId'])
        print(json.dumps(errors, sort_keys=True, indent=2,
                          separators=(',', ': ')))
  else:
    print('There was an error. Response: %s' % result)
예제 #29
0
def main(argv):
  # Authenticate and construct service.
  service, config, _ = common.init(argv, __doc__)

  workflow(service, config)
예제 #30
0
def main(argv):
    # Authenticate and construct service.
    service, config, _ = common.init(argv, __doc__, sandbox=True)
    orders = service.orders()
    merchant_id = config['merchantId']

    # Create a new test order using the template1 template. Normally, orders
    # would be automatically populated by Google in the non-sandbox version,
    # and we'd skip ahead to find out what orders are currently waiting for us.
    print('Creating new test order... ', end='')
    request = orders.createtestorder(merchantId=merchant_id,
                                     body={'templateName': 'template1'})
    response = request.execute()
    order_id = response['orderId']
    print('done (%s).\n' % order_id)

    # List all unacknowledged orders.  A call like this is where we'd normally
    # get new order_id values to operate on.
    print('Listing unacknowledged orders for merchant %d:' % merchant_id)
    _list_all_orders(orders, merchant_id, acknowledged=False)
    print()

    # Acknowledge the newly received order.
    print('Acknowledging order %s... ' % order_id, end='')
    request = orders.acknowledge(merchantId=merchant_id,
                                 orderId=order_id,
                                 body={'operationId': _new_operation_id()})
    response = request.execute()
    print('done (%s).\n' % response['executionStatus'])

    # Set the new order's merchant order ID. For here, we'll just use a
    # random int of 32 bits.
    merchant_order_id = 'test order %d' % random.getrandbits(32)
    print('Updating merchant order ID to "%s"... ' % merchant_order_id, end='')
    request = orders.updatemerchantorderid(merchantId=merchant_id,
                                           orderId=order_id,
                                           body={
                                               'operationId':
                                               _new_operation_id(),
                                               'merchantOrderId':
                                               merchant_order_id
                                           })
    response = request.execute()
    print('done (%s).\n' % response['executionStatus'])

    print('Retrieving merchant order "%s"... ' % merchant_order_id, end='')
    request = orders.getbymerchantorderid(merchantId=merchant_id,
                                          merchantOrderId=merchant_order_id)
    current_order = request.execute()['order']
    print('done.\n')
    utils.print_order(current_order)
    print()

    # Oops, not enough stock for all the Chromecasts ordered, so we cancel
    # one of them.
    print('Canceling one Chromecast order... ', end='')
    request = orders.cancellineitem(
        merchantId=merchant_id,
        orderId=order_id,
        body={
            'operationId': _new_operation_id(),
            'lineItemId': current_order['lineItems'][0]['id'],
            'quantity': 1,
            'reason': 'noInventory',
            'reasonText': 'Ran out of inventory while fulfilling request.'
        })
    response = request.execute()
    print('done (%s).\n' % response['executionStatus'])

    request = orders.get(merchantId=merchant_id, orderId=order_id)
    current_order = request.execute()
    utils.print_order(current_order)
    print()

    # Advance the test order to the shippable state. Normally this would be done
    # by Google when an order is no longer cancelable by the customer, but here
    # we need to do it manually.
    print('Advancing test order... ', end='')
    orders.advancetestorder(merchantId=merchant_id, orderId=order_id).execute()
    print('done.\n')

    request = orders.get(merchantId=merchant_id, orderId=order_id)
    current_order = request.execute()
    utils.print_order(current_order)
    print()

    # To simulate partial fulfillment, we'll pick the first line item and
    # ship the still-pending amount.
    print('Notifying Google about shipment of first line item... ', end='')
    # Storing the request body so we can access the randomly generated
    # shipping/tracking IDs later. Normally we'd just look them
    # up in information we'd store about each shipment.
    item1 = current_order['lineItems'][0]
    shipping_request_1 = {
        'lineItems': [{
            'lineItemId': item1['id'],
            'quantity': item1['quantityPending']
        }],
        'carrier':
        item1['shippingDetails']['method']['carrier'],
        'shipmentId':
        '%d' % random.getrandbits(32),
        'trackingId':
        '%d' % random.getrandbits(32),
        'operationId':
        _new_operation_id()
    }
    request = orders.shiplineitems(merchantId=merchant_id,
                                   orderId=order_id,
                                   body=shipping_request_1)
    response = request.execute()
    print('done (%s).' % response['executionStatus'])

    request = orders.get(merchantId=merchant_id, orderId=order_id)
    current_order = request.execute()
    utils.print_order(current_order)
    print()

    # Now we ship the rest.
    print('Notifying Google about shipment of second line item... ', end='')
    item2 = current_order['lineItems'][1]
    shipping_request_2 = {
        'lineItems': [{
            'lineItemId': item2['id'],
            'quantity': item2['quantityPending']
        }],
        'carrier':
        item2['shippingDetails']['method']['carrier'],
        'shipmentId':
        '%d' % random.getrandbits(32),
        'trackingId':
        '%d' % random.getrandbits(32),
        'operationId':
        _new_operation_id()
    }
    request = orders.shiplineitems(merchantId=merchant_id,
                                   orderId=order_id,
                                   body=shipping_request_2)
    response = request.execute()
    print('done (%s).' % response['executionStatus'])

    request = orders.get(merchantId=merchant_id, orderId=order_id)
    current_order = request.execute()
    utils.print_order(current_order)
    print()

    # Customer receives the first item.
    print('Notifying Google about delivery of first line item... ', end='')
    request = orders.updateshipment(merchantId=merchant_id,
                                    orderId=order_id,
                                    body={
                                        'shipmentId':
                                        shipping_request_1['shipmentId'],
                                        'trackingId':
                                        shipping_request_1['trackingId'],
                                        'carrier':
                                        shipping_request_1['carrier'],
                                        'status':
                                        'delivered',
                                        'operationId':
                                        _new_operation_id()
                                    })
    response = request.execute()
    print('done (%s).\n' % response['executionStatus'])

    request = orders.get(merchantId=merchant_id, orderId=order_id)
    current_order = request.execute()
    utils.print_order(current_order)
    print()

    # Customer receives the second item.
    print('Notifying Google about delivery of second line item... ', end='')
    request = orders.updateshipment(merchantId=merchant_id,
                                    orderId=order_id,
                                    body={
                                        'shipmentId':
                                        shipping_request_2['shipmentId'],
                                        'trackingId':
                                        shipping_request_2['trackingId'],
                                        'carrier':
                                        shipping_request_2['carrier'],
                                        'status':
                                        'delivered',
                                        'operationId':
                                        _new_operation_id()
                                    })
    response = request.execute()
    print('done (%s).\n' % response['executionStatus'])

    request = orders.get(merchantId=merchant_id, orderId=order_id)
    current_order = request.execute()
    utils.print_order(current_order)
    print()

    # Customer returns one of the first item due to being broken on delivery.
    print('Notifying Google about return of first line item... ', end='')
    request = orders.returnlineitem(merchantId=merchant_id,
                                    orderId=order_id,
                                    body={
                                        'lineItemId': item1['id'],
                                        'quantity': 1,
                                        'reason': 'productArrivedDamaged',
                                        'reasonText':
                                        'Item broken at receipt.',
                                        'operationId': _new_operation_id()
                                    })
    response = request.execute()
    print('done (%s).\n' % response['executionStatus'])

    request = orders.get(merchantId=merchant_id, orderId=order_id)
    current_order = request.execute()
    utils.print_order(current_order)
    print()