Python - How to Set Custom Fields using NetSuite webservices - python

I'm trying to be able to set a custom fields in NetSuite using webservices.
The WSDL I'm using is: https://webservices.netsuite.com/wsdl/v2017_2_0/netsuite.wsdl
Currently I'm testing it on creating a customer. Here's what I have so far:
def add_customer():
client = login_client()
RecordRef = client.get_type('ns0:RecordRef')
Customer = client.get_type('ns13:Customer')
customer = Customer(
companyName='TEST',
subsidiary = RecordRef(internalId='5', type='subsidiary')
)
response = client.service.add(customer)
print(response)
add_customer()
This Works perfectly, but now I'm trying to set a custom field with id custfield1
After doing some searching, I found:
http://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2016_2/schema/other/customfieldlist.html?mode=package
From this link I know that I'll be needing to use CustomFieldRef, I'm just not sure how it would be implemented.

I found a way to do this:
def add_customer():
client = login_client()
RecordRef = client.get_type('ns0:RecordRef')
StringCustomFieldRef = client.get_type('ns0:StringCustomFieldRef') #StringCustomFieldRef
CustomFieldList = client.get_type('ns0:CustomFieldList') #To go from object to list
#Cust field 1
acctName = StringCustomFieldRef()
acctName.internalID = '1569'
acctName.scriptId = 'custentity_account_name'
acctName.value = 'testData'
#custField2
acctID= StringCustomFieldRef()
acctID.internalId= '1596'
acctID.scriptId= 'custentity_sf_account_id'
acctID.value = 'FIELD DATA'
Customer = client.get_type('ns13:Customer')
customer = Customer(
companyName='TEST',
entityId='TEST ID',
subsidiary = RecordRef(internalId='5', type='subsidiary'),
customFieldList = CustomFieldList([acctID,acctName]) #List of cust objects
)
response = client.service.add(customer)
print(response)
add_customer()
You have to use the Ref type for the field you are working with: https://system.na1.netsuite.com/app/help/helpcenter.nl?fid=section_n3458179.html

Related

Zenpy; custom fields are not being updated

So within Zendesk I created these custom fields as follows:
and now I am trying to create a user with all these fields filled with preset values. But when I try to create users, like follows:
for row in df.iloc[1:11].fillna(0).iterrows():
user = User(name = row[1].first_name,
email = row[1].email,
lifetime_value = row[1].purchased_total_value,
first_order = row[1].first_purchased,
last_order = row[1].last_purchased,
products_ordered = row[1].purchased_product_count,
total_orders = row[1].purchased_unique_orders,
total_returns = row[1].total_returns,
products_returned = row[1].products_returned,
pro_account = pd.notna(row[1].proaccount_deal),
verified=True)
created_user = zenpy_client.users.create(user)
All users are created however only with email and name fields filled up and all the custom fields which I created are empty. Zenpy's User() function is not very informative in this regard however it accepts **kwargs** and as per json representations in documentation, it should work in theory. Any workaround or my mistakes in this regard?
Have you tried using user_fields?
for row in df.iloc[1:11].fillna(0).iterrows():
uf = {"lifetime_value" : row[1].purchased_total_value,
"first_order" : row[1].first_purchased,
"last_order" : row[1].last_purchased,
"products_ordered" : row[1].purchased_product_count,
"total_orders" : row[1].purchased_unique_orders,
"total_returns" : row[1].total_returns,
"products_returned" : row[1].products_returned,
"pro_account" : pd.notna(row[1].proaccount_deal),
"verified":True}
user = User(name = row[1].first_name, email = row[1].email, user_fields=uf)
created_user = zenpy_client.users.create(user)
This should work, but if it doesn't you could try creating the user first and then querying for them, and then seeing all of your custom fields in user.user_field.
Doing so would allow you to see all the available custom user fields you can enter in. From there you can update the object and zenpy_client.users.update(user) it into the system.

How to add invoice to Quickbooks using their API with Python?

