Skip to Content
Technical Articles
Author's profile photo Yogananda Muthaiah

Most commonly used IronPython functions in SAP CPQ

 

 

List of reserved Keywords in IronPython

Reserved words (also called keywords) are defined with predefined meaning and syntax in the language. These keywords have to be used to develop programming instructions. Reserved words can’t be used as identifiers for other programming elements like name of variable, function etc.

and       del       from      None      True
as        elif      global    nonlocal  try
assert    else      if        not       while
break     except    import    or        with
class     False     in        pass      yield
continue  finally   is        raise
def       for       lambda    return

SAP CPQ Scripting Documentation

Showing custom messages

Quote 1.0 Quote 2.0
Quote.Messages.Add("Script is executed")
from Scripting.Quote import MessageLevel
context.Quote.AddMessage("Success", MessageLevel.Success, False)
context.Quote.AddMessage("Error", MessageLevel.Error, False)
context.Quote.AddMessage("Info", MessageLevel.Info, False)
context.Quote.AddMessage("Warning", MessageLevel.Warning, False)
context.Quote.AddMessage("Success", MessageLevel.Success, True)
context.Quote.AddMessage("Error", MessageLevel.Error, True)
context.Quote.AddMessage("Info", MessageLevel.Info, True)
context.Quote.AddMessage("Warning", MessageLevel.Warning, True)

Setting visibility of Custom Field

Quote.GetCustomField("Custom Field 2").Visible = False

Quote.GetCustomField("Custom Field 1").Visible = True

To format custom field to Decimal Value (commas as thousand separators)

##CTX Tag ##

<*CTX( Number(<*CTX(Quote.CustomField(Net Price) )*>).ToFormat(1234.56))*>
### Output  ##
1,234.56

convertdouble = 12345.87
converted = format(convertdouble, "03,.2f")

###Output####
12,345.87

Getting Quote Order Status translated name in currently selected language

if Quote.OrderStatus is not None:
    if Quote.OrderStatus.NameTranslated == "Waiting for Approval":
        Quote.ChangeQuoteStatus("Approved")

Setting Quote Total Amount

result += Quote.Total.ShippingCost

if Quote.IncludeTaxInTotalPrice:
    result += Quote.Total.TaxAmount
    result += Quote.Total.VatAmount

Quote.Total.TotalAmount = result

Add your scripts to Trace the logs for Troubleshooting

Log.Info("Script is started")
Log.Info("Script is Ended")

Trace.Write("Script is Started")

List of core Python functions

Comments in python

single line - use #

# single line comments

