Documente Academic
Documente Profesional
Documente Cultură
March 2014
1 Introduction
SAP Sourcing supports scripting as a key feature in extending its default functionality. Scripting is also used
to implement workflow approvals, which enable implementation of complex business rules.
1.3 Terminology
Class: The SAP Sourcing class that is being scripted.
Collaborator: A SAP Sourcing user who has rights to a document.
Collaborator role: A role that defines the rights a collaborator has to a given document.
Collection: A group of data of the same type, subordinate to a parent document. In the UI, this data is
rendered in a tabulated form.
Document (syn. Business Document, Object): An instance of the class.
Extension collection: A collection that is user defined. Members of extension collections implement
[ExtensionCollectionMemberIfc] OR [the interface ExtensionCollectionMemberIfc].
Extension member (syn. Member): An IBean that is part of a collection. Members of extension collections
implement the ExtensionCollectionMemberIfc. Members of system collections return either an anonymous
system type or a predefined member type. See the IAPI Documentation for detailed information.
Home: A class that manages Lifecycle tasks related to its associated IBean. Every IBean has the Home
interface.
IBean: Any class that implements IBeanIfc. Every scriptable object is of this type.
Import Record: A data structure containing the raw data from the inbound import file for one record.
Script manager: The part of the underlying application that manages the script from creation to finish.
SSWP: The transportable workflow process file format created by the SAP Sourcing workflow editor.
Subordinate: A class or object that is part of a collection within a top-level class. Collaborators, extension
collections, and RFx line items are all subordinate classes.
System collection: A collection that is part of the SAP Sourcing class by design. Scripting accesses these
collections via the parent classs accessors. Members of these collections may have IAPI-defined types.
Top level (syn. Container): A class of objects that are by design not subordinate to another object. Projects,
companies, master agreements, and agreements are all top-level objects.
Workflow definition: The object in SAP Sourcing that represents the defined workflow process.
Workflow engine: The part of SAP Sourcing that manages a workflow process.
Workflow item: The specific activity in a workflow process.
Workflow process: The active instance of a workflow definition.
Workflow process template: A script file that defines the acceptable approval statuses, routing, and
conditions for each workflow definition. The process template can be created in SSWP format using an
internal workflow editor or uploaded from an externally created XPDL file.
XPDL: The legacy format for workflow process files.
2 Scripting
Context Description
Field Validation A script at the field level executes when the document is fully
validated, typically while saving or before a phase change in a
business document that supports configurable phases.
Field Data Edit A script in which both the old and new values of a field are known.
This script executes during tab changes, auto-refreshing fields, and
when the document is fully validated, as with a field context.*
Note
During field data edit, the target field's old and new
values are accessible via scripted variables. However, if
the same script accesses other fields in the business
document (that is, not the target field) and those fields
have been modified, but not saved, the script only
shows those fields' old values. For example, if a user
changes the display name of a document from Project
Foo to Project Bar, during a field data edit for another
field, and the script invokes doc.getDisplayName(),
it returns Project Foo.
Collection Validation As with a field context, when a collection is scripted, the script
executes if a collection changes or when the parent document is fully
validated.
Toolbar A script that runs on user action by means of a drop-down list on the
document toolbar. Toolbar scripts are only supported by top-level
business documents. Collections do not support toolbar scripts.
Context Description
Import Lifecycle Event A script that executes during data import as dictated by the target
lifecycle. Import lifecycle scripts allow access to inbound data and
newly created business objects.
Loaded Point at which the document is loaded Of limited use, as the document is not
and not editable, for example, when changeable at the time it is loaded.
selecting a project from the My
Projects picker. A number of internal Caution
processes invoke this event, such as
Extreme care should be exercised, as
the daemon responsible for pushing
scripting this event can cause
document security template changes.
performance issues and other
undesirable effects.
Created Point at which the class is instantiated Ideal time to provide alternative
as new defaults. Does not execute when the
Create from Template or Document
Duplicate actions are performed.
Duplicated Creation of a document using the As with the Created event, this is a
Duplicate button or Create from good opportunity to provide alternative
Template option defaults.
Pre Phase On business documents that support Scripts that raise exceptions in this
Change configurable phase definitions, a script context stop the phase change from
that executes prior to the phase occurring. In addition, the document is
change. RFx and Auction phases are fully validated prior to this script, which
not included. includes the execution of any scripts.
Post Phase Script that executes immediately after As the phase change has already
Change the phase change occurred and the document is fully
validated, no additional validation
should be done at this time and no
changes should be made to the
document.
Pre Publish On business documents that support The business document is saved prior
to ERP publishing to ERP, a script that to the execution of this script. Any
executes prior to the publishing exceptions that are raised in this
context stop the publishing from
occurring.
Validated Document validation scripts run when Useful for field validations that are
the document changes and the user dependent on each other. This is the
saves the document, or another action final point at which changes can be
is taken, such as a phase change, that made safely by a script.
invokes a validation.
Saved Once the documentation passes This script is most useful for integration
validation and is stored in the to other systems, because the
database, this script executes. document is both valid and persistent
in SAP Sourcing. No exceptions should
ever be raised by a script for this
event, as undesirable results will occur.
Scripts should account for this in a try
..catch block. Alterations to the
business document affect the post-
saved version and cause confusion for
users.
Should Process Gives the opportunity to Record The script must return a
Row reject the import of a Boolean object .
particular row.
Process Row Gives the opportunity to iBean
manipulate the newly
constructed iBean before
it is saved.
Ok To Save Gives the opportunity to iBean The script must return a
reject the save of a Boolean object.
particular iBean
Save Gives the opportunity to iBean Could be used to write out
act on the iBean *after* it custom log information, or
has been saved. send custom notifications.
Final This is the mirror image None
of the Init event. Allows
scripting after the import
of the entire file has
completed.
Toolbar Script Visibility View Mode, Edit Mode, or View Toolbar All top-level
or Edit Mode. Controls what edit scripts only classes
state the document can be in
before the script is executable.
Collection members are also business documents in their own right, but are always wrapped in a parent
document. As they are business documents, each supports the DLC events. During script definition, if the
context selected is Collection, a list of collections for the selected class is shown. However, if the context
selected is Document Lifecycle, the same collections are shown in the list of classes.
This means that there are multiple ways of scripting collections. For example, given a Certifications collection
with the attribute identifier of CERTS on the supplier object, a script can be written against the collection in
the following ways:
Caution
It is important that validation scripts are only created on either the Member or the Document,
never both. Data corruption can occur if validation scripts exist at both levels due to
interference in the database transaction.
An additional way to script the collection is the Document Validation Context on the supplier. Execute the
following to start operating on the collection:
ExtensionCollectionIfc certsCollection =
doc.getExtensionCollection(CERTS);
hasValue(Object object) Use this method to test for null, Only works for Java String type
or test that a SAP Sourcing and the following SAP Sourcing
object, though not null, has types:
some real value set. SimpleObjectRefenceIfc,
AmountIfc, PriceIfc,
AttachmentIfc,
EnumTypeIfc,
ResourceIdIfc,
SysDateIfc,
SysDatetimeIfc,
SysTimeIfc
getFieldValue() In Field and Field Data Edit Not normally used, as variable
scripts, returns the value of fieldValue accomplishes this
field
In developing a script, the developer must become familiar with the IAPI classes. These classes are listed in
JavaDoc format in the SAP Sourcing Reference Guide (RG).
Example
The following code samples are provided to illustrate exception features.
throw doc.createApplicationException(APPROVAL_SIG,
custom.exception.approval.required);
ae = new ApplicationException(session);
ae.chainAtEnd(doc.createApplicationException(APPROVAL_SIG,
custom.exception.approval.required));
Note
If a field level exception is thrown from a document context script, SAP Sourcing displays the
error twice: once under the field and once at the top of the document. This apparent bug is
actually a feature, because it allows a user to navigate around the document reviewing
potential dependencies that may have caused the error, without losing the actual error text.
There is no recommended way to suppress this output.
BeanShell does not enforce Caught Exception Handling per Java standards. If an exception is not caught
and it is not a ChainedApplicationException or a subclass, it is in a raw format, as shown in the
following figure.
As this format is not helpful to the end user, SAP recommends starting every script with a comment to
provide assistance in the event of an unexpected failure.
Example
The following is an example of a preceding comment:
/** An error occurred when validating the Display Name. Please contact
a system administrator */
Example
Alternatively, if the script or a dependent component is likely to fail, it may be better to inform
the user generically, as shown in the following example, and log the full exception in the system
log.
try {
myFailableCode();
} catch(e) {
Logger.error(Logger.createLogMessage(session).setException(e).setLogMe
ssage(My script failed));
throw new ApplicationException(session, custom.exception.error.id);
}
Note
Comments related to authorship and script intentions should not be included in the script. They
should be added to the Description field in the script definition.
Example
In the following example, SAP Sourcing presents the error in the language of the current users
session if the ID custom.exception.doc_desc.required is part of the bundle
exception and of the type ERROR. The value of this resource ID must be translated to the
relevant languages, or it is only displayed in the default language.
doc.createApplicationException(DOCUMENT_DESCRIPTION,
custom.exception.doc_desc.required);
Example
If an object does not expose an attribute, the value can still be obtained by using the field name
of the property, as in the following example.
Once the Home is obtained, it can be used to find an instance of the IBean. Note that the lookup methods
vary from IBean to IBean:
// Find by Account Object Reference
//
ownerEmail = userHome.find(doc.getDocumentOwnerUserReference());
Note
Standard logging is available for troubleshooting scripts. See Troubleshooting for details.
The following example indicates one way to incorporate a logging model for a script that may log in greater
volume due to its complexity:
// Create a log message and set the method to be the script event
//
log = Logger.createLogMessage(session);
log.setMethod(ProjectPrePhase);
try {
...
} catch(IOException e) {
logError(Could not write to the file, because of an IOError: +
e.getMessage() );
return;
}
You can also log the exception and raise a more understandable exception, as follows:
try {
<script>
} catch(e) {
Logger.error(Logger.createLogMessage(session).setException(e));
throw new ApplicationException (session, helpful message ID);
}
Occasionally, a lower-level SAP Sourcing function raises an exception without providing the underlying
cause in the exception message. This can happen when saving the IBean. In such a case, substitute the
following line:
Logger.error(Logger.createLogMessage(session).setException(e.getRootEx
ception() ));
See Handling Exceptions for further details on exception handling.
FIELDA = doc.getExtensionField(FIELDA).get();
FIELDB = doc.getExtensionField(FIELDB).get();
//
user = session.getAccount().getAccountObjectReference();
acct = IBeanHomeLocator.lookup(session, user).find(user);
colln = doc.getExtensionCollection("my_collection");
if(colln.size() == 0) {
return;
}
iter = colln.iterator();
for(member : iter) {
feildA = member.get("FIELDA");
if(!hasValue(feildA) ) {
exception.chainAtEnd(member.createApplicationException("FEILDA",
"exception.feild.is.required"));
}
}
From a scripting perspective, an absolute reference is needed when checking values, so value lists should
always be referenced by their internal identifier.
Note
In the UI for Value List Value Definition, this is labeled as Display Name, although this value is
not displayed to the user.
Value lists are often configured to give the display name the same value as the value list values default
resource ID. However, if the value list values are longer than 40 characters, the display name must be
abbreviated, so these values are not always identical.
// Is the Project Status completed?
// Field validation script on STATUS
STATUS_COMPLETED = "Completed";
// DO SOMETHING
}
if(hasValue(fieldValue) @and
fieldValue.getDisplayName().equals(STATUS_COMPLETED)) {
// DO SOMETHING
}
newLink = doc.getDocumentLinkList().create();
newLink.setDisplayName( rfx.getDisplayName() );
newLink.setLinkDate(TypeFactory.createSysDatetime(new
java.util.Date()));
...
// Check to make sure the Commodity (Int Cat) is not at the top level
//
if(!hasValue(fieldValue)) {
return;
}
if(!hasValue(categoryIBean.getParentObjRef()) ) {
throw doc.createApplicationException(field.getAttributeId(),
"custom.top_level_commodity_not_allowed");
}
Example
An example is a script that runs every night and checks if any master agreements are past
expiration. If they are past the expiration date, the script changes the status of the master
agreement to Expired.
To create a new Explicitly Called Script:
1. Choose Setup System Setup Integration Explicitly Called Script.
2. On the Explicitly Called Script page, choose the New button.
3. Enter the required information and your script and save your work.
To trigger the script:
1. Choose Setup System Setup Scheduled Tasks Scheduled Tasks.
2. Create a scheduled task of the type Explicitly Called Script Execution.
2.10 Troubleshooting
2.10.1 Script Logging
SAP Sourcing provides standard logging for scripts in Info mode, to allow you to access information without
turning on Debug mode. This information includes the date and time the script begins and ends and the
execution duration. When possible, the type of script, the object against which it is being executed, and any
system-set variables are also included in the log,
The log attribute debug_scope=scripting allows you to filter the log content to view script information.
3 Workflow
Workflow functionality in SAP Sourcing allows a business document to be submitted for approval to one or
more approvers. In a typical scenario, once a phase is reached with an assigned workflow definition, the
document is locked by the system. It can be released from this lock in the following ways:
The approvers approve or reject the document.
The workflow is deleted by use of the Workflow Processes Report found on the Workflow Definition
page.
The approvers action causes the workflows status to be evaluated and this may release the document from
workflow, generating any necessary emails. An approval outcome allows the document to continue to
advance to later phases; rejection only permits the document to regress phases.
Workflow is enabled on a number of documents. The functionality provided in this area is fixed by the
application to a large degree. However, scripting is used to customize the workflow by deciding which
approvers are added to the document.
SAP Sourcing provides an internal workflow editor for the creation of workflow process files. A workflow
process schema file defines the steps the workflow must go through and the scripts for adding the required
approvers at each step.
Workflow process files can also be created by importing an existing schema file.
The process of creating and assigning workflow definitions is described in this guide. For more detailed
information, see the SAP Sourcing Online Help.
Note
SAP Sourcing workflow provides legacy support for XPDL 1.0 files. Some XPDL files cannot
be edited using the internal workflow editor, but most can be imported and edited to generate a
new draft Workflow Process Template and corresponding SSWP file.
For more information, see Creating and Changing a Workflow Process Template in the SAP Sourcing Online
Help.
Workflow delegation is a feature available in the premium package for SAP Sourcing. This functionality may
not be available on all systems.
For more information and instructions on enabling workflow delegation, see the SAP Sourcing Online Help.
Note
A shaded icon (as in the Prescript example below) indicates that the script is populated. A white
icon (as in the Postscript and PreCancelScript examples below) indicates that the script is
blank.
Attribute Description
In addition to these scripts, there is a Global PreCancelScript available which serves the same purpose, and
will execute after any PreCancelScript of the workflow activity that the document was in at the time of
cancellation. Using the Global PreCancelScript is recommended if behavior should be the same for every
activity of a workflow process, so only one script needs to be maintained.
Attribute Description
Attribute Description
Variable Description
Note
Multiple contract documents in the same Master Agreement or subagreement should not have
active workflow processes at the same time, due to conflicts with the parent agreements
collaborator list.
recommended practice is to use extensions and extension collections to store this data. There are many
potential business documents for such data. The following are some examples:
Company
Organizational unit
Location
Document type
User account
Deciding which of these to use is part of the requirements analysis. For example, if rules are company-wide,
defining them at the enterprise company level is appropriate.
Because this functionality is based on business requirements and because scripting offers a great deal of
flexibility, workflow routing can be drawn from more than one of these locations. For example, if the owner of
the document (that is, User Account) is a supervisor, the value is between 0 and 100,000 USD, and the
document type is Recurring Agreement, add Group XXX as an approver. This can be represented in a
collection structured like the following table:
User Level Document Type Lower Limit Upper Limit Approval Group
The role of the script on the activity is to perform the four-way match by iterating over this collection and
adding the approval group. See Workflow Examples (page 32) for a similar scenario to this one.
Note
For this type, if you check the Automatically advance to first Status (Phase) Requiring Approval
checkbox, the phase should NOT be changed via scripting in the workflow process, even to the
Approved/Rejected phases. The behavior of this type is different from that of other workflow
types, which never advance the phase automatically.
4. On the Type page, assign a Supplier Configurable Phase Definition to the Supplier Type.
5. Save your entries.
Note
This is an important configuration step for enabling supplier workflow.
Configure two security templates: one for Workflow Supplier Registration and one for Workflow Supplier
Modification.
Note the following when creating the templates:
1. Open the supplier for which you want to reassign the supplier type.
2. Choose Edit.
3. Choose Document Type and select a new supplier type.
4. Choose OK.
5. Save your changes.
Note
When a supplier is created via workflow, the supplier type that was used for creation is
assigned to the supplier
/fsguestvendor/vendordesktop/register?ui=ui3
5. Save your entries.
Note
A self-registration form can be assigned to only one supplier type. If a form does not have an
assigned supplier type, the default supplier type will be used for registration.
3.8.1.1 Scenario - Iterate over a collection which contains the approval rules.
The main outcome from prescripts is to add an approver or not. In this case, a no match is not normal and
the workflow can be canceled. This can vary depending on business requirements.
// Get Document's Pertinent values. These attributes are all required
// so no need to check for null
//
projectContractValue = doc.getExtensionField("PROJ_VALUE").get();
cpSubGroup = doc.getExtensionField("PUR_GRP").get();
requestType = doc.getExtensionField("REQUEST_TYPE").get();
import
com.sap.odp.api.doc.collaboration.CollaboratorApprovalRuleType;
for(member : iterator) {
if(requestType.equals(member.get("REQUEST_TYPE")) @and
(cpSubGroup.equals(member.get("CP_SUB_GRP"))) ) {
if(projectContractValue.compareTo(member.get("FROM_VALUE"))
@gteq 0 @and
projectContractValue.compareTo(member.get("TO_VALUE")) @lteq 0) {
addApprover(member.get("APPROVER_GROUP"), new
CollaboratorApprovalRuleType(ANY));
found = true;
}
}
}
if(!found) {
cancelProcess("No routing data found for the values on the
Project");
}
3.8.2 Postscript
3.8.2.1 Scenario - End of Workflow Processing
The following script is implemented as postscript on the final activity. Its purpose is to advance the document
under workflow to the next phase and also to lock an amount field that is considered pivotal to the approval.
3.8.3 PreCancelScript
3.8.3.1 Scenario - When the workflow is rejected, or is manually canceled
When a script is canceled, such as is shown in the prescript example, the following example code regresses
the document back to draft phase. This can also be an approach in the postscript if the request was denied,
based on the business requirements.
doc.getIBeanHomeIfc().upgradeToEdit(doc);
home.changePhase(doc,"Request in Draft");
processHome = IBeanHomeLocator.lookup(session,
WorkflowProcessIBeanHomeIfc.sHOME_NAME);
process = processHome.findByNativeId(nativeId);
return process.getCreator();
submitter = getSubmitter();
A.3 Exceptions
Comment the top of the script with a failure message that describes where the script is
executing from.
Always use resource IDs for scripted exceptions.
Always use the objects method for creating exception on that object.
A.4 General
Do not use Internal APIs.
Do not access the database directly.
Only access objects from the home interface and even then, with utmost consideration to
system resources especially on methods like findWhere().
If indirectly accessing an object using getFieldMetadata( ), use the property field on the
IBean only.
If an attribute has no property field and the object does not have an IAPI, contact support to
request that it be added.
Crossgate, m@gic EDDY, B2B 360, and B2B 360 Services are registered trademarks of Crossgate AG in
Germany and other countries. Crossgate is an SAP company.
All other product and service names mentioned are the trademarks of their respective companies. Data
contained in this document serves informational purposes only. National product specifications may vary.
These materials are subject to change without notice. These materials are provided by SAP AG and its
affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any
kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only
warranties for SAP Group products and services are those that are set forth in the express warranty
statements accompanying such products and services, if any. Nothing herein should be construed as
constituting an additional warranty.