I wonder how can I add an invoice via Quickbooks API v3 using Python. A script with minimum requirements would be appreciated.
I am new to APIs so, I am interested if I can write a simple script without running server to upload invoices to QuickBooks. If not, I guess I should use Django or Flask right?
Thank you in advance.
here is a simple example of how to create a single-line Invoice with only required fields.
from quickbooks.objects import (Invoice,
SalesItemLineDetail,
SalesItemLine)
customer_ref = Ref()
customer_ref.value = 123
customer_ref.name = 'Ivan Petrov'
customer_ref.type = 'Customer'
# or customer_ref = Customer.get(123, qb=client).to_ref()
line_detail = SalesItemLineDetail()
line_detail.UnitPrice = 100 # in dollars
line_detail.Qty = 1 # quantity can be decimal
line = SalesItemLine()
line.Amount = 100 # in dollars
line.SalesItemLineDetail = line_detail
invoice = Invoice()
invoice.CustomerRef = customer_ref
invoice.Line = [line]
client = QuickBooks(...)
invoice.save(qb=client)
follow this link for more explanation www.github.com/ej2/python-quickbooks/issues/103
You can use python-quickbooks library.
There are also examples how to use it:
from intuitlib.client import AuthClient
from quickbooks import QuickBooks
auth_client = AuthClient(
client_id='CLIENT_ID',
client_secret='CLIENT_SECRET',
environment='sandbox',
redirect_uri='http://localhost:8000/callback',
)
client = QuickBooks(
auth_client=auth_client,
refresh_token='REFRESH_TOKEN',
company_id='COMPANY_ID',
)
customer = Customer()
customer.CompanyName = "Test Company"
customer.save(qb=client)
For invoice, you must have a customer who will pay, accounts for expense and income, and item of service or product that provide to the customer.
# client is your quickbook object
customer = Customer()
customer.CompanyName = "Test221wq Company"
customer.DisplayName = "Test3wrq1 Owner"
customer.PrimaryEmailAddr = EmailAddress()
customer.PrimaryEmailAddr.Address = "test1wq3#email.com"
customer.save(qb=client)
print(customer.__dict__)
income_account = Account()
income_account.Name = "Test3w1 Account"
income_account.AccountSubType = "ServiceFeeIncome"
income_account.CurrentBalanceWithSubAccounts = 500
income_account.save(qb=client)
print(income_account.__dict__)
expense_account = Account()
expense_account.Name = "Test4 Account"
expense_account.AccountSubType = "CostOfLabor"
expense_account.CurrentBalanceWithSubAccounts = 1000
expense_account.save(qb=client)
print(expense_account.__dict__)
item = Item()
item.Name = "Test Service Item"
item.IncomeAccountRef = income_account.to_ref()
item.ItemCategoryType = "Service"
item.ExpenseAccountRef = expense_account.to_ref()
item.Type = "Service"
item.save(qb=client)
print(item.__dict__)
line = SalesItemLine()
line.LineNum = 1
line.Description = "fieldworkers"
line.Amount = 100
line.SalesItemLineDetail = SalesItemLineDetail()
line.SalesItemLineDetail.ItemRef = item.to_ref()
invoice = Invoice()
invoice.CustomerRef = customer.to_ref()
invoice.Line.append(line)
invoice.save(qb=client)
print(invoice.__dict__)
This is enough to generate an invoice.

Is the following the correct way to obtain unique id in app engine datastore

I have a legacy Google App engine code, which is having the following entity classes in Python
class AffiliateParent(db.Model):
name = db.StringProperty(required = True)
class Affiliate(db.Model):
email = db.StringProperty(required = True)
point_gain = db.IntegerProperty()
point_used = db.IntegerProperty()
#feature_upgrade = db.ListProperty(str)
modified_time = db.DateTimeProperty(auto_now = True)
I was wondering, is the following the correct way to generate unique id? Are they guarantee unique within Affiliate table?
affiliate_parent_key = AffiliateParent.all(keys_only=True).filter('name =', 'yancheng').get();
affiliate_parent = db.get(affiliate_parent_key);
# check whether affiliate exist, if not create one
affiliate_parent = db.get(affiliate_parent_key);
q = Affiliate.all()
q.ancestor(affiliate_parent)
q.filter('email =', email)
affiliate = q.get()
if not affiliate:
affiliate = Affiliate(
email = email,
point_gain = 0,
point_used = 0,
parent = affiliate_parent
)
affiliate.put()
# 4503602445942784
# is this unique?
unique_id = affiliate.key().id()
yes, if you don't supply id or key when instantiating the model, then datastore will generate a unique ID and assign it to your entity when you .put() it... thus affiliate.key.id() will be unique
you can also generate unique IDs using allocate_ids(count)
https://cloud.google.com/appengine/docs/python/datastore/functions#allocate_ids

account.number is required (recurly)