multiline use '''. often called as docstring, as it is just 
to document function/classes. 

'''
This is a example of 
Multiline comment.
'''
import re
txt = "Quote Status is in Approved"
#Check if "Aproved" is in the string:
x = re.findall("Approved", txt)
print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

To Sort

ListPrice = [589.36, 237.81, 230.87, 463.98, 453.42]
ListPrice.sort()

##  Output  ###
[230.87, 237.81, 453.42, 463.98, 589.36]

To convert absolute number

negative_number  = -676
print(abs(negative_number))

##  Output  ###
676

Lambda

add = (lambda x: x + 1)(2)

##  Output  ###
3



add_one = lambda x: x + 1
aa = add_one(2)

##  Output  ###
3

Append

months = ['January', 'February', 'March']
months.append('April')
Trace.Write(months)

##  Output  ###
['January', 'February', 'March', 'April']

Union

l1 = {1, 2, 3}
l2 = [2, 3, 4]
output = l1.union(l2)

## Output ####
{1, 2, 3, 4}

Extend

list = [1, 2, 3]
list.extend([4, 5, 6])
list

##  Output  ###
[1, 2, 3, 4, 5, 6]

Index and Max

months = ['January', 'February', 'March', 'April', 'May']
index = months.index('March')

print(index)
##  Output  ###
2


prices = [589.36, 237.81, 230.87, 463.98, 453.42]
price_max = max(prices)
print(price_max)

##  Output  ###
589.36

To find Min and Max Prices from Index

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]

min_price = min(prices)
# Identify min price index
min_index = prices.index(min_price)
# Identify the month with min price
min_month = months[min_index]

print(min_price)
print(min_index)
print(min_month)

##  Output  ###
237.81
1
February

List

list_1 = [50.29]
list_2 = [76.14, 89.64, 167.28]
print('list_1 length is ', len(list_1))
print('list_2 length is ', len(list_2))

##  Output  ###
list_1 length is  1
list_2 length is  3

Space

string = 'SAP CPQ'
yoga = (string.isspace())

### Output ##
False


string1 = '\n \n \n'
yoga = (string.isspace())

### Output ##
True

Count

fruits = ['cherry', 'apple', 'cherry', 'banana', 'cherry']
x = fruits.count("cherry")

##  Output  ###
3

Insert

fruits = ['apple', 'banana', 'cherry']
fruits.insert(2, "pineapple")

##  Output  ###
['apple', 'banana', 'pineapple', 'cherry']

Remove

fruits = ['apple', 'banana', 'cherry', 'orange', 'pineapple']
fruits.remove("banana")

##  Output  ###
['apple', 'cherry', 'orange', 'pineapple']

Zip

labelnames = ("QuoteId", "ListPrice", "NetPrice", "SoldtoParty")
value = (02111111, 4000, 6000, "Yogananda")

zipped = zip(labelnames, value)

for(x,y) in zipped:
    print(x,y)

### Output ###
# QuoteId 02111111
# QuoteId 4000
# QuoteId 6000
# QuoteId Yogananda

Reverse

qutoes = ['NetPrice', 'ListPrice', 'BasePrice', 'AdditionalDiscount', 'Shipping']
qutoes.reverse()

##  Output  ###
['Shipping', 'AdditionalDiscount', 'BasePrice', 'ListPrice', 'NetPrice']

Map

values = [10, 20, 30]

def Add(values):
    return values + 10

result = map(Add, values)

print(list(values))
print(list(result))
######## Output  #####
[10, 20, 30]
[20, 30, 40]

Copy

quotes= ['Discount 1', 'Rewards', 'Bonus', 'Incentives']
x = quotes.copy()

##  Output  ###
['Discount 1', 'Rewards', 'Bonus', 'Incentives']

Clear

months = ['January', 'February', 'March', 'April', 'May']
months.clear()

##  Output  ###
[ ]

Decorators

def log_result(func):
    def inner(*args, **kwargs):
        res = func(*args, **kwargs)
        print("The result is ", res)
        return res
    return inner


@log_result
def sum(a, b):
    return a+b


l = sum(3, 5)

## Output ##
8

String Functions

##Replace all occurrences of the word “Gartner”

string = "SAP Named a Leader in Gartner Magic Quadrant for CPQ"
aa = (string.replace("Gartner", "Gartner's"))


##Replace only the first occurrence of the word “SAP”
string = "SAP CPQ videos is now available in SAP Microlearning"
bb = (string.replace("SAP", "SAP", 1))


##Make the lower case letters to upper case and the upper case letters to lower case
string = "SAP CPQ can be integrated end to end solution with ERP and S4HANA"
ccc = (string.swapcase())


myTuple = ("Data Scientists", "Machine Learning", "Data Science")
x = "#".join(myTuple)

myDict = {"name": "Aa", "country": "India", "Technology": "Data Science"}
mySeparator = "TEST"
x1 = mySeparator.join(myDict)

Class Function

class MyClass:
x = 5

p1 = MyClass()
aa = p1.x

 

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

aas = (p1.name)
ksk = (p1.age)

Exception

try:
    print(sorted([1, 2, 3]))
    except Exception as error:
        print("Something went wrong")
        print(error)
        else:
            print("Nothing went wrong")

Exception

try:
    print(int("Hello"))
    except NameError:
        print("A NameError occured")
        except TypeError:
            print("A TypeError occured")
            except ValueError:
                print("A ValueError occured")
                except:
                    print("Another type of error occured")

Identify Performance of the script time taken

from datetime import datetime
start_time = datetime.now()


# let your script work does here


end_time = datetime.now()
Totaltime = ('Duration: {}'.format(end_time - start_time))

 

If anything you would like to tell the new way, add it in below comment

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.