Search code examples
pythonibm-cloudibm-cloud-infrastructurebillinginvoice

Is that possible to get invoices by users?


I am trying to calculate how many items and cost by each sub-account. I read the article. It shows using "getNextInvoiceTopLevelBillingItems" (http://knowledgelayer.softlayer.com/procedure/how-extract-user-billing-information-using-softlayers-api).

However, Billing items is not like invoices. For example, billing item only show vCPU total amount, not show RAM and DISK and NIC amounts. If I'd like to get all invoices, the function will be getInvoices under SoftLayer_Account.

Can billing_items related to invoices? or just grab all invoices, but how can invoice relate to user?


Solution

  • Yes, they can. The article you read allows to know the totalRecurringAmount and associated user of each SoftLayer_Billing_Item on next invoice. Take account that items in an invoice could had been ordered by different users.

    If you want to get same information for all invoices in the Account, you need to use the same idea by using getInvoices method but first you need to understand how it is structured. A Softlayer_Billing_Invoice object has a list of SoftLayer_Billing_Invoice_Item items and each one is associated to a SoftLayer_Billing_item object, as you can see, this is the relation you asked for.

    Below is the object mask you can use to get the billing items associated to users on each invoice, this using getInvoices method:

    object_mask="mask[id,items[id,description,billingItem[id,orderItem[id,order[id,status,userRecord[id,firstName,lastName]]],invoiceItem[id,totalRecurringAmount]]]]"
    

    But take account that an invoice can have hundred or thousand of items and you may get time out or server internal errors due to that. To avoid them I recommend you to use result limits.

    Below is a complete example in python.

    import SoftLayer
    from pprint import pprint as pp
    
    user_name = 'set-me'
    user_key = 'set-me'    
    
    client = SoftLayer.create_client_from_env(username=user_name, api_key=user_key)
    
    object_mask = "mask[id,items[id,description,billingItem[id,orderItem[id," \
                  "order[id,status,userRecord[id,firstName,lastName]]]," \
                  "invoiceItem[id,totalRecurringAmount]]]]";
    
    user_bill = client['Account'].getInvoices(mask=object_mask, limit=10, offset=0)
    
    pp(user_bill)