I'm trying to create a Recurly account using their python API, and keep hitting the same error:
def upsert_recurly_account(office):
try:
account = recurly.Account.get(office.pk)
except recurly.errors.NotFoundError:
logger.warning("Creating new recurly account for pk %s" % office.pk)
account = recurly.Account(account_code=office.pk)
else:
logger.info("Recurly account %s already exists, we will update it")
account.email = office.manager.email
account.first_name = office.manager.first_name
account.last_name = office.manager.last_name
account.company_name = '%s - %s' % (office.legal_name, office.name)
account.vat_number = office.tax_id
account.tax_exempt = office.tax_exempt
billing_info = recurly.BillingInfo()
billing_info.first_name = office.manager.first_name
billing_info.last_name = office.manager.last_name
billing_info.address1 = office.address1
billing_info.address2 = office.address2
billing_info.city = office.city
billing_info.country = office.country
billing_info.zip = office.postal_code
billing_info.phone = office.phone
billing_info.vat_number = office.tax_id
account.billing_info = billing_info
account.save()
The error I'm getting is:
ValidationError:required: account.number is required
Manually adding
account.number = 1234
Doesn't solve the problem.
Any ideas?
Since you're creating a new Account with nested billing info you need to provide a valid credit card number in the billing_info hash like so:
billing_info.number = 123
There are other mandatory fields (like month and year) when creating a new account with nested billing info. Please read the docs
Account.number isn't a valid Recurly field - it looks like you need to be passing through account_code - see the sample at https://docs.recurly.com/api/accounts#create-account

Separating "user-owned" from "other" data in Django template

I have an Openstack-powered, Django-modified application that shows the disk images and snapshots available for a user to launch. The user currently sees both snapshots they created and ones they did not. I would like to separate the current table into two based on whether they are owned by the user or not.
My two table definitions are as follows (note I altered row_actions accordingly):
class UserSnapshotsTable(OldSnapshotsTable):
cloud = tables.Column(get_cloud, verbose_name=_("Cloud"))
class Meta:
name = "usersnapshots"
verbose_name = _("User Snapshots")
table_actions = (DeleteSnapshot,)
row_actions = (LaunchSnapshot, LaunchCluster, EditImage, DeleteSnapshot)
pagination_param = "snapshot_marker"
row_class = UpdateRow
status_columns = ["status"]
class OtherSnapshotsTable(OldSnapshotsTable):
cloud = tables.Column(get_cloud, verbose_name=_("Cloud"))
class Meta:
name = "othersnapshots"
verbose_name = _("Other Snapshots")
table_actions = (DeleteSnapshot,)
row_actions = (LaunchSnapshot, LaunchCluster)
pagination_param = "snapshot_marker"
row_class = UpdateRow
status_columns = ["status"]
I have altered the HTML template to pull the "UserSnapshotsTable" and "OtherSnapshotsTable" tables (I copied the original table and renamed both), but both full tables still generate under the respective headings. There are two functions generating the data:
def get_usersnapshots_data(self):
req = self.request
marker = req.GET.get(UserSnapshotsTable._meta.pagination_param, None)
try:
usersnaps, self._more_snapshots = api.snapshot_list_detailed(req,
marker=marker)
except:
usersnaps = []
exceptions.handle(req, _("Unable to retrieve user-owned snapshots."))
return usersnaps
def get_othersnapshots_data(self):
req = self.request
marker = req.GET.get(OtherSnapshotsTable._meta.pagination_param, None)
try:
othersnaps, self._more_snapshots = api.snapshot_list_detailed(req,
marker=marker)
except:
othersnaps = []
exceptions.handle(req, _("Unable to retrieve non-user-owned snapshots."))
return othersnaps
There are also Edit/Delete options defined for images, and imported for snapshots, that seem to have a key comparison. Here's the "Delete" one (line 7):
class DeleteImage(tables.DeleteAction):
data_type_singular = _("Image")
data_type_plural = _("Images")
def allowed(self, request, image=None):
if image:
return image.owner == request.user.tenant_id
# Return True to allow table-level bulk delete action to appear.
return True
def delete(self, request, obj_id):
api.image_delete(request, obj_id)
How can I separate those tables out? This is my first time asking a question here, so please let me know if I can provide further information. Apologies for the length of it.
As far as I see you are using glanceclient. If that so you can use extra_filters parameter of snapshot_list_detailed() to filter only user images like this:
usersnaps, self._more_snapshots = api.snapshot_list_detailed(
req,
marker = marker,
extra_filters = {"owner": "user_name"}
)
Under cover snapshot_list_detailed uses GET images of Openstack Image Service API.

Categories